python日誌收集
① python處理日誌的包有哪些
#coding:utf-8
#file: FileSplit.py
import os,os.path,time
def FileSplit(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
number = 100000 #每個小文件中保存100000條數據
dataLine = sFile.readline()
tempData = [] #緩存列表
fileNum = 1
if not os.path.isdir(targetFolder): #如果目標目錄不存在,則創建
os.mkdir(targetFolder)
while dataLine: #有數據
for row in range(number):
tempData.append(dataLine) #將一行數據添加到列表中
dataLine = sFile.readline()
if not dataLine :
break
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + str(fileNum) + ".txt")
tFile = open(tFilename, 'a+') #創建小文件
tFile.writelines(tempData) #將列表保存到文件中
tFile.close()
tempData = [] #清空緩存列表
print(tFilename + " 創建於: " + str(time.ctime()))
fileNum += 1 #文件編號
sFile.close()
if __name__ == "__main__" :
FileSplit("access.log","access")
#coding:utf-8
#file: Map.py
import os,os.path,re
def Map(sourceFile, targetFolder):
sFile = open(sourceFile, 'r')
dataLine = sFile.readline()
tempData = {} #緩存列表
if not os.path.isdir(targetFolder): #如果目標目錄不存在,則創建
os.mkdir(targetFolder)
while dataLine: #有數據
p_re = re.compile(r'(GET|POST)\s(.*?)\sHTTP/1.[01]',re.IGNORECASE) #用正則表達式解析數據
match = p_re.findall(dataLine)
if match:
visitUrl = match[0][1]
if visitUrl in tempData:
tempData[visitUrl] += 1
else:
tempData[visitUrl] = 1
dataLine = sFile.readline() #讀入下一行數據
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(targetFolder,os.path.split(sourceFile)[1] + "_map.txt")
tFile = open(tFilename, 'a+') #創建小文件
tFile.writelines(tList) #將列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Map("access\\access.log1.txt","access")
Map("access\\access.log2.txt","access")
Map("access\\access.log3.txt","access")
#coding:utf-8
#file: Rece.py
import os,os.path,re
def Rece(sourceFolder, targetFile):
tempData = {} #緩存列表
p_re = re.compile(r'(.*?)(\d{1,}$)',re.IGNORECASE) #用正則表達式解析數據
for root,dirs,files in os.walk(sourceFolder):
for fil in files:
if fil.endswith('_map.txt'): #是rece文件
sFile = open(os.path.abspath(os.path.join(root,fil)), 'r')
dataLine = sFile.readline()
while dataLine: #有數據
subdata = p_re.findall(dataLine) #用空格分割數據
#print(subdata[0][0]," ",subdata[0][1])
if subdata[0][0] in tempData:
tempData[subdata[0][0]] += int(subdata[0][1])
else:
tempData[subdata[0][0]] = int(subdata[0][1])
dataLine = sFile.readline() #讀入下一行數據
sFile.close()
tList = []
for key,value in sorted(tempData.items(),key = lambda k:k[1],reverse = True):
tList.append(key + " " + str(value) + '\n')
tFilename = os.path.join(sourceFolder,targetFile + "_rece.txt")
tFile = open(tFilename, 'a+') #創建小文件
tFile.writelines(tList) #將列表保存到文件中
tFile.close()
if __name__ == "__main__" :
Rece("access","access")
② 如何用 python 分析網站日誌
日誌的記錄
Python有一個logging模塊,可以用來產生日誌。
(1)學習資料
http://blog.sina.com.cn/s/blog_4b5039210100f1wv.html
http://blog.donews.com/limodou/archive/2005/02/16/278699.aspx
http://kenby.iteye.com/blog/1162698
http://blog.csdn.NET/fxjtoday/article/details/6307285
前邊幾篇文章僅僅是其它人的簡單學習經驗,下邊這個鏈接中的內容比較全面。
http://www.red-dove.com/logging/index.html
(2)我需要關注內容
日誌信息輸出級別
logging模塊提供了多種日誌級別,如:NOTSET(0),DEBUG(10),
INFO(20),WARNING(30),WARNING(40),CRITICAL(50)。
設置方法:
logger = getLogger()
logger.serLevel(logging.DEBUG)
日誌數據格式
使用Formatter設置日誌的輸出格式。
設置方法:
logger = getLogger()
handler = loggingFileHandler(XXX)
formatter = logging.Formatter("%(asctime)s %(levelname) %(message)s","%Y-%m-%d,%H:%M:%S")
%(asctime)s表示記錄日誌寫入時間,"%Y-%m-%d,%H:%M:%S「設定了時間的具體寫入格式。
%(levelname)s表示記錄日誌的級別。
%(message)s表示記錄日誌的具體內容。
日誌對象初始化
def initLog():
logger = logging.getLogger()
handler = logging.FileHandler("日誌保存路徑")
formatter = logging.Formatter("%(asctime)s %(levelname) %(message)s","%Y-%m-%d,%H:%M:%S")
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel
寫日誌
logging.getLogger().info(), logging.getLogger().debug()......
2. 日誌的分析。
(1)我的日誌的內容。(log.txt)
2011-12-12,12:11:31 INFO Client1: 4356175.0 1.32366309133e+12 1.32366309134e+12
2011-12-12,12:11:33 INFO Client1: 4361320.0 1.32366309334e+12 1.32366309336e+12
2011-12-12,12:11:33 INFO Client0: 4361320.0 1.32366309389e+12 1.32366309391e+12
2011-12-12,12:11:39 INFO Client1: 4366364.0 1.32366309934e+12 1.32366309936e+12
2011-12-12,12:11:39 INFO Client0: 4366364.0 1.32366309989e+12 1.32366309991e+12
2011-12-12,12:11:43 INFO Client1: 4371416.0 1.32366310334e+12 1.32366310336e+12
2011-12-12,12:11:43 INFO Client0: 4371416.0 1.32366310389e+12 1.32366310391e+12
2011-12-12,12:11:49 INFO Client1: 4376450.0 1.32366310934e+12 1.32366310936e+12
我需要將上述內容逐行讀出,並將三個時間戳提取出來,然後將其圖形化。
(2) 文件操作以及字元串的分析。
打開文件,讀取出一行日誌。
file = file("日誌路徑",「r」)
while True:
line = file.readline()
if len(len) == 0:
break;
print line
file.close()
從字元串中提取數據。
字元串操作學習資料:
http://reader.you.com/sharelite?itemId=-4646262544179865983&method=viewSharedItemThroughLink&sharedBy=-1137845767117085734
從上面展示出來的日誌內容可見,主要數據都是用空格分隔,所以需要使用字元串的
split函數對字元串進行分割:
paraList = line.split(),該函數默認的分割符是空格,返回值為一個list。
paraList[3], paraList[4], paraList[5]中分別以字元串形式存儲著我需要的時間戳。
使用float(paraList[3])將字元串轉化為浮點數。
(3)將日誌圖形化。
matplotlib是python的一個繪圖庫。我打算用它來將日誌圖形化。
matplotlib學習資料。
matplotlib的下載與安裝:
http://yexin218.iteye.com/blog/645894
http://blog.csdn.Net/sharkw/article/details/1924949
對matplotlib的宏觀介紹:
http://apps.hi..com/share/detail/21928578
對matplotlib具體使用的詳細介紹:
http://blog.sina.com.cn/s/blog_4b5039210100ie6a.html
在matplotlib中設置線條的顏色和形狀:
http://blog.csdn.net/kkxgx/article/details/python
如果想對matplotlib有一個全面的了解,就需要閱讀教程《Matplotlib for Python developers》,教程下載地址:
http://download.csdn.net/detail/nmgfrank/4006691
使用實例
import matplotlib.pyplot as plt
listX = [] #保存X軸數據
listY = [] #保存Y軸數據
listY1 = [] #保存Y軸數據
file = file("../log.txt","r")#打開日誌文件
while True:
line = file.readline()#讀取一行日誌
if len(line) == 0:#如果到達日誌末尾,退出
break
paraList = line.split()
print paraList[2]
print paraList[3]
print paraList[4]
print paraList[5]
if paraList[2] == "Client0:": #在坐標圖中添加兩個點,它們的X軸數值是相同的
listX.append(float(paraList[3]))
listY.append(float(paraList[5]) - float(paraList[3]))
listY1.append(float(paraList[4]) - float(paraList[3]))
file.close()
plt.plot(listX,listY,'bo-',listX,listY1,'ro')#畫圖
plt.title('tile')#設置所繪圖像的標題
plt.xlabel('time in sec')#設置x軸名稱
plt.ylabel('delays in ms'')#設置y軸名稱
plt.show()
③ python有沒有通用的日誌統計系統
logging模塊
importlogging
#配置日誌,輸出到控制台
logging.basicConfig(
level=logging.DEBUG,#日誌記錄級別
format="[%(asctime)s]%(name)s:%(levelname)s:%(message)s"#日誌列印格式
)
#輸出日誌
logging.debug("Thisisadebug")
logging.info("Thisisaninfo")
logging.warning("Thisisawarning")
logging.error("Thisisanerror")
logging.critical("Thesystemisdown")
④ php 有沒有類似 python 的 sentry 日誌收集系統
php 有沒有類似 python 的 sentry 日誌收集系統
phpserialize 可以作為單純的 Python 擴展件來使用,不過,通常還是經常應用在 Python 編程環境和 PHP 編程環境相互之間需要進行數據交換時。
phpserialize 安裝很簡單,在 下載後,解壓,然後 # python setup.py install 即可。
phpserialize 使用起來也很簡單。
先導入該庫: import phpserialize
利用 mps 進行序列化(變數 -> 格式化文本): phpserialize.mps(vary)
使用 loads 進行反序列化(格式化文本 -> 變數):phpserialize.loads(formated_string)
⑤ python里如何提取日誌中的錯誤信息
只要進行提取日誌中的錯誤信息,那麼你可以編輯一段程序,然後這樣的話才能夠完成達到提取的。
⑥ 用python怎麼實現自動記日誌的功能
功能
[root@skatedb55 ~]# vi op_log_file.py
#!/usr/bin/env python
#-*- coding: utf-8 -*-
#Author:Skate
import os,time
def op_log(log):
f=file(log_file,'a')
date=time.strftime('%Y-%m-%d %H:%M:%S')
record = '%s %s\n' %(date,log)
f.write(record)
⑦ python 讀取日誌文件
#-*-coding:utf-8-*-
withopen('log.txt','r')asf:
foriinf:
ifdt.strftime(dt.now(),'%Y-%m-%d')ini:
#判斷是否當天時間
if'ERROR'iniand'atcom.mytijian'ini:
#判斷此行中是否含有'ERROR'及'atcom.mytijian'
if((dt.now()-dt.strptime(i.split(',')[0],'%Y-%m-%d%H:%M:%S')).seconds)<45*60:
#判斷時間是為當前45分鍾內
printi
⑧ Python記錄詳細調用堆棧日誌的方法
Python記錄詳細調用堆棧日誌的方法
這篇文章主要介紹了Python記錄詳細調用堆棧日誌的方法,涉及Python調用堆棧日誌的相關技巧,具有一定參考借鑒價值,需要的朋友可以參考下
import sys
import os
def detailtrace(info):
retStr = ""
curindex=0
f = sys._getframe()
f = f.f_back # first frame is detailtrace, ignore it
while hasattr(f, "f_code"):
co = f.f_code
retStr = "%s(%s:%s)->"%(os.path.basename(co.co_filename),
co.co_name,
f.f_lineno) + retStr
f = f.f_back
print retStr+info
def foo():
detailtrace("hello world")
def bar():
foo()
def main():
bar()
if __name__ == "__main__":
main()
輸出:
aaa1.py(<mole>:27)->aaa1.py(main:24)->aaa1.py(bar:21)->aaa1.py(foo:18)->hello world
希望本文所述對大家的Python程序設計有所幫助。
⑨ Python語言掃描日誌並統計
修復了一些小的拼寫錯誤
修復了出現無效數據行會出現錯誤的BUG
修復了最小值統計方法的錯誤
===================下面開始咯log.py========
# -*- coding: cp936 -*-
#上一句不可以刪!表示中文路徑是GBK編碼
importdatetime
#處理時間的模塊
defsparse(target='log.txt') :
tgfile = file(target,"r")
event={}
#event是一個字典,key是事件的編號,value是數據(可以利用嵌套來擴展數據)
linelog = "Not Empty"
whilelinelog:
linelog = tgfile.readline()
data = linelog.split('')
#按空格將一行數據分為列表
# printdata #testing
iflen(data) > 4 : #有效的數據行
time1 = data[2][1:] + '' + data[3][:-1]
#將時間處理為(字元串):年-月-日 小時:分鍾:秒
time2 = datetime.datetime.strptime(time1,'%Y-%m-%d %H:%M:%S')
#將時間識別為datetime類
if data[5] == "begin:" and data[6][:2] == "OK" :
#我不知道有沒有 requestbegin: fail 這個東西,沒有就把後半刪掉吧!
ifnotevent.has_key(data[0]) :
#第一次發生某id的事件時初始化數據
event[data[0]]=[[1,time2,0]]
#我設置的value是一個列表,每個元素是一次記錄,包括[是否沒結束,開始時間,結束時間]。
else :
event[data[0]].append([1,time2,0])
#已經有過記錄了就在記錄後加一條新記錄
ifdata[5] == "end:"anddata[6][:2] == "OK" :
#我想應該沒有不出現begin就直接end的事件吧……
event[data[0]][-1][0]=0 #最後一條記錄中寫入:事件已經結束
event[data[0]][-1][2]=time2 #最後一條記錄寫入:記錄結束時間
#如果還要處理其他的什麼情形在這里添加if的判斷
tgfile.close()
returnevent
defanalysis(target='log.txt') :
event = sparse(target)
#調用上面定於的sparse方法。其實簡單的處理用不著這么做的……單純為了擴展性
static = {}
#用於統計結果的字典(其key和event中的key相同)
foroneeventinevent :
#每個事件的記錄
static[oneevent]=[0,0,0,0,-1]
#初始化每個事件的統計:[成功發生次數,總發生次數,總發生時間,最大發生時間,最小發生時間]
foronerecordinevent[oneevent] :
#每個事件的一次記錄
static[oneevent][0] += 1 #總發生次數加一
if onerecord[0] == 0 : #成功事件
static[oneevent][1] += 1
time_delta = onerecord[2] - onerecord[1]
#計算結果是一個timedelta類型
inttimedelta = time_delta.days *24*60*60 + time_delta.seconds
#將時間差轉化為以秒計算的整數
if inttimedelta > static[oneevent][3] :
static[oneevent][3] = inttimedelta #統計最大值
if inttimedelta < static[oneevent][4] or static[oneevent][4] < 0 :
static[oneevent][4] = inttimedelta #統計最小值
static[oneevent][2] += inttimedelta
return static
===================下面是log.txt===========
#10.0.0.0[2007-06-1223:27:08]requestbegin:OK
#30.0.0.0[2007-06-1223:28:08]requestbegin:fail
#10.0.0.0[2007-06-1223:37:08]requestbegin:OK
#10.0.0.0[2007-06-1223:37:18]requestforadata:OK
#10.0.0.0[2007-06-1223:37:19]receivedsomedata:OK
#10.0.0.0[2007-06-1300:27:08]requestend:OK
#20.0.0.0[2007-06-1300:37:08]requestbegin:OK
#20.0.0.0[2007-06-1300:47:08]requestend:OK
systemERROR:reboot
Another Invalid Line
#10.0.0.0[2007-06-1323:28:18]requestbegin:OK
#70.0.0.0[2007-06-1323:29:08]requestbegin:OK
#70.0.0.0[2007-06-1323:30:18]requestend:OK
#40.0.0.0[2007-06-1323:33:08]requestbegin:OK
#40.0.0.0[2007-06-1323:35:23]requestend:OK
#40.0.0.0[2007-06-1323:37:08]requestbegin:OK
#40.0.0.0[2007-06-1323:43:38]requestend:OK
#50.0.0.0[2007-06-1323:47:08]requestbegin:OK
#10.0.0.0[2007-06-1323:57:48]requestbegin:OK
#50.0.0.0[2007-06-1323:59:08]requestend:OK
===================下面是使用和輸出========
importlog
output = log.analysis()
#或者直接log.analysis()
=============輸出============
{'#2': [1, 1, 600, 600, 600], '#1': [4, 1, 3000, 3000, 3000], '#7': [1, 1, 70, 70, 70], '#5': [1, 1, 720, 720, 720], '#4': [2, 2, 525, 390, 135]}
比如#1事件,總次數output['#1'][0]==4次
成功次output['#1'][1]==1次
失敗次output['#1'][0]-output['#1'][1]==3次
總時間output['#1'][2]==3000秒
平均時間output['#1'][2]/output['#1'][1]==3000/1==3000秒
最大時間output['#1'][3]==3000秒
最小時間output['#1'][4]==3000秒
共有len(output)==5種ID事件