溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

python+pandas分析nginx日志的實(shí)例

發(fā)布時(shí)間:2020-09-09 04:19:19 來(lái)源:腳本之家 閱讀:251 作者:man8er 欄目:開(kāi)發(fā)技術(shù)

需求

通過(guò)分析nginx訪(fǎng)問(wèn)日志,獲取每個(gè)接口響應(yīng)時(shí)間最大值、最小值、平均值及訪(fǎng)問(wèn)量。

實(shí)現(xiàn)原理

將nginx日志uriuriupstream_response_time字段存放到pandas的dataframe中,然后通過(guò)分組、數(shù)據(jù)統(tǒng)計(jì)功能實(shí)現(xiàn)。

實(shí)現(xiàn)

1.準(zhǔn)備工作

#創(chuàng)建日志目錄,用于存放日志
mkdir /home/test/python/log/log
#創(chuàng)建文件,用于存放從nginx日志中提取的$uri $upstream_response_time字段
touch /home/test/python/log/log.txt
#安裝相關(guān)模塊
conda create -n science numpy scipy matplotlib pandas
#安裝生成execl表格的相關(guān)模塊
pip install xlwt

2.代碼實(shí)現(xiàn)

#!/usr/local/miniconda2/envs/science/bin/python
#-*- coding: utf-8 -*-
#統(tǒng)計(jì)每個(gè)接口的響應(yīng)時(shí)間
#請(qǐng)?zhí)崆皠?chuàng)建log.txt并設(shè)置logdir
import sys
import os
import pandas as pd
mulu=os.path.dirname(__file__)
#日志文件存放路徑
logdir="/home/test/python/log/log"
#存放統(tǒng)計(jì)所需的日志相關(guān)字段
logfile_format=os.path.join(mulu,"log.txt")
print "read from logfile \n"
for eachfile in os.listdir(logdir):
 logfile=os.path.join(logdir,eachfile)
 with open(logfile, 'r') as fo:
  for line in fo:
   spline=line.split()
   #過(guò)濾字段中異常部分
   if spline[6]=="-":
    pass
   elif spline[6]=="GET":
    pass
   elif spline[-1]=="-":
    pass
   else:
    with open(logfile_format, 'a') as fw:
     fw.write(spline[6])
     fw.write('\t')
     fw.write(spline[-1])
     fw.write('\n')
print "output panda"
#將統(tǒng)計(jì)的字段讀入到dataframe中
reader=pd.read_table(logfile_format,sep='\t',engine='python',names=["interface","reponse_time"] ,header=None,iterator=True)
loop=True
chunksize=10000000
chunks=[]
while loop:
 try:
  chunk=reader.get_chunk(chunksize)
  chunks.append(chunk)
 except StopIteration:
  loop=False
  print "Iteration is stopped."
df=pd.concat(chunks)
#df=df.set_index("interface")
#df=df.drop(["GET","-"])
df_groupd=df.groupby('interface')
df_groupd_max=df_groupd.max()
df_groupd_min= df_groupd.min()
df_groupd_mean= df_groupd.mean()
df_groupd_size= df_groupd.size()
#print df_groupd_max
#print df_groupd_min
#print df_groupd_mean
df_ana=pd.concat([df_groupd_max,df_groupd_min,df_groupd_mean,df_groupd_size],axis=1,keys=["max","min","average","count"])
print "output excel"
df_ana.to_excel("test.xls")

3.打印的表格如下:

python+pandas分析nginx日志的實(shí)例

要點(diǎn)

1. 日志文件比較大的情況下讀取不要用readlines()、readline(),會(huì)將日志全部讀到內(nèi)存,導(dǎo)致內(nèi)存占滿(mǎn)。因此在此使用for line in fo迭代的方式,基本不占內(nèi)存。

2. 讀取nginx日志,可以使用pd.read_table(log_file, sep=' ‘, iterator=True),但是此處我們?cè)O(shè)置的sep無(wú)法正常匹配分割,因此先將nginx用split分割,然后再存入pandas。

3. Pandas提供了IO工具可以將大文件分塊讀取,使用不同分塊大小來(lái)讀取再調(diào)用 pandas.concat 連接DataFrame

以上這篇python+pandas分析nginx日志的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI