python的logging模組,pythonlogging模組
Python的logging模組一、簡單的將日誌列印到螢幕
import logging
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
輸出結果為WARNING:root:This is warning message。
預設情況下,logging將日誌列印到螢幕,記錄層級為WARNING;記錄層級大小關係為:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,當然也可以自己定義記錄層級。
二、通過logging.basicConfig函數對日誌的輸出格式及方式做相關配置
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='myapp.log',
filemode='w')
logging.debug('This is debug message')
logging.info('This is info message')
logging.warning('This is warning message')
結果為在程式所在目錄下產生一個名為“myapp.log”的檔案,檔案內容為:Sun, 29 Oct 2017 18:00:04 test2.py[line:26] DEBUG This is debug message
Sun, 29 Oct 2017 18:00:04 test2.py[line:27] INFO This is info message
Sun, 29 Oct 2017 18:00:04 test2.py[line:28] WARNING This is warning message
如果,再次運行改程式,則檔案myapp.log裡的內容會被覆蓋掉。若想在檔案裡繼續新增內容則需將filemode=‘w’改為filemode=‘a’。
logging.basicConfig函數各參數:
filename: 指定記錄檔名
filemode: 和file函數意義相同,指定記錄檔的開啟模式,'w'或'a'
format: 指定輸出的格式和內容,format可以輸出很多有用資訊,如上例所示:
%(levelno)s: 列印記錄層級的數值
%(levelname)s: 列印記錄層級名稱
%(pathname)s: 列印當前執行程式的路徑,其實就是sys.argv[0]
%(filename)s: 列印當前執行程式名
%(funcName)s: 列印日誌的當前函數
%(lineno)d: 列印日誌的當前行號
%(asctime)s: 列印日誌的時間
%(thread)d: 列印線程ID
%(threadName)s: 列印線程名稱
%(process)d: 列印進程ID
%(message)s: 列印日誌資訊
datefmt: 指定時間格式,同time.strftime()
level: 設定記錄層級,預設為logging.WARNING
stream: 指定將日誌的輸出資料流,可以指定輸出到sys.stderr,sys.stdout或者檔案,預設輸出到sys.stderr,當stream和filename同時指定時,stream被忽略
三、將日誌同時輸出到檔案和螢幕
import logging
logger = logging.getLogger() #建立一個logger對象
fh=logging.FileHandler('test.log') #檔案輸出資料流對象
ch=logging.StreamHandler() #螢幕輸出資料流對象
formatter = logging.Formatter('%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s') #建立輸出格式
fh.setFormatter(formatter) #檔案輸出引用建立的格式
ch.setFormatter(formatter) #螢幕輸出引用建立的格式
logger.addHandler(fh) #進行檔案輸出
logger.addHandler(ch) #進行螢幕輸出
logger.setLevel(logging.DEBUG) #修改輸出記錄層級
logger.debug('This is debug message')
logger.info('This is info message')
logger.warning('This is warning message')
結果為在程式所在目錄下產生一個名為“test.log”的檔案,檔案內容為2017-10-29 18:50:09,717 test2.py[line:29] DEBUG This is debug message
2017-10-29 18:50:09,717 test2.py[line:30] INFO This is info message
2017-10-29 18:50:09,718 test2.py[line:31] WARNING This is warning message
;螢幕顯示2017-10-29 18:50:09,717 test2.py[line:29] DEBUG This is debug message
2017-10-29 18:50:09,717 test2.py[line:30] INFO This is info message
2017-10-29 18:50:09,718 test2.py[line:31] WARNING This is warning message
建立輸出格式時,使用的是logging.basicConfig函數各參數:。
如果不修改輸出記錄層級,預設是輸出WARNING記錄層級以上及其本身的日誌內容。
該方法實質思路如: