當前位置:首頁 » 編程語言 » python日記

python日記

發布時間: 2022-08-18 14:14:59

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 log日誌怎麼寫 案例

python中,logging模塊主要是處理日誌的。
所謂日誌,可理解為在軟體運行過程中,所記錄的的一些運行情況信息
軟體開發人員可以根據自己的需求添加日誌,日誌可以幫助軟體開發人員
了解軟體的運行信息,對軟體的維護尤為重要。

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

#-*-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日誌記錄模塊主要作用是什麼呢,求具體例子

4個主要的組件
logger: 日誌類,應用程序往往通過調用它提供的api來記錄日誌;
handler: 對日誌信息處理,可以將日誌發送(保存)到不同的目標域中;
filter: 對日誌信息進行過濾;
formatter:日誌的格式化;

㈦ python日誌怎麼配置壓縮

#!/usr/bin/env python#-*- coding: utf-8 -*-#import datetimeimport osimport zipfile#計算昨天的時間time = datetime.datetime.now()
delta = datetime.timedelta(days=-1)
n_days = time + delta
yestoday = n_days.strftime('%Y-%m-%d')
name = 'app.' +yestoday +'.log'#print (name)def zip_files(file,file_news):
file = '/data/server/apps/rules_scalability/logs/' +name #文件名
# print(file)
file_news = '/data/server/apps/rules_scalability/logs/' +name +'.zip' #文件壓縮後的名
#print(file_news)
f = zipfile.ZipFile(file_news, 'w', zipfile.ZIP_DEFLATED,allowZip64=True)
f.write(file,name) #name文件解壓後的名 f.close()
os.remove(file) #刪除源文件file = '/data/server/apps/rules_scalability/logs/' +name
file_news = '/data/server/apps/rules_scalability/logs/' +name +'.zip'zip_files(file,file_news)

㈧ 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事件

㈩ PYTHON使用日記之怎麼找到linux系統上django的安裝路徑

python的話,你可以把python的安裝環境加到系統變數(我記得是自動添加的,可以在dos下直接運行python)
至於django的話,可以直接運行django-admin startproject mysite2(django-admin不用.py),不用python django-admin.py startproject mysite2(如果要的話,需要在python安裝包下的script添加到系統環境變數)

熱點內容
資料庫數據插入語句 發布:2025-05-15 01:30:01 瀏覽:870
js是無需編譯直接運行嗎 發布:2025-05-15 01:28:30 瀏覽:475
android文件夾重命名 發布:2025-05-15 01:13:50 瀏覽:481
cns腳本 發布:2025-05-15 01:13:38 瀏覽:722
數據結構與演算法筆試題 發布:2025-05-15 01:04:20 瀏覽:417
搜狗輸入法如何直接編輯配置文件 發布:2025-05-15 00:51:47 瀏覽:668
電箱都有哪些配置 發布:2025-05-15 00:30:21 瀏覽:74
安卓qq邀請碼在哪裡尋找 發布:2025-05-15 00:02:04 瀏覽:35
三菱fx編程口 發布:2025-05-15 00:01:23 瀏覽:810
醫院招商引資宣傳片腳本 發布:2025-05-15 00:01:21 瀏覽:368