標籤:python logging
Python內建Tlog模組logging
預設的記錄層級有DEBUG,INFO,WARNING,ERROR,CRITICAL,對應的函數是debug(),info(),warning(),error()和critical()
In [490]: import loggingIn [491]: LOG_FILENAME=‘/tmp/example.log‘In [492]: logging.basicConfig(filename=LOG_FILENAME,level=logging.DEBUG)In [493]: logging.debug(‘This message should go to the log file‘)
查看/tmp/example.log的內容
$ cat /tmp/example.log DEBUG:root:This message should go to the log file
不斷執行
logging.debug(‘This message should go to the log file‘)
/tmp/example.log會不斷地重新整理
日誌輪轉
In [639]: import globIn [640]: import loggingIn [641]: import logging.handlersIn [642]: LOG_FILENAME=‘/tmp/logging_rotatingfile_example.out‘In [643]: my_logger=logging.getLogger(‘MyLogger‘)In [644]: my_logger.setLevel(logging.DEBUG)In [645]: handler=logging.handlers.RotatingFileHandler(LOG_FILENAME,maxBytes=20,backupCount=5)In [646]: my_logger.addHandler(handler)In [648]: for i in range(20): my_logger.debug(‘i=%d‘ % i) .....: .....: In [650]: logfiles=glob.glob(‘%s*‘ %LOG_FILENAME)In [651]: for filename in logfiles: .....: print filename .....: .....: /tmp/logging_rotatingfile_example.out.1/tmp/logging_rotatingfile_example.out.2/tmp/logging_rotatingfile_example.out.5/tmp/logging_rotatingfile_example.out.3/tmp/logging_rotatingfile_example.out.4/tmp/logging_rotatingfile_example.out
最近的記錄檔總是名為logging_rotatingfile_example.out,一旦大小達到maxBytes設定的20位元組,就將輪轉。
logging模組最重要的一個功能就是可以根據設定的不同的記錄層級輸出不同的日誌資訊。
參考文檔:
https://docs.python.org/2.6/library/logging.html#configuration-file-format
本文出自 “Linux SA John” 部落格,請務必保留此出處http://john88wang.blog.51cto.com/2165294/1622501
Python學習之logging模組