pythonlog文件
A. python logging 源文件在哪
首先,想到的是更改logging.basicConfig(filename=logfilename)參數,來實現變更日誌文件名的目的。編寫代碼如下:
log_fmt = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
for i in range(1,4):
filename = str.format('mylog%d.txt' % i)
logging.basicConfig(format=log_fmt, level=logging.DEBUG, filename=filename)
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')12345678
運行結果沒有達到預期的效果,只有日誌文件mylog1.txt被創建,mylog2.txt和mylog3.txt都未被創建,連續3次的輸出的內容都寫入mylog1.txt中。說明logging.basicConfig()設置屬性具有全局性,第一次設置之後,之後再設置將不再生效。查看官方文檔,也確實是如此。
B. python中log文件和txt文件的區別
沒區別啊。
log.txt是txt文件。
run.log是log文件。但兩個只是後綴格式的不同。都是普通文本文件。沒什麼特別的。
log是日誌的意思
C. Python 將運行結果保存到log文件中遇到的問題
這個簡單啊。通過來管道輸出到另一源個程序里去,另外一個程序同時列印並輸出到out.log
這是我常用的辦法。
還有一個笨辦法,用自己的myprint代替所有的print語句。這樣你可以同時輸出到屏幕與文件了。
第三個辦法是通過logging。這個模塊支持多個listener,可以同時輸出到屏幕與文件以及網路。
D. python 使用logging,生成的log文件是什麼編碼格式腳本的編碼格式決定系統的編碼格式決定
log的文件當然是byte格式。或者是無格式的。漢字編碼取決於你自己設定內的類型。
#coding:utf-8這個東容西,只在python2下有效果。還需要編程器配合。你使用python自帶的idle當然是沒有問題的。
log中的漢字是一定要編碼的。不編碼你存貯不了。
編輯器本身的預設編碼格式要與你的源代碼編碼一致,不然看到的就是亂碼。如果是idle,它會根據python腳本自動識別。
不過有些編輯器是有些不智能的。它不能理解python腳本第一行的提示。所以有時候,覺著很別扭自己要手工保持編輯器的編碼與源碼一致。還需要維護那個coding:utf-8
不過python3已將這一句去掉了。源代碼全部要求使用utf-8編碼(也許是utf-16),我很少用python3
E. python里的logging怎麼寫多個文件
an example:
#coding:utf-8
#filename:cfg/logger.yml
version:1
formatters:
simple:
format:'%(asctime)s-%(name)s-%(levelname)s-%(message)s'
consolefmt:
format:'%(name)s-%(levelname)s-%(message)s'
handlers:
console:
class:logging.StreamHandler
formatter:consolefmt
level:WARNING
stream:ext://sys.stdout
ownerloggerfile:
class:logging.handlers.RotatingFileHandler
formatter:simple
level:INFO
filename:log/billingcodeowner.log
maxBytes:1048576
backupCount:3
phnloggerfile:
class:logging.handlers.RotatingFileHandler
formatter:simple
level:INFO
filename:log/phnparser.log
maxBytes:1048576
backupCount:3
loggers:
billingcodeowner:
level:DEBUG
handlers:[ownerloggerfile]
propagate:no
phoneparser:
level:DEBUG
handlers:[console,phnloggerfile]
propagate:no
root:
level:DEBUG
handlers:[console,phnloggerfile]
usage in python application:
importlogging
importlogging.config
importcodecs
importyaml
logging.config.dictConfig(codecs.open("cfg/logger.yml",'r','utf-8').read())
logger=logging.getLogger("billingcodeowner")
F. python的日誌,如何做到一天是單獨一個日誌,並且定期清理
創建以日期為文件的log文件(如:20140911.log),寫日誌前判斷存放日誌路徑是否存在以當天日期為文件名的文件,如果存在添加日誌信息,不存在就創建,在寫日誌信息。
定期清理亦可以按照此思路來做
G. python中log info 是什麼文件
a. 利用sys.stdout將print行導向到你定義的日誌文件中,例如:
import sys# make a of original stdout routestdout_backup = sys.stdout# define the log file that receives your log infolog_file = open("message.log", "w")# redirect print output to log filesys.stdout = log_fileprint "Now all print info will be written to message.log"# any command line that you will execute...
log_file.close()# restore the output to initial patternsys.stdout = stdout_backupprint "Now this will be presented on screen"
b. 利用logging模塊(規范化日誌輸出,推薦!!)
由於logging模塊的功能比較多,下面就放一些文檔里介紹的簡單的例子,更詳細具體的用法請戳這里
需求
最好的實現方式
故障調查或者狀態監測 logging.info()或logging.debug()(後者常用於針對性檢測診斷的目的)
特定運行事件發出警告 logging.warning()
報告錯誤抑制不出發異常(常見於長時間運行的伺服器進程的錯誤處理程序) logging.error(), logging.exception()或者logging.critical()
而以下是根據事件的嚴重性程度而應採取的logging函數的建議:
程度
使用場景
DEBUG 獲得診斷問題是具體的信息
INFO 確認程序是否按正常工作
WARNING 在程序還正常運行時獲取發生的意外的信息,這可能會在之後引發異常(例如磁碟空間不足)
ERROR 獲取程序某些功能無法正常調用這類嚴重異常的信息
CRITICAL 獲取程序無法繼續運行的這類最嚴重異常信息
默認的等級是WARNING,也就是說logging函數在沒有特別配置的前提下只追蹤比WARNING程度更嚴重的異常。
下面就用一些例子來具體說明如何用logging函數記錄日誌信息:
# this is a simple exampleimport logging# define the log file, file mode and logging levellogging.basicConfig(filename='example.log', filemode="w", level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
查看example.log文件可以看到以下信息:
DEBUG:root:This message should go to the log fileINFO:root:So should thisWARNING:root:And this, too
從多個文件記錄日誌
# myapp.pyimport loggingimport mylibdef main():
logging.basicConfig(filename='myapp.log', level=logging.INFO)
logging.info('Started')
mylib.do_something()
logging.info('Finished')if __name__ == '__main__':
main()
# mylib.pyimport loggingdef do_something():
logging.info('Doing something')
輸出的信息為
INFO:root:StartedINFO:root:Doing somethingINFO:root:Finished
改變默認輸出信息的格式
import logging# output format: output time - logging level - log messageslogging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s')
logging.warning('This message will appear in python console.')
在python console中直接列印以下輸出:
2016-8-2 2:59:11, 510 - WARNING - This message will appear in python console
logging高級用法
可以通過構建logger或者讀取logging config文件對logging函數進行任意配置。
構建logger法
- import logging# create loggerlogger = logging.getLogger('simple_example')
- logger.setLevel(logging.DEBUG)# create console handler and set level to debugch = logging.StreamHandler()
- ch.setLevel(logging.DEBUG)# create formatterformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')# add formatter to chch.setFormatter(formatter)# add ch to loggerlogger.addHandler(ch)# 'application' codelogger.debug('debug message')
- logger.info('info message')
- logger.warn('warn message')
- logger.error('error message')
- logger.critical('critical message')
- $ python simple_logging_mole.py2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message2005-03-19 15:10:26,620 - simple_example - INFO - info message2005-03-19 15:10:26,695 - simple_example - WARNING - warn message2005-03-19 15:10:26,697 - simple_example - ERROR - error message2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
讀取配置文件法
- import loggingimport logging.config
- logging.config.fileConfig('logging.conf')# create loggerlogger = logging.getLogger('simpleExample')# 'application' codelogger.debug('debug message')
- logger.info('info message')
- logger.warn('warn message')
- logger.error('error message')
- logger.critical('critical message')
- [loggers]
- keys=root,simpleExample
- [handlers]
- keys=consoleHandler
- [formatters]
- keys=simpleFormatter
- [logger_root]
- level=DEBUG
- handlers=consoleHandler
- [logger_simpleExample]
- level=DEBUG
- handlers=consoleHandler
- qualname=simpleExample
- propagate=0[handler_consoleHandler]class=StreamHandlerlevel=DEBUGformatter=simpleFormatterargs=(sys.stdout,)[formatter_simpleFormatter]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt= '%m/%d/%Y %I:%M:%S %p'
- $ python simple_logging_config.py2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message2005-03-19 15:38:55,979 - simpleExample - INFO - info message2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message2005-03-19 15:38:56,055 - simpleExample - ERROR - error message2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message
以上程序結果會輸出到python console中:
其中logging.conf文件格式為:(其實就是將前一種方法的各項配置參數寫到logging.conf文件中)
與前面一樣,上述文件輸出結果為:
H. 有幾千個TXT格式的log文件,怎麼用Python批量提取每個log文件固定位置的具體數值,輸出到一個TXT文件
1.將這些TXT文件先合並
2.找到這些具體數值的特徵
3.用正則表達式過濾提取
這陣子正學習python,不介意可以發給我,練著玩
I. 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")