1. 程式人生 > >python 內建模組之logging

python 內建模組之logging

python 內建的模組很多,其中之一是logging 。

使用方式一

import logging  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')  

輸出如下

WARNING:root:warning message
ERROR:root:error message
CRITICAL
:root:critical message

可見,預設情況下Python的logging模組將日誌列印到了標準輸出中,且只顯示了大於等於WARNING級別的日誌,這說明預設的日誌級別設定為WARNING(日誌級別等級CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET),預設的日誌格式為日誌級別:Logger名稱:使用者輸出訊息。
使用方式二

import logging

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s'
, datefmt='%a, %d %b %Y %H:%M:%S', filename='test.log', filemode='w') logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')

結果如下:

Tue, 04 Sep 2018 14:33:13 logging_module.py[line:11] DEBUG debug message
Tue, 04 Sep 2018 14:33:13 logging_module.py[line:12] INFO info message
Tue, 04 Sep 2018 14:33:13 logging_module.py[line:13] WARNING warning message
Tue, 04 Sep 2018 14:33:13 logging_module.py[line:14] ERROR error message
Tue, 04 Sep 2018 14:33:13 logging_module.py[line:15] CRITICAL critical message

以上內容會被寫入test.log 檔案中

使用方式三

import logging

logger = logging.getLogger()
# 建立一個handler,用於寫入日誌檔案
fh = logging.FileHandler('test1.log')
logger.setLevel(logging.DEBUG)
# 再建立一個handler,用於輸出到控制檯
ch = logging.StreamHandler()

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh) #logger物件可以新增多個fh和ch物件
logger.addHandler(ch)

logger.debug('logger debug message')
logger.info('logger info message')
logger.warning('logger warning message')
logger.error('logger error message')
logger.critical('logger critical message')

結果如下:

2018-09-04 14:25:01,953 - root - DEBUG - logger debug message
2018-09-04 14:25:01,954 - root - INFO - logger info message
2018-09-04 14:25:01,954 - root - WARNING - logger warning message
2018-09-04 14:25:01,954 - root - ERROR - logger error message
2018-09-04 14:25:01,954 - root - CRITICAL - logger critical message

以下內容將會被寫入test1.log 檔案中