Python中日誌模組Logging模組詳述
Python中的日誌模組,使用使用logging模組,該模組自2.3版本開始便是Python標準庫的一部分。
日誌的兩個目的:
- 診斷功能: 記錄與應用程式操作相關的日誌,方便診斷。
- 審計功能: 為商業分析而記錄的日誌,具備審計的功能。
日誌 vs 列印
當列印顯示幫助文件時,列印無疑是個不錯的選擇,但是更多情況,都是日誌的方式更優秀,原因如下:
- 日誌事件產生的日誌記錄 ,包含清晰可用的診斷資訊,如檔名稱、路徑、函式名和行號等。
- 包含日誌模組的應用,預設可通過根記錄器對應用的日誌流進行訪問,除非你將日誌過濾了。
- 可通過 logging.Logger.setLevel() 方法有選擇地記錄日誌, 或可通過設定logging.Logger.disabled 屬性為True來禁用。
配置日誌常用的三種方式:
方式一:使用INI格式檔案
1. 配置檔案config.ini
[loggers] keys=root [handlers] keys=stream_handler [formatters] keys=formatter [logger_root] level=DEBUG handlers=stream_handler [handler_stream_handler] class=StreamHandler level=DEBUG formatter=formatter args=(sys.stderr,) [formatter_formatter] format=%(asctime)s %(name)-12s %(levelname)-8s %(message)s
2. 在原始碼中呼叫logging.config.fileConfig()方法
import logging from logging.config import fileConfig fileConfig('logging_config.ini') logger = logging.getLogger() logger.debug('often makes a very good meal of %s', 'visiting tourists')
3. 列印輸出
2018-09-15 09:34:37,361 rootDEBUGoften makes a very good meal of visiting tourists
方式二:使用字典或JSON格式檔案
import logging from logging.config import dictConfig logging_config = dict( version = 1, formatters = { 'f': {'format': '%(asctime)s %(name)-12s %(levelname)-8s %(message)s'} }, handlers = { 'h': {'class': 'logging.StreamHandler', 'formatter': 'f', 'level': logging.DEBUG} }, root = { 'handlers': ['h'], 'level': logging.DEBUG, }, ) dictConfig(logging_config) logger = logging.getLogger() logger.debug('often makes a very good meal of %s', 'visiting tourists')
方式三:使用原始碼
import logging logger = logging.getLogger() handler = logging.StreamHandler() formatter = logging.Formatter( '%(asctime)s %(name)-12s %(levelname)-8s %(message)s') handler.setFormatter(formatter) logger.addHandler(handler) logger.setLevel(logging.DEBUG) logger.debug('often makes a very good meal of %s', 'visiting tourists')
幾種配置檔案優缺點比較:
使用INI格式檔案:
- 優點: 使用 logging.config.listen() 函式監聽socket,可在執行過程中更新配置
- 缺點: 通過原始碼控制日誌配置較少( 例如 子類化定製的過濾器或記錄器)。
使用字典或JSON格式檔案:
- 優點: 除了可在執行時動態更新,在Python 2.6之後,還可通過 json 模組從其它檔案中匯入配置。
- 缺點: 很難通過原始碼控制日誌配置。
使用原始碼:
- 優點: 對配置絕對的控制。
- 缺點: 對配置的更改需要對原始碼進行修改。
Linux公社的RSS地址:ofollow,noindex" target="_blank">https://www.linuxidc.com/rssFeed.aspx
本文永久更新連結地址:https://www.linuxidc.com/Linux/2018-09/154261.htm