博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python 日志处理(一) 按Nginx log_format 分割日志记录
阅读量:4622 次
发布时间:2019-06-09

本文共 1967 字,大约阅读时间需要 6 分钟。

要求:不使用正则

根据nginx 默认的日志记录格式,分割日志记录。

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '                      '$status $body_bytes_sent "$http_referer" '                      '"$http_user_agent" "$http_x_forwarded_for"';

  日志记录先后顺序:

访客IP - 访客用户 请求时间 请求URL 状态码 响应字节大小 访问来源 浏览器标识 转发标识

  单行日志:

183.60.212.153 - - [19/Feb/2013:10:23:29 +0800] "GET /o2o/media.html?menu=3 HTTP/1.1" 200 16691 "-" "Mozilla/5.0 (compatible; EasouSpider; +http://www.easou.com/search/spider.html)"

  本次只处理单行,单行处理可以了就可以应用于大文件日志分析。

  

每个字段特殊情况:

183.60.212.153    #不以" 或 [/] 开头结尾

[19/Feb/2013:10:23:29 +0800]   #以 [ 开头 ] 结尾
"GET /o2o/media.html?menu=3 HTTP/1.1"   #以 " 开头 " 结尾1
"-"   #以 " 开头 " 结尾但只有一个字符
"Mozilla/5.0 (compatible; EasouSpider; +http://www.easou.com/search/spider.html)"  #以 " 开头 " 结尾2

 

 

logline = '''183.60.212.153 - - [19/Feb/2013:10:23:29 +0800] "GET /o2o/media.html?menu=3 HTTP/1.1" 200 16691 "-" "Mozilla/5.0 (compatible; EasouSpider; +http://www.easou.com/search/spider.html)"'''fields = logline.split()flag = Falsetmp = ''lst = []for word in fields:    if not flag:  # if flag == False        if word.startswith('[') or word.startswith('"'):            if word.endswith(']') or word.endswith('"'):  # "-"                tmp = word.strip('[]"')                lst.append(tmp)            else:  # '[19/Feb/2013:10:23:29',                tmp = word[1:]                flag = True        else:            lst.append(word)        continue    if flag:  # '+0800]'        if word.endswith(']') or word.endswith('"'):            tmp += ' ' + word[:-1]  # '19/Feb/2013:10:23:29 +0800'            lst.append(tmp)            tmp = ''            flag = False        else:            tmp += ' ' + wordprint(lst)

  

  输出结果:

['183.60.212.153', '-', '-', '19/Feb/2013:10:23:29 +0800', 'GET /o2o/media.html?menu=3 HTTP/1.1', '200', '16691', '-', 'Mozilla/5.0 (compatible; EasouSpider; +http://www.easou.com/search/spider.html)']

  

转载于:https://www.cnblogs.com/i-honey/p/7782417.html

你可能感兴趣的文章
Socket & TCP &HTTP
查看>>
osip及eXosip的编译方法
查看>>
Hibernate composite key
查看>>
[CF Round #294 div2] D. A and B and Interesting Substrings 【Map】
查看>>
keepalived+nginx安装配置
查看>>
我的2015---找寻真实的自己
查看>>
android编译遇到问题修改
查看>>
解决Ubuntu18.04.2远程桌面Xrdp登录蓝屏问题
查看>>
Git的安装和使用教程详解
查看>>
lsof命令详解
查看>>
常用模块,异常处理
查看>>
父窗口与子窗口之间的传值
查看>>
eclipse 找不到 tomcat 的解决方案
查看>>
HDU 1890--Robotic Sort(Splay Tree)
查看>>
connection string for Excel/Access 2010
查看>>
【转】【Python】Python中的__init__.py与模块导入(from import 找不到模块的问题)
查看>>
学习wavenet_vocoder之环境配置
查看>>
常用Maven命令
查看>>
Docker启动mysql的坑2
查看>>
j2ee爬坑行之二 servlet
查看>>