python+pandas分析nginx日志的实例
作者:man8er 发布时间:2021-03-13 12:51:22
标签:python,nginx,日志,pandas
需求
通过分析nginx访问日志,获取每个接口响应时间最大值、最小值、平均值及访问量。
实现原理
将nginx日志uriuriupstream_response_time字段存放到pandas的dataframe中,然后通过分组、数据统计功能实现。
实现
1.准备工作
#创建日志目录,用于存放日志
mkdir /home/test/python/log/log
#创建文件,用于存放从nginx日志中提取的$uri $upstream_response_time字段
touch /home/test/python/log/log.txt
#安装相关模块
conda create -n science numpy scipy matplotlib pandas
#安装生成execl表格的相关模块
pip install xlwt
2.代码实现
#!/usr/local/miniconda2/envs/science/bin/python
#-*- coding: utf-8 -*-
#统计每个接口的响应时间
#请提前创建log.txt并设置logdir
import sys
import os
import pandas as pd
mulu=os.path.dirname(__file__)
#日志文件存放路径
logdir="/home/test/python/log/log"
#存放统计所需的日志相关字段
logfile_format=os.path.join(mulu,"log.txt")
print "read from logfile \n"
for eachfile in os.listdir(logdir):
logfile=os.path.join(logdir,eachfile)
with open(logfile, 'r') as fo:
for line in fo:
spline=line.split()
#过滤字段中异常部分
if spline[6]=="-":
pass
elif spline[6]=="GET":
pass
elif spline[-1]=="-":
pass
else:
with open(logfile_format, 'a') as fw:
fw.write(spline[6])
fw.write('\t')
fw.write(spline[-1])
fw.write('\n')
print "output panda"
#将统计的字段读入到dataframe中
reader=pd.read_table(logfile_format,sep='\t',engine='python',names=["interface","reponse_time"] ,header=None,iterator=True)
loop=True
chunksize=10000000
chunks=[]
while loop:
try:
chunk=reader.get_chunk(chunksize)
chunks.append(chunk)
except StopIteration:
loop=False
print "Iteration is stopped."
df=pd.concat(chunks)
#df=df.set_index("interface")
#df=df.drop(["GET","-"])
df_groupd=df.groupby('interface')
df_groupd_max=df_groupd.max()
df_groupd_min= df_groupd.min()
df_groupd_mean= df_groupd.mean()
df_groupd_size= df_groupd.size()
#print df_groupd_max
#print df_groupd_min
#print df_groupd_mean
df_ana=pd.concat([df_groupd_max,df_groupd_min,df_groupd_mean,df_groupd_size],axis=1,keys=["max","min","average","count"])
print "output excel"
df_ana.to_excel("test.xls")
3.打印的表格如下:
要点
1. 日志文件比较大的情况下读取不要用readlines()、readline(),会将日志全部读到内存,导致内存占满。因此在此使用for line in fo迭代的方式,基本不占内存。
2. 读取nginx日志,可以使用pd.read_table(log_file, sep=' ‘, iterator=True),但是此处我们设置的sep无法正常匹配分割,因此先将nginx用split分割,然后再存入pandas。
3. Pandas提供了IO工具可以将大文件分块读取,使用不同分块大小来读取再调用 pandas.concat 连接DataFrame
来源:https://blog.csdn.net/yanggd1987/article/details/69542669


猜你喜欢
- 首先,你要知道pycharm可以通过ssh链接到远程服务器,并且也能够用pycharm运行远程服务器的代码。可以参考https://www.
- 我们先把数据表建好use test;create table `employee`( emp_no int unsigned, emp_na
- 最近学习javascript,碰到caller和callee的问题,去网上百度了很多。搜到的内容大同小益,整理总结了一下与大家分享。call
- 矩阵增加行np.row_stack() 与 np.column_stack()import numpy as npa = np.array(
- 你是否曾经想在数据库中存储一个日期而没有时间部分,或者想存储一个时间值希望有更高的精度?在SQL Server 2008的介绍中,微软介绍了
- 1创建窗口1 turtle.setup(width,height,startx,starty)设置主窗口的大小和位置,width如果是整数,
- 因为要将js的一个签名算法移植到python上,遇到一些麻烦。int无限宽度,不会溢出算法中需要用到了32位int的溢出来参与运算,但是py
- 本文实例为大家分享了Pyqt实现无边框窗口拖动及大小改变的具体代码,供大家参考,具体内容如下做个记录,绘制边框阴影可以忽略这里不是主要根据网
- super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类
- 此版本是始终只有最新的一版(我自己的用的是版本是每天都有一个备份) declare @DBName varchar(200) set @DB
- 今天比较忙,水一下下面的代码来源于这个视频里面提到的,github 的链接为:github.com/mikeckenned…(本地下载)第一
- 方法一: 1、打开查询分析器,输入命令 BACKUP LOG database_name WITH NO_LOG 2、再打开企业管理器--右
- 一、yield使用简析yield是一个生成器generator,返回一个interable对象。该对象具有next()方法,可以通过next
- 请定义函数,将列表[10, 1, 2, 20, 10, 3, 2, 1, 15, 20, 44, 56, 3, 2, 1]中的重复元素除去,
- 连接mysql#!/usr/bin/python#-*- coding:utf-8 -*-import timeimport pymysql
- 1.文件介绍python操作文件1.1python文件的基本操作打开文件关键字open语法格式:open('文件路径',
- 在.net 1.1中我们要实现压缩这一功能,一般都是用open source的SharpZipLib 或者调用
- python中return的用法1、return语句就是把执行结果返回到调用的地方,并把程序的控制权一起返回程序运行到所遇到的第一个retu
- 不加(0)的用法:set rs=conn.execute(sql)'将这个结果赋给rs这时要读取这个记录集第一个字段的数据就用rs(
- 需要用到2个库,requestsocks5-http-client/lib/Agent/或socks5-https-client/lib/A