本文目錄一覽:
python日誌模塊記錄三_日誌命名_日誌輪轉
在日誌記錄中,我們往往要能看到是什麼哪裡出錯了。可以通過日誌名字記錄哪裡出錯了。而日誌也需要輪轉,一個日誌文件不能無限大,也需要備份。所以有了通過日誌名的靈活配置,和通過設置handler文件輸出調用 logging.handlers.RotatingFileHandler 方法來實現輪轉和備份。
my_logging文件如下配置
python程序中logging怎麼用
簡單將日誌列印到屏幕:
[python] view plain copy
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名稱:用戶輸出消息。
靈活配置日誌級別,日誌格式,輸出位置
[python] view plain copy
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=’/tmp/test.log’,
filemode=’w’)
logging.debug(‘debug message’)
logging.info(‘info message’)
logging.warning(‘warning message’)
logging.error(‘error message’)
logging.critical(‘critical message’)
查看輸出:
cat /tmp/test.log
Mon, 05 May 2014 16:29:53 test_logging.py[line:9] DEBUG debug message
Mon, 05 May 2014 16:29:53 test_logging.py[line:10] INFO info message
Mon, 05 May 2014 16:29:53 test_logging.py[line:11] WARNING warning message
Mon, 05 May 2014 16:29:53 test_logging.py[line:12] ERROR error message
Mon, 05 May 2014 16:29:53 test_logging.py[line:13] CRITICAL critical message
可見在logging.basicConfig()函數中可通過具體參數來更改logging模塊默認行為,可用參數有
filename:用指定的文件名創建FiledHandler(後邊會具體講解handler的概念),這樣日誌會被存儲在指定的文件中。
filemode:文件打開方式,在指定了filename時使用這個參數,默認值為「a」還可指定為「w」。
format:指定handler使用的日誌顯示格式。
datefmt:指定日期時間格式。
level:設置rootlogger(後邊會講解具體概念)的日誌級別
stream:用指定的stream創建StreamHandler。可以指定輸出到sys.stderr,sys.stdout或者文件,默認為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用戶輸出的消息
python日誌記錄模塊主要作用是什麼呢,求具體例子
4個主要的組件
logger: 日誌類,應用程序往往通過調用它提供的api來記錄日誌;
handler: 對日誌信息處理,可以將日誌發送(保存)到不同的目標域中;
filter: 對日誌信息進行過濾;
formatter:日誌的格式化;
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/287190.html