Python把Nginx日誌儲存到MySQL資料庫

來源:互聯網
上載者:User

Nginx access日誌格式如下:

 代碼如下 複製代碼

#使用的nginx預設日誌格式$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"'

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"'''
 
 
 
#日誌分析Regex
#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')
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)
#conn.commit()
print result
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
conn.commit()
conn.close()


存入資料庫後資料是如下格式:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.