使用python解析nginx日志
性能测试时,需使用生产环境各接口请求比例分配接口请求比,nginx统计脚本如下:
import re
import pandas as pd
import xlwt obj = re.compile(
r'(?P<ip>.*?)- - \[(?P<time>.*?)\] "(?P<request>.*?)" (?P<request_time>.*?) (?P<status>.*?) (?P<bytes>.*?) "(?P<referer>.*?)" "(?P<ua>.*?)"') def load_log(path):
lst = []
error_lst = []
i = 0
with open(path, mode="r", encoding="utf-8") as f:
for line in f:
line = line.strip()
dic = parse(line)
if dic:
lst.append(dic)
else:
error_lst.append(line)
i += 1 return lst, error_lst def NumIn(s):
for char in s:
if char.isdigit():
return True
return False def parse(line):
dic = {}
try:
result = obj.match(line) time = result.group("time")
time = time.replace(" +0800", "")
time_min = time[:17]
time_10min = time[:16]
time_hour = time[:14]
dic['time'] = time
dic['time_min'] = time_min
dic['time_10min'] = time_10min
dic['time_hour'] = time_hour request = result.group("request")
a = request.split()[1].split("?")[0]
c = '/'.join(a.split('/')[:5])
b = request.split()[0]
for item in c.split('/')[4]:
if NumIn(item):
c='/'.join(a.split('/')[:4])
dic['request'] = b + " " + c return dic except:
return False def analyse(lst,project):
df = pd.DataFrame(lst)
df = df[df['request'].str.contains(project)]
request_time_count = pd.value_counts(df['time']).reset_index().rename(columns={"index": "time", "time": "count"}).iloc[:100, :]
request_time_min_count = pd.value_counts(df['time_min']).reset_index().rename(columns={"index": "time_min", "time_min": "count"}).iloc[:100, :]
request_time_10min_count = pd.value_counts(df['time_10min']).reset_index().rename(columns={"index": "time_10min", "time_10min": "count"}).iloc[:100, :]
request_time_hour_count = pd.value_counts(df['time_hour']).reset_index().rename(columns={"index": "time_hour", "time_hour": "count"}).iloc[:24, :]
request_count = pd.value_counts(df['request']).reset_index().rename(columns={"index": "request", "request": "count"}).iloc[:, :]
request_time_count_values = request_time_count.values
request_time_min_count_values = request_time_min_count.values
request_time_10min_count_values = request_time_10min_count.values
request_time_hour_count_values = request_time_hour_count.values
request_count_values = request_count.values wb = xlwt.Workbook() sheet = wb.add_sheet("url请求次数及占比")
row = 0
sheet.write(row, 0, "request_url")
sheet.write(row, 1, "request_type")
sheet.write(row, 2, "count")
sheet.write(row, 3, "百分比")
sheet.write(row, 4, "请求总数")
row += 1
sheet.write(row, 4, df.shape[0])
for item in request_count_values:
sheet.write(row, 0, item[0].split(" ")[1])
sheet.write(row, 1, item[0].split(" ")[0])
sheet.write(row, 2, item[1])
sheet.write(row, 3, "%.2f%%" % (round(float(item[1]/df.shape[0]) * 100, 2)))
row += 1 sheet = wb.add_sheet("秒级请求数top100") row = 0
sheet.write(row, 0, "time")
sheet.write(row, 1, "count")
row += 1
for item in request_time_count_values:
sheet.write(row, 0, item[0])
sheet.write(row, 1, item[1])
row += 1 sheet = wb.add_sheet("分钟请求数top100") row = 0
sheet.write(row, 0, "time_min")
sheet.write(row, 1, "count")
row += 1
for item in request_time_min_count_values:
sheet.write(row, 0, item[0]+':00'+"-"+item[0]+':59')
sheet.write(row, 1, item[1])
row += 1 sheet = wb.add_sheet("10分钟请求数top100") row = 0
sheet.write(row, 0, "time10")
sheet.write(row, 1, "count")
row += 1
for item in request_time_10min_count_values:
sheet.write(row, 0, item[0]+'0:00'+"-"+item[0]+'9:59')
sheet.write(row, 1, item[1])
row += 1 sheet = wb.add_sheet("小时级请求数") row = 0
sheet.write(row, 0, "timehour")
sheet.write(row, 1, "count")
row += 1
for item in request_time_hour_count_values:
sheet.write(row, 0, item[0]+':00:00'+"-"+item[0]+':59:59')
sheet.write(row, 1, item[1])
row += 1 wb.save("nginx_log.xls") if __name__ == '__main__':
lst, error_lst = load_log(path="D:\Desktop\\****imc.log")
analyse(lst,project='/SVC***/')
统计结果如下:

使用python解析nginx日志的更多相关文章
- python 解析nginx 日志 url
>>> import os>>> os.chdir('e:/')>>> log=open('access.log')//这两行是获取日志流> ...
- Python切割nginx日志_小组_ThinkSAAS
Python切割nginx日志_小组_ThinkSAAS Python切割nginx日志
- python解析Nginx访问日志
环境说明 python3+ pip install geoip2==2.9.0 nginx日志配置成json格式,配置如下: log_format json_log '{ "time&quo ...
- 利用python分析nginx日志
最近在学习python,写了个脚本分析nginx日志,练练手.写得比较粗糙,但基本功能可以实现. 脚本功能:查找出当天访问次数前十位的IP,并获取该IP来源,并将分析结果发送邮件到指定邮箱. 实现前两 ...
- 通过python统计nginx日志定位php网站响应慢的问题
# 公司网站反映很慢,可能是一些页面的访问方法或者页面引起,通过程序统计nginx访问日志的页面和具体的action方法访问次数以及平均响应时间可以为程序开发的同事提供参考定位具体的代码 # 默认的n ...
- Logstash使用grok插件解析Nginx日志
grok表达式的打印复制格式的完整语法是下面这样的: %{PATTERN_NAME:capture_name:data_type}data_type 目前只支持两个值:int 和 float. 在线g ...
- ELK+Redis 解析Nginx日志
一.ELK简介 Elk是指logstash,elasticsearch,kibana三件套,我们一般使用它们做日志分析. ELK工作原理图: 简单来讲ELK具体的工作流程就是客户端的logstash ...
- [日志分析]Graylog2进阶 通过正则解析Nginx日志
之前分享的 [日志分析]Graylog2采集Nginx日志 主动方式 这篇文章介绍了Graylog如何通过Graylog Collector Sidecar来采集nginx日志. 由于日志是未经处理的 ...
- Goaccess解析nginx日志备忘
参考 http://nginx.org/en/docs/http/ngx_http_log_module.html?&_ga=1.92028562.949762386.1481787781#l ...
- 使用Python 统计nginx日志前十ip访问量并以柱状图显示
脚本内容: import matplotlib.pyplot as plt # nginx_file = '10.6.11.91_access.log-2018-12-27' ip = {} #筛选n ...
随机推荐
- [GPT] 用dogecoin接受付款,如何实现收款回调,不借助中心化的第三方
要在不借助中心化的第三方的情况下实现Dogecoin的收款回调,您可以按照以下步骤进行操作: 1. 设置一个用于接收收款回调的URL:您需要在您的网站或应用程序中设置一个用于接收收款回调的URL. ...
- [PHP] 浅谈 Laravel Authorization 的 gates 与 policies
首先要区分 Authentication 与 Authorization,认证和授权,粗细有别. 授权(Authorization) 有两种主要方式,Gates 和 Policies. Gates 和 ...
- dotnet C# 基础 为什么 GetHashCode 推荐只取只读属性或字段做哈希值
在 C# 里面,所有的对象都继承 Object 类型,此类型有开放 GetHashCode 用于给开发者重写.此 GetHashCode 方法推荐是在重写 Equals 方法时也同时进行重写,要求两个 ...
- Codeforces Round #922 (Div. 2) ABCD
A. Brick Wall 很直白的贪心,显然就是全放横着的砖最优,每行中最多能放 \(\lfloor \dfrac{m}{2} \rfloor\) 个,答案为 \(n \cdot \lfloor \ ...
- dotnet build error CS5001: Program does not contain a static 'Main' method suitable for an entry point
前言 Docker环境编译.Net6项目,出现诡异的CS5001 Program does not contain a static 'Main' method suitable for an ent ...
- 【python爬虫案例】用python爬豆瓣音乐TOP250排行榜!
目录 一.爬虫对象-豆瓣音乐TOP250 二.python爬虫代码讲解 三.同步视频 四.获取完整源码 一.爬虫对象-豆瓣音乐TOP250 今天我们分享一期python爬虫案例讲解.爬取对象是,豆瓣音 ...
- C# 实现Ping远程主机功能
C#实现Ping远程主机功能. 1.引用nuget包 Wesky.Net.OpenTools OpenTools是一个用于提高开发效率的开源工具库.该项目为个人开源项目,采用MIT开源协议,永不更改协 ...
- istio sidecar 工作方式
istio 是什么 Istio 是一个开放源代码的服务网格,它为基于微服务的应用程序提供了一种统一的方式来连接.保护.监控和管理服务.Istio 主要解决的是在微服务架构中的服务间通信的复杂性问题,它 ...
- C数据结构:树和森林存储方式与遍历方式
文章目录 树的存储方式 双亲表示法 孩子链表表示法 孩子兄弟表示法(二叉树表示法) 树和二叉树的转换 森林和二叉树的转换 树和森林的遍历 树的遍历方式 森林的遍历方式 浅谈一下几个问题 为什么树没有中 ...
- 内网渗透 Metasploit(MSF)基础使用
免责申明 以下内容仅供学习使用,非法使用造成的问题由使用人承担 攻击思路 漏洞探测(信息收集) <- fsacn,namp | 漏洞利用 <- 工具(msf等) | 获取服务器权限 MSF ...