收藏消零派 会飞的小科,编号144

Pandas完成日志统计分析

2022-01-28  本文已影响0人  刘小白DOER

    Pandas是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的,提供了大量能快速便捷地处理数据的函数和方法。最近使用pandas将一些运维日志提取出来做一些分析,一是作为工作量分析,优化流程;二是通过日志查看故障率,找到薄弱环节。在前期的实践中,数据告诉你怎么干掉琐事,笔者使用jieba分词和wordcloud词云图来完成日志的云图显示。现在做一些类别统计和关键字统计。

    使用pandas完成csv日志文件读取,并定义一个红色打印输出函数。

df = pd.read_csv('events.csv')

def red_print(string):

    print("\033[0;31;40m{0}\033[0m".format(string))

1、类别统计

  value_counts()函数可以统计Categroy字段的重复个数,然后利用matplotlib绘制bar图。

event_categroy_counts = df.Categroy.value_counts()

red_print("事件类别统计信息:")

print(event_categroy_counts)

names = list(event_categroy_counts.index)

percents = [item/len(df)*100 for item in event_categroy_counts.values]

plt.rcParams['font.sans-serif'] = ['simhei'] 

#plt.figure(dpi=180)

plt.figure(figsize=[11,8])

plt.bar(names,percents,color='green')

plt.ylabel("类别信息百分比(%)", fontproperties='SimHei', rotation=90, size=12)

plt.title("事件类别统计Percent", size=16)

plt.xticks(list(names), rotation=50, size=12)

red_print("生成png文件-事件类别统计信息.png")

plt.savefig("事件类别统计信息.png") 

2、关键字统计

    df.str.contains()函数搜索包含特定字符串的数据,笔者按照"debug_log ","info_log","warning_log","error_log"来进行搜索日志,然后利用matplotlib绘制bar图,实现不同log所需占比例显示。

debug_log = len(df[df.str.contains("debug_log")==True])

info_log= len(df[df.str.contains("info_log")==True])

warning_log= len(df[df.str.contains("warning_log")==True])

error_log= len(df[df.str.contains("error_log")==True])

critical_log= len(df[df.str.contains("critical_log")==True])

names = ["debug_log ","info_log","warning_log","error_log"]

numbers = [debug_log ,info_log,warning_log,error_log]

numbers_percent = [item/len(df)*100 for item in numbers]

plt.rcParams['font.sans-serif'] = ['simhei'] 

plt.figure(figsize=[10,6])

#plt.bar(names,numbers,color='green')

plt.bar(names,numbers_percent,color='green')

plt.ylabel("关键字百分比(%)", fontproperties='SimHei', rotation=90, size=12)

plt.title("关键字统计Percent", size=16)

plt.xticks(list(names), rotation=90, size=12)

red_print("生成png文件-关键字统计bar.png")

plt.savefig("关键字事件统计bar.png") 

上一篇 下一篇

猜你喜欢

热点阅读