python分析nignx访问日志脚本分享


Posted in Python onFebruary 26, 2015
#!/usr/bin/env python 
# coding=utf-8 
 
#------------------------------------------------------ 
# Name:     nginx 日志分析脚本 
# Purpose:   此脚本只用来分析nginx的访问日志 
# Version:   1.0 
# Author:    LEO 
# Created:   2013-05-07 
# Modified:   2013-05-07 
# Copyright:  (c) LEO 2013 
#------------------------------------------------------ 
 
import sys 
import time 
 
#该类是用来打印格式 
class displayFormat(object): 
 
  def format_size(self,size): 
    '''''格式化流量单位''' 
    KB = 1024      #KB -> B B是字节 
    MB = 1048576    #MB -> B 
    GB = 1073741824   #GB -> B 
    TB = 1099511627776 #TB -> B 
    if size >= TB : 
      size = str(size / TB) + 'T' 
    elif size < KB : 
      size = str(size) + 'B' 
    elif size >= GB and size < TB: 
      size = str(size / GB) + 'G' 
    elif size >= MB and size < GB : 
      size = str(size / MB) + 'M' 
    else : 
      size = str(size / KB) + 'K' 
    return size 
 
  #定义字符串格式化 
  formatstring = '%-15s %-10s %-12s %8s %10s %10s %10s %10s %10s %10s %10s' 
 
  def transverse_line(self) : 
    '''''输出横线''' 
    print self.formatstring % ('-'*15,'-'*10,'-'*12,'-'*12,'-'*10,'-'*10,'-'*10,'-'*10,'-'*10,'-'*10,'-'*10) 
 
  def head(self): 
    '''''输出头部信息''' 
    print self.formatstring % ('IP','Traffic','Times','Times%','200','404','500','403','302','304','503') 
 
  def error_print(self) : 
    '''''输出错误信息''' 
    print 
    print 'Usage : ' + sys.argv[0] + ' NginxLogFilePath [Number]' 
    print 
    sys.exit(1) 
 
  def execut_time(self): 
    '''''输出脚本执行的时间''' 
    print 
    print "Script Execution Time: %.3f second" % time.clock() 
    print 
 
#该类是用来生成主机信息的字典 
class hostInfo(object): 
  host_info = ['200','404','500','302','304','503','403','times','size'] 
 
  def __init__(self,host): 
    self.host = host = {}.fromkeys(self.host_info,0) 
 
  def increment(self,status_times_size,is_size): 
    '''''该方法是用来给host_info中的各个值加1''' 
    if status_times_size == 'times': 
      self.host['times'] += 1 
    elif is_size: 
      self.host['size'] = self.host['size'] + status_times_size 
    else: 
      self.host[status_times_size] += 1 
 
  def get_value(self,value): 
    '''''该方法是取到各个主机信息中对应的值''' 
    return self.host[value] 
 
#该类是用来分析文件 
class fileAnalysis(object): 
  def __init__(self): 
    '''''初始化一个空字典''' 
    self.report_dict = {} 
    self.total_request_times,self.total_traffic,self.total_200, 
    self.total_404,self.total_500,self.total_403,self.total_302, 
    self.total_304,self.total_503 = 0,0,0,0,0,0,0,0,0 
 
  def split_eachline_todict(self,line): 
    '''''分割文件中的每一行,并返回一个字典''' 
    split_line = line.split() 
    split_dict = {'remote_host':split_line[0],'status':split_line[8], 
           'bytes_sent':split_line[9],} 
    return split_dict 
 
  def generate_log_report(self,logfile): 
    '''''读取文件,分析split_eachline_todict方法生成的字典''' 
    for line in logfile: 
      try: 
        line_dict = self.split_eachline_todict(line) 
        host = line_dict['remote_host'] 
        status = line_dict['status'] 
      except ValueError : 
        continue 
      except IndexError : 
        continue 
 
      if host not in self.report_dict : 
        host_info_obj = hostInfo(host) 
        self.report_dict[host] = host_info_obj 
      else : 
        host_info_obj = self.report_dict[host] 
 
      host_info_obj.increment('times',False) 
      if status in host_info_obj.host_info : 
        host_info_obj.increment(status,False) 
      try: 
        bytes_sent = int(line_dict['bytes_sent']) 
      except ValueError: 
        bytes_sent = 0 
      host_info_obj.increment(bytes_sent,True) 
    return self.report_dict 
 
  def return_sorted_list(self,true_dict): 
    '''''计算各个状态次数、流量总量,请求的总次数,并且计算各个状态的总量 并生成一个正真的字典,方便排序''' 
    for host_key in true_dict : 
      host_value = true_dict[host_key] 
      times = host_value.get_value('times')            
      self.total_request_times = self.total_request_times + times 
      size = host_value.get_value('size')            
      self.total_traffic = self.total_traffic + size  
 
      o200 = host_value.get_value('200') 
      o404 = host_value.get_value('404') 
      o500 = host_value.get_value('500') 
      o403 = host_value.get_value('403') 
      o302 = host_value.get_value('302') 
      o304 = host_value.get_value('304') 
      o503 = host_value.get_value('503') 
 
      true_dict[host_key] = {'200':o200,'404':o404,'500':o500, 
                  '403':o403,'302':o302,'304':o304, 
                  '503':o503,'times':times,'size':size} 
 
      self.total_200 = self.total_200 + o200 
      self.total_404 = self.total_404 + o404 
      self.total_500 = self.total_500 + o500 
      self.total_302 = self.total_302 + o302 
      self.total_304 = self.total_304 + o304 
      self.total_503 = self.total_503 + o503 
 
    sorted_list = sorted(true_dict.items(),key=lambda t:(t[1]['times'],
                               t[1]['size']),reverse=True) 
 
    return sorted_list 
 
class Main(object): 
  def main(self) : 
    '''''主调函数''' 
    display_format = displayFormat() 
    arg_length = len(sys.argv) 
    if arg_length == 1 : 
      display_format.error_print() 
    elif arg_length == 2 or arg_length == 3: 
      infile_name = sys.argv[1] 
      try : 
        infile = open(infile_name,'r') 
        if arg_length == 3 : 
          lines = int(sys.argv[2]) 
        else : 
          lines = 0 
      except IOError,e : 
        print 
        print e 
        display_format.error_print() 
      except ValueError : 
        print 
        print "Please Enter A Volid Number !!" 
        display_format.error_print() 
    else : 
      display_format.error_print() 
 
    fileAnalysis_obj = fileAnalysis() 
    not_true_dict = fileAnalysis_obj.generate_log_report(infile) 
    log_report = fileAnalysis_obj.return_sorted_list(not_true_dict) 
    total_ip = len(log_report) 
    if lines : 
      log_report = log_report[0:lines] 
    infile.close() 
 
    print 
    total_traffic = display_format.format_size(fileAnalysis_obj.total_traffic) 
    total_request_times = fileAnalysis_obj.total_request_times 
    print 'Total IP: %s  Total Traffic: %s  Total Request Times: %d' 
       % (total_ip,total_traffic,total_request_times) 
    print 
    display_format.head() 
    display_format.transverse_line() 
 
    for host in log_report : 
      times = host[1]['times'] 
      times_percent = (float(times) / float(fileAnalysis_obj.total_request_times)) * 100 
      print display_format.formatstring % (host[0],
                         display_format.format_size(host[1]['size']),
                         times,str(times_percent)[0:5],
                         host[1]['200'],host[1]['404'],
                         host[1]['500'],host[1]['403'],
                         host[1]['302'],host[1]['304'],host[1]['503']) 
                         
    if (not lines) or total_ip == lines : 
      display_format.transverse_line() 
      print display_format.formatstring % (total_ip,total_traffic, 
                         total_request_times,'100%',
                         fileAnalysis_obj.total_200,
                         fileAnalysis_obj.total_404,
                         fileAnalysis_obj.total_500, 
                         fileAnalysis_obj.total_403,
                         fileAnalysis_obj.total_302, 
                         fileAnalysis_obj.total_304,
                         fileAnalysis_obj.total_503) 
 
    display_format.execut_time() 
 
if __name__ == '__main__': 
  main_obj = Main() 
  main_obj.main()
Python 相关文章推荐
python+selenium识别验证码并登录的示例代码
Dec 21 Python
python3下实现搜狗AI API的代码示例
Apr 10 Python
解决python3 Pycharm上连接数据库时报错的问题
Dec 03 Python
简单了解python的内存管理机制
Jul 08 Python
Python的缺点和劣势分析
Nov 19 Python
在notepad++中实现直接运行python代码
Dec 18 Python
CentOS7下安装python3.6.8的教程详解
Jan 03 Python
python实现串口通信的示例代码
Feb 10 Python
详解用Pytest+Allure生成漂亮的HTML图形化测试报告
Mar 31 Python
Python实现播放和录制声音的功能
Aug 12 Python
Python正则re模块使用步骤及原理解析
Aug 18 Python
Alpine安装Python3依赖出现的问题及解决方法
Dec 25 Python
python分析apache访问日志脚本分享
Feb 26 #Python
Python构造函数及解构函数介绍
Feb 26 #Python
python中的__slots__使用示例
Feb 26 #Python
Python map和reduce函数用法示例
Feb 26 #Python
Python中运行并行任务技巧
Feb 26 #Python
Python通过递归遍历出集合中所有元素的方法
Feb 25 #Python
Python THREADING模块中的JOIN()方法深入理解
Feb 18 #Python
You might like
jscript之Open an Excel Spreadsheet
2007/06/13 Javascript
JavaScript 动态创建VML的方法
2009/10/14 Javascript
js禁止document element对象选中文本实现代码
2013/03/21 Javascript
js中的数组Array定义与sort方法使用示例
2013/08/29 Javascript
Javascript中Event属性搜集整理
2013/09/17 Javascript
让复选框只能选择一项的方法
2013/10/08 Javascript
jquery实现搜索框常见效果的方法
2015/01/22 Javascript
javascript判断并获取注册表中可信任站点的方法
2015/06/01 Javascript
日常收集整理的JavaScript常用函数方法
2015/12/10 Javascript
js时间戳转为日期格式的方法
2015/12/28 Javascript
JavaScript表单验证实例之验证表单项是否为空
2016/01/10 Javascript
javascript实现倒计时跳转页面
2016/01/17 Javascript
js阻止冒泡和默认事件(默认行为)详解
2016/10/20 Javascript
RGB和YUV 多媒体编程基础详细介绍
2016/11/04 Javascript
JavaScript中捕获与冒泡详解及实例
2017/02/03 Javascript
JavaScript数据结构学习之数组、栈与队列
2017/05/02 Javascript
浅谈JS中的常用选择器及属性、方法的调用
2017/07/28 Javascript
什么是Vue.js框架 为什么选择它?
2017/10/17 Javascript
vue中根据时间戳判断对应的时间(今天 昨天 前天)
2019/12/20 Javascript
JQuery中DOM节点的操作与访问方法实例分析
2019/12/23 jQuery
haskell实现多线程服务器实例代码
2013/11/26 Python
让python在hadoop上跑起来
2016/01/27 Python
python实现rsa加密实例详解
2017/07/19 Python
解决python3.5 正常安装 却不能直接使用Tkinter包的问题
2019/02/22 Python
Python通过TensorFLow进行线性模型训练原理与实现方法详解
2020/01/15 Python
浅谈Tensorflow 动态双向RNN的输出问题
2020/01/20 Python
python设置环境变量的作用整理
2020/02/17 Python
澳大利亚巧克力花束和礼品网站:Tastebuds
2019/03/15 全球购物
实习生体会的自我评价范文
2013/11/28 职场文书
城市轨道交通工程职业生涯规划书范文
2014/09/16 职场文书
指导老师鉴定意见
2015/06/05 职场文书
个人合作协议范本
2015/08/06 职场文书
入党宣誓大会后的感想
2015/08/10 职场文书
Java9新特性之Module模块化编程示例演绎
2022/03/16 Java/Android
PostgreSQL事务回卷实战案例详析
2022/03/25 PostgreSQL