當前位置:首頁 » 編程語言 » python日誌切割

python日誌切割

發布時間: 2022-05-22 11:13:16

㈠ 如何用 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 日誌按時間切分問題!

提供個思路,
win下和linux下的換行符不一樣,所以處理文本結果就有差異。

㈢ python怎麼使用切割獲取網頁內容

你可以用用現成的python模板:beautifulsoup。 或者最起碼你得了解Python的正則,然後自己去用正則解析網頁。

㈣ 日誌文件太大,python怎麼分割文件,多線程操作

python的多線程為偽多線程,多線程並不能提高文件IO的速度,在讀取文件時使用直接讀取 for line in open('文件名', 'r') 效率最高,因為此方式為直接讀取,不像其它方式要把文件全部載入到內存再讀取,所以效率最高。分割時文件時,提前計算好行數,把讀取的每固定數量的行數存入新文件,直接讀取完成,最後刪除舊文件,即可實現文件分割。

示意代碼:

line_count=0
index=0
fw=open('part'+str(index)+'.log','w')
forlineinopen('filename.log','r'):
fw.write(line)
line_count+=1
#假設每10000行寫一個文件
ifline_count>10000:
fw.close()
index+=1
fw=open('part'+str(index)+'.log','w')
fw.close()

㈤ 如何用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 處理日誌,用什麼模塊比較好

首先切割數據到小文件:

#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")
2. 對小文件分類匯總
#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中的logger和handler到底是個什麼鬼

最近的任務經常涉及到日誌的記錄,特意去又學了一遍logging的記錄方法。跟java一樣,python的日誌記錄也是比較繁瑣的一件事,在寫一條記錄之前,要寫好多東西。典型的日誌記錄的步驟是這樣的:

創建logger
創建handler
定義formatter
給handler添加formatter
給logger添加handler

寫成代碼差不多就是醬嬸的(這個是照別的網頁抄的,參考附註):

1 import logging
2
3 # 1、創建一個logger
4 logger = logging.getLogger('mylogger')
5 logger.setLevel(logging.DEBUG)
6
7 # 2、創建一個handler,用於寫入日誌文件
8 fh = logging.FileHandler('test.log')
9 fh.setLevel(logging.DEBUG)
10
11 # 再創建一個handler,用於輸出到控制台
12 ch = logging.StreamHandler()
13 ch.setLevel(logging.DEBUG)
14
15 # 3、定義handler的輸出格式(formatter)
16 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
17
18 # 4、給handler添加formatter
19 fh.setFormatter(formatter)
20 ch.setFormatter(formatter)
21
22 # 5、給logger添加handler
23 logger.addHandler(fh)
24 logger.addHandler(ch)

之後才可以正式的開始記錄日誌。Java裡面的java.util.Logging類差不多也是這樣,代碼還要更復雜一點。Golang的日誌相對
寫法簡單一些,不過沒有什麼格式,系統記錄一條時間,內容格式完全自己手畫。第三方的日誌庫倒是沒有接觸過,像Java的Log4j,Golang的
log4go和seelog等等,不知道用起來會不會簡單一點。我一直都記不住這些,因為不太理解logger和handler為什麼要這樣寫。一直到這
次任務中出現的在我看來相當「詭異」的bug,才深入理解了一下。

我的任務是這樣的,要做一個日誌切割的工具,按天將日誌分割開,即每天0點產生一個新日誌,將舊日誌改名。並且,將超過3個月的日誌刪除掉,以保證磁碟空間不會被log占滿。程序要求可以切割多個目錄中的不同日誌,具體路徑由json中配置。

這里用到了logging.handlers類中的TimedRotatingFileHandler方法,用以獲得一個handler。大概的寫法為:

1 logger = logging.getLogger() #獲得logger
2 handler = logging.handlers.TimedRotatingFileHandler(logfile, 'S', 1, 0) #切割日誌
3 handler.suffix = '%Y%m%d' #切割後的日誌設置後綴
4 logger.addHandler(handler) #把logger添加上handler
5 logger.fatal(datetime.datetime.now().strftime('%Y-%m-%d')) #在新日誌中寫上當天的日期

這里我沒有設置level和formatter。因為只是分割,對新日誌沒有什麼影響。TimedRotatingFileHandler函數的方
法見附註,或查看python的源碼,這個函數是python寫的,可以找到定義。這里我使用的是每秒生成一個新的日誌文件,之後用Crontab在每天
0點調度,然後用for循環處理json中的每一個日誌文件。

但是奇怪的是,每次運行程序,第一個切割的日誌生成一個分割後的文件,而後面的都生成兩個新日誌。百思不得其解。後檢查代碼覺得,可能是程序中設置
的時間太短了,每秒生成一個文件,有可能一秒鍾處理不完,就生成了兩個。雖然這個說法沒有什麼科學根據,但是還是把
TimedRotatingFileHandler中的第三個參數改成了60,即每60秒生成一個文件。完成,靜靜的等待crontab到時間。

㈧ 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 讀取日誌文件

#-*-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

㈩ 切割後的nginx日誌怎麼讀取 python

兄弟,能說明白點不? linux下日誌文件 vi、cat都可以讀取啊,用python 直接open就行。

熱點內容
和平精英安卓版怎麼調成中文 發布:2025-02-13 22:16:10 瀏覽:36
混沌起源需要什麼配置玩 發布:2025-02-13 22:14:33 瀏覽:277
vs引入文件夾 發布:2025-02-13 22:05:52 瀏覽:127
安卓手機如何調無限電量 發布:2025-02-13 22:05:50 瀏覽:113
phppost長度 發布:2025-02-13 22:05:45 瀏覽:626
烈火戰神源碼 發布:2025-02-13 22:04:51 瀏覽:619
源碼貓交易 發布:2025-02-13 22:04:49 瀏覽:756
廣告腳本鏡頭 發布:2025-02-13 22:04:48 瀏覽:986
安卓手機哪個app自拍更真實 發布:2025-02-13 22:00:19 瀏覽:194
安卓系統密碼忘了怎麼辦 發布:2025-02-13 21:49:28 瀏覽:972