1. 程式人生 > >Python基礎-logging模塊

Python基礎-logging模塊

路徑 日誌級別 .get 一個 style 自定義 表示 級別 pro

日誌的級別
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=a ) logging.debug(
debug message) logging.info(info message) logging.warning(warning message) logging.error(error message) logging.critical(critical message) 執行結果會在工作目錄下生成一個test.log文件,內容如下: Tue, 17 Oct 2017 14:08:22 test.py[line:13] DEBUG debug message Tue, 17 Oct 2017 14:08:22 test.py[line:14] INFO info message Tue,
17 Oct 2017 14:08:22 test.py[line:15] WARNING warning message Tue, 17 Oct 2017 14:08:22 test.py[line:16] ERROR error message Tue, 17 Oct 2017 14:08:22 test.py[line:17] CRITICAL critical message
logging.basicConfig()函數中的參數及說明如下:
filename:用指定的文件名創建FiledHandler(後邊會具體講解handler的概念),這樣日誌會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值為“a”還可指定為“w”。
format:指定handler使用的日誌顯示格式。
datefmt:指定日期時間格式。
level:設置rootlogger(後邊會講解具體概念)的日誌級別
stream:用指定的stream創建StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者文件(f=open(‘test.log‘,‘w‘)),默認為sys.stderr。若同時列出了filename和stream兩個參數,則stream參數會被忽略。
format參數中可能用到的格式化串:
%(name)s Logger的名字
%(levelno)s 數字形式的日誌級別
%(levelname)s 文本形式的日誌級別
%(pathname)s 調用日誌輸出函數的模塊的完整路徑名,可能沒有
%(filename)s 調用日誌輸出函數的模塊的文件名
%(module)s 調用日誌輸出函數的模塊名
%(funcName)s 調用日誌輸出函數的函數名
%(lineno)d 調用日誌輸出函數的語句所在的代碼行
%(created)f 當前時間,用UNIX標準的表示時間的浮 點數表示
%(relativeCreated)d 輸出日誌信息時的,自Logger創建以 來的毫秒數
%(asctime)s 字符串形式的當前時間。默認格式是 “2003-07-08 16:49:45,896”。逗號後面的是毫秒
%(thread)d 線程ID。可能沒有
%(threadName)s 線程名。可能沒有
%(process)d 進程ID。可能沒有
%(message)s用戶輸出的消息

將日誌同時輸出到屏幕和文件
logger = logging.getLogger()
fh = logging.FileHandler(test.log)
ch = logging.StreamHandler()
formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
fh.setFormatter(formatter)
ch.setFormatter(formatter)
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)
logger.addHandler(ch)
logging.debug(debug message)
logging.info(info message)
logging.warning(warning message)
logging.error(error message)
logging.critical(critical message)

Python基礎-logging模塊