『壹』 python logging.conf是什麼類型文件
下面的函數用於配置logging模塊,它們位於logging.config模塊中。你可以使用這些函數來配置,也可以在logging或是logging.handlers中聲明它們來配置。
logging.config.dictConfig(config)
從dictionary中獲取logging配置
logging.config.fileConfig(fname, defaults=None, disable_existing_loggers=True)
從指定的fname的配置文件中讀取logging配置文件
該函數可以在應用程序中多次調用
logging.config.listen(port=DEFAULT_LOGGING_CONFIG_PORT)
在指定埠啟動socket server並偵聽新配置
logging.config.stopListening()
關閉先前正在偵聽的server
Configuration file format
被fileConfiguration()所理解的配置文件格式基於configparser功能。配置文件必須包含[loggers], [handlers]和[formatters],它們分別代表日誌文件中定義的每種類型的實體。對這3種實體,後面有一個單獨的section來定義該實體如何配置。
因此,[loggers]節中名為log01的logger,相關的配置文件細節在[logger_log01]節中定義。類似地,[handlers]節中名為
hand01的handler將在[handler_hand01]節中聲明,[formatters]節中的form01將在[formatter_form01]聲明。root logger配置必須在[logger_root]節聲明。
注意:fileConfig() API比dictConfig()舊,並不包含logging某些方面的功能。建議以後盡量使用dictConfig API。
配置文件的例子如下:
[loggers]
keys=root,log02,log03,log04,log05,log06,log07
[handlers]
keys=hand01,hand02,hand03,hand04,hand05,hand06,hand07,hand08,hand09
[formatters]
keys=form01,form02,form03,form04,form05,form06,form07,form08,form09
root logger必須指定一個級別和handlers列表。示例如下:
[logger_root]
level=NOTSET
handlers=hand01
其中level可以是DEBUG, INFO, WARNING, ERROR, CRITICAL or NOTSET之一,僅對root logger來說,NOTSET意味著所有的log message
都會記錄。對非root的logger,強制要求一些額外信息,比如
[logger_parser]
level=DEBUG
handlers=hand01
propagate=1
qualname=compiler.parser
當一個非root的logger中level被配置為NOSET,它將通過上一級的logger來確定當前logger的有效級別。propagete為1表示message必須傳播到上一級logger中,為0表示不傳。qualname表示該logger的層級channel名稱,這就是說,應用程序使用該名稱可以得到該logger對象。
handler類型很多,主要有StreamHandler,FileHandler,NullHandler,SysLogHandler,HTTPHandler等
handler節對應的配置示例如下:
[handler_hand01]
class=StreamHandler
level=NOTSET
formatter=form01
args=(sys.stdout,)
class表示該handler在logging包命名空間中的類名,level表示logger的級別,NONSET表示要記錄所有日誌。
formatter表示該handler的formatter的鍵名,假如空白的話,就使用默認值logging._defaultFormatter。假如formatter指定了該名字,必須在對應的section聲明。args欄位是handler類的構造函數的變數列表,參考相關handler構造函數,或者下面的例子,去觀察通常的元素是如何構造的。比如:
[handler_hand02]
class=FileHandler
level=DEBUG
formatter=form02
args=('python.log', 'w')
下面是formatter的配置
[formatter_form01]
format=F1 %(asctime)s %(levelname)s %(message)s
datefmt=
class=logging.Formatter
format欄位是全局格式字元串,datefmt是strftime()兼容的date/time格式字元串,為空時使用默認的ISO8601格式,比如2003-01-23 00:29:50,411,class欄位表示formatter的類名,
日誌級別如下:
Level Numeric value
CRITICAL 50
ERROR 40
WARNING 30
INFO 20
DEBUG 10
NOTSET 0
logging.handlers解讀
logging模塊中定義了這3個handler:StreamHandler, FileHandler and NullHandler
其它的handler都在logging.handler中定義,一並說明如下:
StreamHandler
該類位於logging包,將logging output輸出到流中,比如sys.stdout,sys.stderr或任何支持write()和flush()方法的類文件對象
class logging.StreamHandler(stream=None)
假如指定了stream名稱,日誌將輸出到流實例中,否則,日誌輸出到sys.stderr
FileHandler
該類位於logging包,將logging output輸出到磁碟文件中,文件默認無限增長
class logging.FileHandler(filename, mode='a', encoding=None, delay=False)
打開指定的文件並記錄日誌,假如mode沒有設置,默認使用'a'表示追加日誌到文件中。
NullHandler
該對象什麼也不處理
WatchedFileHandler
一個FileHandler實例,監視日誌文件的變化,假如文件變化了,它會關閉並重新打開,不建議在Windows下使用
文件的變化可以發生,當應用程序使用newsyslog和logrotate來實現日誌文件的回滾時。這個handle是在Unix/Linux下面,監視文件是否改變。(一個文件認為改變了,假如它的device厚實inode已經改變),將舊的文件關閉,這個流打開。
class logging.handlers.WatchedFileHandler(filename[, mode[, encoding[, delay]]])
指定的文件被打開,用來記錄日誌,假如mode未指示,默認使用a
RotatingFileHandler
支持磁碟文件的回滾
class logging.handlers.RotatingFileHandler(filename, mode='a', maxBytes=0, backupCount=0, encoding=None, delay=0)
你可以使用 maxBytes和backupCount值去讓日誌文件在預設大小時回滾。只要日誌文件在長度上接近maxBytes時,就會關閉舊日誌文件,打開一個新的日誌文件,實現回滾。假如maxBytes或backupCount為0,回滾不會發生。假如backupCount非零,系統會備份舊文件,文件名後加『.1』, 『.2』 。比如,日誌文件名為app.log,backupCount為5,將會得到app.log, app.log.1, app.log.2, 直到app.log.5這6個文件。寫入日誌的文件總是app.log,當這個文件填滿時,就關閉它並重命名為app.log.1, 假如還存在app.log.1, app.log.2等文件,就逐一改名為app.log.2, app.log.3等等。
TimedRotatingFileHandler
支持在指定時間段內回滾日誌
class logging.handlers.TimedRotatingFileHandler(filename, when='h', interval=1, backupCount=0, encoding=None, delay=False, utc=False)
回滾基於when和interval設置,when指定interval的類型,參見下表,大小寫不敏感,默認按小時回滾
Value Type of interval
'S' Seconds
'M' Minutes
'H' Hours
'D' Days
'W0'-'W6' Weekday (0=Monday)
'midnight' Roll over at midnight
回滾擴展名使用strftime format %Y-%m-%d_%H-%M-%S或其頭部子字元串,當使用基於weekday的回滾時,W0表示周一,……,W6表示周日,interval的值不會用到
backupCount表示備份數,當日誌很多時,新日誌會覆蓋舊日誌,刪除邏輯使用interval值去決定刪除哪些日誌文件
utc為true,表示使用UTC時間,否則使用本地時間
SocketHandler
通過網路套接字輸出日誌,SocketHandler類的基類使用TCP socket
class logging.handlers.SocketHandler(host, port)
向指定地址和埠的遠程主機發送日誌
DatagramHandler
繼承自基類SocketHandler類,使用UDP socket發送日誌message
class logging.handlers.DatagramHandler(host, port)
SysLogHandler
發送日誌到遠程或是本地unix syslog
class logging.handlers.SysLogHandler(address=('localhost', SYSLOG_UDP_PORT), facility=LOG_USER, socktype=socket.SOCK_DGRAM)
NTEventLogHandler
發送日誌消息到本地Windows NT, Windows 2000 or Windows XP event log
class logging.handlers.NTEventLogHandler(appname, dllname=None, logtype='Application')
SMTPHandler
通過SMTP將日誌消息發送到email address
MemoryHandler
支持將日誌message緩存到內存中,周期性刷新日誌到target handler
class logging.handlers.BufferingHandler(capacity)
class logging.handlers.MemoryHandler(capacity, flushLevel=ERROR, target=None)
HTTPHandler
使用GET或是POST,將日誌message發送到web server
class logging.handlers.HTTPHandler(host, url, method='GET')
『貳』 python log中文亂碼
Python log出現中文亂碼的解決方法:修改「handle」的「encode」參數為「utf-8」,即在源碼中修改「encoding='utf-8'」。
python log寫入中文亂碼,直接修改handle的encode參數為utf-8
即在源碼中修改encoding='utf-8',因為 logging.basicConfig() 配置時實際上是用到了4大組件,只不過給了默認值,在loging.FileHandler()方法中默認是這樣的。
只需在源碼中修改。
推薦課程:零基礎入門學習Python(小甲魚)
『叄』 python logging 意圖:根據運行的不同時間來創建log文件,而不是固定命名,如:2013-06-13.log
原生loggging類+TimedRotatingFileHandler類實現按dayhoursecond切分
importlogging
fromlogging.
log=logging.getLogger(loggerName)
formatter=logging.Formatter('%(name)-12s%(asctime)slevel-%(levelname)-8sthread-%(thread)-8d%(message)s')#每行日誌的前綴設置
fileTimeHandler=TimedRotatingFileHandler(BASIC_LOG_PATH+filename,"S",1,10)
fileTimeHandler.suffix="%Y%m%d.log"#設置切分後日誌文件名的時間格式默認filename+"."+suffix如果需要更改需要改logging源碼
fileTimeHandler.setFormatter(formatter)
logging.basicConfig(level=logging.INFO)
fileTimeHandler.setFormatter(formatter)
log.addHandler(fileTimeHandler)
try:
log.error(msg)
exceptException,e:
print"writeLogerror"
finally:
log.removeHandler(fileTimeHandler)
值 interval的類型
S 秒
M 分鍾
H 小時
D 天
W 周
midnight 在午夜
『肆』 python 使用logging,生成的log文件是什麼編碼格式腳本的編碼格式決定系統的編碼格式決定
log的文件當然是byte格式。或者是無格式的。漢字編碼取決於你自己設定的類型。
#coding:utf-8這個東西,只在python2下有效果。還需要編程器配合。你使用python自帶的idle當然是沒有問題的。
log中的漢字是一定要編碼的。不編碼你存貯不了。
編輯器本身的預設編碼格式要與你的源代碼編碼一致,不然看到的就是亂碼。如果是idle,它會根據python腳本自動識別。
不過有些編輯器是有些不智能的。它不能理解python腳本第一行的提示。所以有時候,覺著很別扭自己要手工保持編輯器的編碼與源碼一致。還需要維護那個coding:utf-8
不過python3已將這一句去掉了。源代碼全部要求使用utf-8編碼(也許是utf-16),我很少用python3
『伍』 如何動態修改python logging配置文件
配置文件:
#Configuration for log output
#Naiveloafer
#2012-06-04
[loggers]
keys=root,xzs
[handlers]
keys=consoleHandler,fileHandler,rotatingFileHandler
[formatters]
keys=simpleFmt
[logger_root]
level=DEBUG
#handlers=consoleHandler
#handlers=fileHandler
handlers=rotatingFileHandler
[logger_xzs]
level=DEBUG
handlers=rotatingFileHandler
qualname=xzs
propagate=0
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFmt
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=simpleFmt
args=("../log/p2pplayer.log", "a")
[handler_rotatingFileHandler]
class=handlers.RotatingFileHandler
level=DEBUG
formatter=simpleFmt
args=("../log/p2pplayer.log", "a", 20*1024*1024, 10)
[formatter_simpleFmt]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s - [%(filename)s:%(lineno)s]
datefmt=
測試代碼:
def log_test02():
import logging
import logging.config
CONF_LOG = "../conf/p2pplayer_logging.conf"
logging.config.fileConfig(CONF_LOG); # 採用配置文件
logger = logging.getLogger("xzs")
logger.debug("Hello xzs")
logger = logging.getLogger()
logger.info("Hello root")
if __name__ == "__main__":
log_test02()
輸出:
2012-06-04 15:28:05,751 - xzs - DEBUG - Hello xzs - [xlog.py:29]
2012-06-04 15:28:05,751 - root - INFO - Hello root - [xlog.py:32]
具體就不詳細說明了,總之是能夠運行的,這個文件配置搞了我兩天時間。
特別是class=XXXX要注意!!!
『陸』 python之配置日誌的幾種方式
1)使用Python代碼顯式的創建loggers, handlers和formatters並分別調用它們的配置函數;
2)創建一個日誌配置文件,然後使用fileConfig()函數來讀取該文件的內容;
3)創建一個包含配置信息的dict,然後把它傳遞個dictConfig()函數;
『柒』 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法
以上程序結果會輸出到python console中:
讀取配置文件法
其中logging.conf文件格式為:(其實就是將前一種方法的各項配置參數寫到logging.conf文件中)
與前面一樣,上述文件輸出結果為:
『捌』 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()設置屬性具有全局性,第一次設置之後,之後再設置將不再生效。查看官方文檔,也確實是如此。
『玖』 python中log文件和txt文件的區別
沒區別啊。
log.txt是txt文件。
run.log是log文件。但兩個只是後綴格式的不同。都是普通文本文件。沒什麼特別的。
log是日誌的意思
『拾』 Python 將運行結果保存到log文件中遇到的問題
這個簡單啊。通過管道輸出到另一個程序里去,另外一個程序同時列印並輸出到out.log
這是我常用的辦法。
還有一個笨辦法,用自己的myprint代替所有的print語句。這樣你可以同時輸出到屏幕與文件了。
第三個辦法是通過logging。這個模塊支持多個listener,可以同時輸出到屏幕與文件以及網路。