logging爲python模塊提供狀態、錯誤、信息輸出的標準接口。
日誌級別大小關係爲:CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET
logging.basicConfig函數各參數說明:
filename: 指定日誌文件名
filemode: 和file函數意義相同,指定日誌文件的打開模式,'w'或'a'
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被忽略
記錄日誌信息
#!/usr/bin/env python #coding: utf-8 import logging # 記錄日誌信息 logname = 'log.log' logging.basicConfig( level = logging.INFO, #定義記錄大於或等於日誌級別 format='[%(levelname)s] [%(asctime)s] --- %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=logname, filemode='a', ) logging.warning("log")
將日誌輸出到文件,同時打印匹配的級別到屏幕上
#!/usr/bin/env python #coding: utf-8 import logging # 記錄日誌信息 logname = 'log.log' logging.basicConfig( level = logging.INFO, #定義記錄大於或等於日誌級別 format='[%(levelname)s] [%(asctime)s] --- %(message)s', datefmt='%Y-%m-%d %H:%M:%S', filename=logname, filemode='a', ) console = logging.StreamHandler() console.setLevel(logging.INFO) #定義需要顯示大於或等於日誌級別 formatter = logging.Formatter('[%(levelname)s] [%(asctime)s] ------ %(message)s') console.setFormatter(formatter) logging.getLogger('').addHandler(console) logging.warning('log info')