專案的乙個需求是解析nginx的日誌檔案。
簡單的整理如下:
首先要明確自己的nginx的日誌格式,這裡採用預設nginx日誌格式:
'"$http_user_agent" "$http_x_forwarded_for"';其中一條真實記錄樣例如下:
172.22.8.207 - - [16/dec/2014:17:57:35 +0800] "get /report?domjjus6kewjp+wculsqagdukaipodexmzawmdjdn0fc http/1.1" 200 0 "-" "******x/1.0.16; iphone/ios 8.1.2; ; 8da77e2f91d0"
其中,客戶端型號資訊用******x
代替。
專案中已經按照業務規則對nginx日誌檔案進行了處理命名規則如下:
id-id-yymmdd-hhmmss
並且所有的日誌檔案存放在統一路徑下。
這裡使用python的glob
模組來獲取日誌檔案path
import glob
def readfile(path):
return glob.glob(path + '*-*-*-*')
使用python的linecache
模組來獲取檔案行的內容
import linecache
def readline(path):
return linecache.getlines(path)
注意:linecache模組使用了快取,所以存在以下問題:
在使用linecache模組讀取檔案內容以後,如果檔案發生了變化,那麼需要使用linecache.updatecache(filename)
來更新快取,以獲取最新變化。
linecache模組使用快取,所以會耗費記憶體,耗費量與要解析的檔案相關。最好在使用完畢後執行linecache.clearcache()
清空一下快取。
當然,作為優化,這裡可以利用生成器
來進行優化。暫且按下不表。
一條日誌資訊就是乙個特定格式的字串,因此使用正規表示式
來解析,這裡使用python的re
模組。
下面,一條一條建立規則:
規則
ip = r"?p[\d.]*"
date = r"?p\d+"
month = r"?p\w+"
year = r"?p\d+"
log_time = r"?p\s+"
method = r"?p\s+"
request = r"?p\s+"
status = r"?p\d+"
bodybytessent = r"?p\d+"
refer = r"""?p[^\"]*
"""useragent=r"""?p.*
"""
p = re.compile(r"(%s)\ -\ -\ \[(%s)/(%s)/(%s)\:(%s)\ [\s]+\]\ \"(%s)?[\s]?(%s)?.*?\"\ (%s)\ (%s)\ \"(%s)\"\ \"(%s).*?\"" %( ip, date, month, year, log_time, method, request, status, bodybytessent, refer, useragent ), re.verbose)
m = re.findall(p, logline)
這樣,就可以得到日誌條目中各個要素的原始資料。
得到日誌原始資料之後,需要根據業務要求,對原始資料進行格式及內容轉化。
這裡需要處理的內容包括:時間,request,useragent
時間格式轉化
在日誌資訊原始資料中存在dec
這樣的資訊,利用python的time
模組可以方便的進行解析
import time
def parsetime(date, month, year, log_time):
time_str = '%s%s%s %s' %(year, month, date, log_time)
return time.strptime(time_str, '%y%b%d %h:%m:%s')
解析request
在日誌資訊原始資料中得到的request
的內容格式為:
/report?******
這裡只需要根據協議取出******
即可。
這裡仍然採用python的re
模組
import re
def parserequest(rqst):
param = r"?p.*"
p = re.compile(r"/report\?(%s)" %param, re.verbose)
return re.findall(p, rqst)
接下來需要根據業務協議解析引數內容。這裡需要先利用base64
模組解碼,然後再利用struct
模組解構內容:
import struct
import base64
def parseparam(param):
decodeinfo = base64.b64decode(param)
s = struct.struct('!x' + bytes(len(decodeinfo) - (1 + 4 + 4 + 12)) + 'xii12x')
return s.unpack(decodeinfo)
解析useragent
在日誌資訊原始資料中useragent資料的格式為:
***; ***; ***; ***
根據業務要求,只需要取出最後一項即可。
這裡採用re
模組來解析。
import re
def parseuseragent(useragent):
agent = r"?p.*"
p = re.compile(r".*;.*;.*;(%s)" %agent, re.verbose)
return re.findall(p, useragent)
至此,nginx日誌檔案解析基本完成。
剩下的工作就是根據業務需要,對獲得的基本資訊進行處理。
(完)
Nginx使用解析說明
其整體結構如下 從圖中我們可以看出主要包含以下幾大部分內容 main 全域性設定 設定的指令將影響其他所有設定 server 主機設定 指令主要用於指定主機和埠 upstream 負載均衡伺服器設定 指令主要用於負載均衡,設定一系列的後端伺服器 location url匹配特定位置的設定 用於匹配網...
Nginx 配置解析
執行使用者,預設即是nginx,可不設定 user nobody nginx程序,一般設定為和cpu核數一樣 worker processes 1 單個後台worker process程序的最大併發鏈結數 docker run itd restart unless stopped v etc loc...
Nginx配置解析
執行使用者,預設即是nginx,可不設定 user nobody nginx程序,一般設定為和cpu核數一樣 worker processes 1 單個後台worker process程序的最大併發鏈結數 docker run itd restart unless stopped v etc loc...