python筆記--內置模塊之logging
阿新 • • 發佈:2018-05-06
內置模塊logging模塊
顧名思義,用於程序日誌輸出,可以設置日誌級別、格式、輸出方式等,基本使用方法如下:
1、logging.basicConfig方式
簡單的配置,只能選擇單獨輸出到屏幕或輸出到文件,不能同時輸出。例如:
#-*- coding:utf-8 -*- #只能選擇輸出到屏幕或文件 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='a') ''' 參數: level:指定輸出的日誌級別 format:指定日誌格式,包括: asctime:時間 filename:日誌歸屬的文件名稱 lineno:日誌對應代碼在歸屬文件中的行號 levelname:日至最低級別,不指定默認為warning message:具體的日誌內容, datefmt:指定具體的時間格式,如果不指定,asctime將使用默認格式,如:2018-05-05 22:07:30,578 filename:指定日誌文件名稱,可攜帶具體路徑,不指定該參數時日誌輸出到屏幕 filemode:指定日誌寫入模式,默認為'a'表示追加,可以指定為'w'表示覆蓋 ''' logging.debug('debug message') logging.info('info message') logging.warning('warning message') logging.error('error message') logging.critical('critical message')
上面例子將日誌輸出到test.log文件,內容:
Sat,05 May 2018 22:25:14 2.py[line:22] DEBUG debug message Sat,05 May 2018 22:25:14 2.py[line:23] INFO info message Sat,05 May 2018 22:25:14 2.py[line:24] WARNING warning message Sat,05 May 2018 22:25:14 2.py[line:25] ERROR error message Sat,05 May 2018 22:25:14 2.py[line:26] CRITICAL critical message
如果,只需要日誌輸出到屏幕,只需要將filename='test.log'和filemode='a'兩行註釋掉即可。
2、logging.getLogger方式
完整配置,即可單獨輸出到屏幕或文件,也可同時輸出。例如:
#-*- coding:utf-8 -*- #日誌輸出更靈活,可以分別或同時輸出到屏幕和文件 import logging #創建一個logger對象 logger=logging.getLogger() #創建一個文件輸出流handler,用於寫入日誌文件 fm=logging.FileHandler('test1.log') #再創建一個標準輸出流handler,用於輸出到屏幕 pm=logging.StreamHandler() #創建一個日誌格式對象 formatter=logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') #為兩個handler添加日誌格式 fm.setFormatter(formatter) pm.setFormatter(formatter) #為logger對象添加handler logger.addHandler(fm) logger.addHandler(pm) #設置輸出日誌級別,默認只輸出warning以上 logger.setLevel(logging.DEBUG) logger.debug('debug message') logger.info('info message') logger.warning('warning message') logger.error('error message') logger.critical('critical message')
上面例子,將日誌同時輸出到屏幕和test1.log文件,內容:
2018-05-05 22:32:52,800 3.py[line:28] DEBUG debug message 2018-05-05 22:32:52,800 3.py[line:29] INFO info message 2018-05-05 22:32:52,800 3.py[line:30] WARNING warning message 2018-05-05 22:32:52,800 3.py[line:31] ERROR error message 2018-05-05 22:32:52,800 3.py[line:32] CRITICAL critical message
logger.addHandler()決定日誌輸出方向,如果只輸出到某一方面,可以將另一行註釋掉。
python筆記--內置模塊之logging