python—分析日志

分析日志

需求

  • 简单分析日志文件中两个时间差.
  • 计算平均值,中位数,方差等.
  • 图形化展示.

分析

  • 用到的功能

    • 系统io,只需要按行读入即可,当然需要指定gbk编码
    • 科学计算的函数库
    • 简单的画图库
  • python库

    • 系统的 io 库即可
    • numpy 库,大材小用
    • matplotlib.pyplot,大材小用

示例

  • 按行读入

    1
    2
    3
    4
    5
    6
    7
    8
    9
    with open(path,encoding='gbk') as f:
    for number, line in enumerate(f):
    #去空格
    line = line.strip().replace(' ','')
    #匹配字符串
    try:
    ln1 = line.index(str1)
    except ValueError as e:
    ln1 = 1
  • 得到一个list 统计

    1
    2
    3
    4
    5
    print("数量",len(time))
    print("平均值",np.mean(time))
    print("最大值",np.max(time))
    print("最小值",np.min(time))
    print("方差",np.var(time))
  • 画图

    1
    2
    3
    4
    5
    6
    7
    #格式化转化为时间
    for ts in x :
    tx.append(datetime.datetime.fromtimestamp(ts/1000))

    plt.plot(tx,time)
    plt.title('len%d, mean%d, max%d, min%d' % (len(time),np.mean(time),np.max(time),np.min(time))) # 添加图形标题
    plt.show()