使用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代码:
复制代码 代码如下:
import os
import fileinput
import re
import sys
import MySQLdb
logfile=open("access_20130812.log")
ipP = r"?P
timeP = r"""?P
requestP = r"""?P
statusP = r"?P
bodyBytesSentP = r"?P
referP = r"""?P
userAgentP = r"""?P
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')
cur=conn.cursor()
sql = "INSERT INTO python.test VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)"
while True:
line = logfile.readline()
if not line:break
matchs = nginxLogPattern.match(line)
if matchs != None:
allGroup = matchs.groups()
ip = allGroup[0]
time = allGroup[1]
request = allGroup[2]
status = allGroup[3]
bodyBytesSent = allGroup[4]
refer = allGroup[5]
userAgent = allGroup[6]
Time = time.replace('T',' ')[1:-7]
if len(userAgent) > 20:
userinfo = userAgent.split(' ')
userkel = userinfo[0]
try:
usersystem = userSystems.findall(userAgent)
usersystem = usersystem[0]
print usersystem
userliu = userlius.findall(userAgent)
value = [ip,Time,request,status,bodyBytesSent,refer,userkel,usersystem,userliu[1]]
conn.commit()
print value
except IndexError:
userinfo = userAgent
value = [ip,Time,request,status,bodyBytesSent,refer,userinfo,"",""]
else:
useraa = userAgent
value = [ip,Time,request,status,bodyBytesSent,refer,useraa,"",""]
try:
result = cur.execute(sql,value)
print result
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
conn.commit()
conn.close()
四、存入数据库后数据是如下图:
Copyright© 2013-2020
All Rights Reserved 京ICP备2023019179号-8