您的位置:首页 > 运维架构 > Nginx

python实现的分析并统计nginx日志数据功能示例

2019-12-22 07:05 3815 查看

本文实例讲述了python实现的分析并统计nginx日志数据功能。分享给大家供大家参考,具体如下:

利用python脚本分析nginx日志内容,默认统计ip、访问url、状态,可以通过修改脚本统计分析其他字段。

一、脚本运行方式

python count_log.py -f med.xxxx.com.access.log

二、脚本内容

#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
1.分析日志,每行日志按空格切分,取出需要统计的相应字段,作为字典的key,遍历相加
2.使用到字典的get方法,通过定义默认值,避免miss key的错误
3.使用列表解析表达式
4.使用sorted函数排序列表
5.使用argparse传入参数
6.nginx日志格式:
log_format     access_log
'$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$request_time"' '"$upstream_addr"' '"$upstream_response_time"';
7.日志内容:
222.xx.xxx.15 - - [07/Dec/2016:00:03:27 +0800] GET /app/xxx/xxx.apk HTTP/1.0 "304" 0 "-" "Mozilla/5.0 Gecko/20100115 Firefox/3.6" "0.055""-""-"
8.脚本运行结果:
('106.xx.xx.46', '/gateway/xxx/user/mxxxxx/submitSelfTestOfSingleQuestion', '"200"', 299)
('182.1xx.xx.83', '/', '"200"', 185)
('222.xx.1xx.15', '/', '"200"', 152)
('125.xx.2xx.58', '/', '"200"', 145)
"""
import argparse
def count_log(filename, num):
try:
with open(filename) as f:
dic = {}
for l in f:
if not l == '\n': # 判断空白行
arr = l.split(' ')
ip = arr[0]
url = arr[6]
status = arr[8]
# 字典的key是有多个元素构成的元组
# 字典的get方法,对取的key的值加1,第一次循环时由于字典为空指定的key不存在返回默认值0,因此读第一行日志时,统计结果为1
dic[(ip, url, status)] = dic.get((ip, url, status), 0) + 1
# 从字典中取出key和value,存在列表中,由于字典的key比较特殊是有多个元素构成的元组,通过索引k[#]的方式取出key的每个元素
dic_list = [(k[0], k[1], k[2], v) for k, v in dic.items()]
for k in sorted(dic_list, key=lambda x: x[3], reverse=True)[:num]:
print(k)
except Exception as e:
print("open file error:", e)
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="传入日志文件")
# 定义必须传入日志文件,使用格式-f filename
parser.add_argument('-f', action='store', dest='filename', required=True)
# 通过-n传入数值,取出最多的几行,默认取出前10
parser.add_argument('-n', action='store', dest='num', type=int, required=False, default=10)
given_args = parser.parse_args()
filename = given_args.filename
num = given_args.num
count_log(filename, num)

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python日志操作技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

希望本文所述对大家Python程序设计有所帮助。

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python nginx日志