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

yipeiwu_com7年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

使用pygame模块编写贪吃蛇的实例讲解

python ### 刚学了python不久,发现了一个好玩的库pygame 使用pygame模块 利用面向对象的思想编写贪吃蛇,主要用到pygame.sprite: 游戏主类 im...

Python 基于wxpy库实现微信添加好友功能(简洁)

Python 基于wxpy库实现微信添加好友功能(简洁)

Github:https://github.com/Lyo-hub/wxpy_AddFriend 本程序为基于wxpy库实现的。 1.打开cmd导入一下库。 2.修改库文件中ad...

基于pandas数据样本行列选取的方法

注:以下代码是基于python3.5.0编写的 import pandas food_info = pandas.read_csv("food_info.csv") # ------...

Windows下python2.7.8安装图文教程

Windows下python2.7.8安装图文教程

本文为大家分享了python2.7.8安装图文教程,供大家参考,具体内容如下 1、进入python的官方网站下载:https://www.python.org/,点击Download,选...

django自带serializers序列化返回指定字段的方法

django orm 有个defer方法,指定模型排除的字段。 如下返回的Queryset, 排除‘username', 'id'。 users=models.UserInfo.ob...