使用Python 分析Nginx access 日志,根據Nginx日志格式進行分割并存入MySQL數據庫。
一、Nginx access日志格式如下:
代碼如下:
$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"' #使用的是nginx默認日志格式
二、Nginx access 日志內容如下:
代碼如下:
182.19.31.129 - - [2013-08-13T00:00:01-07:00] "GET /css/anniversary.css HTTP/1.1" 304 0 "http://www.chlinux.net/" "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36" "-"
三、下面是Python 分析nginx日志的Python代碼:
代碼如下:#!/usr/bin/env python
#coding:utf8
import os
import fileinput
import re
import sys
import MySQLdb
#日志的位置
logfile=open("access_20130812.log")
#使用的nginx默認日志格式$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'
#日志分析正則表達式
#203.208.60.230
ipP = r"?P<ip>[/d.]*"
#以[開始,除[]以外的任意字符 防止匹配上下個[]項目(也可以使用非貪婪匹配*?) 不在中括號里的.可以匹配換行外的任意字符 *這樣地重復是"貪婪的“ 表達式引擎會試著重復盡可能多的次數。#以]結束
#[21/Jan/2011:15:04:41 +0800]
timeP = r"""?P<time>/[[^/[/]]*/]"""
#以"開始, #除雙引號以外的任意字符 防止匹配上下個""項目(也可以使用非貪婪匹配*?),#以"結束
#"GET /EntpShop.do?method=view&shop_id=391796 HTTP/1.1"
#"GET /EntpShop.do?method=view&shop_id=391796 HTTP/1.1"
requestP = r"""?P<request>/"[^/"]*/""""
statusP = r"?P<status>/d+"
bodyBytesSentP = r"?P<bodyByteSent>/d+"
#以"開始, 除雙引號以外的任意字符 防止匹配上下個""項目(也可以使用非貪婪匹配*?),#以"結束
#"http://test.myweb.com/myAction.do?method=view&mod_id=&id=1346"
referP = r"""?P<refer>/"[^/"]*/""""
#以"開始, 除雙引號以外的任意字符 防止匹配上下個""項目(也可以使用非貪婪匹配*?),以"結束
#"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userAgentP = r"""?P<userAgent>/"[^/"]*/""""
#以(開始, 除雙引號以外的任意字符 防止匹配上下個()項目(也可以使用非貪婪匹配*?),以"結束
#(compatible; Googlebot/2.1; +http://www.google.com/bot.html)"'
userSystems = re.compile(r'/([^/(/)]*/)')
#以"開始,除雙引號以外的任意字符防止匹配上下個""項目(也可以使用非貪婪匹配*?),以"結束
userlius = re.compile(r'[^/)]*/"')
#原理:主要通過空格和-來區分各不同項目,各項目內部寫各自的匹配表達式
nginxLogPattern = re.compile(r"(%s)/ -/ -/ (%s)/ (%s)/ (%s)/ (%s)/ (%s)/ (%s)" %(ipP, timeP, requestP, statusP, bodyBytesSentP, referP, userAgentP), re.VERBOSE)
#數據庫連接信息
conn=MySQLdb.connect(host='192.168.1.22',user='test',passwd='pass',port=3306,db='python')
新聞熱點
疑難解答