Python中logging日誌庫例項詳解
logging的簡單使用
用作記錄日誌,預設分為六種日誌級別(括號為級別對應的數值)
- NOTSET(0)
- DEBUG(10)
- INFO(20)
- WARNING(30)
- ERROR(40)
- CRITICAL(50)
special
- 在自定義日誌級別時注意不要和預設的日誌級別數值相同
- logging 執行時輸出大於等於設定的日誌級別的日誌資訊,如設定日誌級別是 INFO,則 INFO、WARNING、ERROR、CRITICAL 級別的日誌都會輸出。
|2logging常見物件
- Logger:日誌,暴露函式給應用程式,基於日誌記錄器和過濾器級別決定哪些日誌有效。
- LogRecord :日誌記錄器,將日誌傳到相應的處理器處理。
- Handler :處理器,將(日誌記錄器產生的)日誌記錄傳送至合適的目的地。
- Filter :過濾器,提供了更好的粒度控制,它可以決定輸出哪些日誌記錄。
- Formatter:格式化器,指明瞭最終輸出中日誌記錄的格式。
|3logging基本使用
logging 使用非常簡單,使用 basicConfig()
方法就能滿足基本的使用需要;如果方法沒有傳入引數,會根據預設的配置建立Logger 物件,預設的日誌級別被設定為 WARNING,該函式可選的引數如下表所示。
引數名稱 |
引數描述 |
---|---|
filename |
日誌輸出到檔案的檔名 |
filemode |
檔案模式,r[+]、w[+]、a[+] |
format |
日誌輸出的格式 |
datefat |
日誌附帶日期時間的格式 |
style |
格式佔位符,預設為 "%" 和 “{}” |
level |
設定日誌輸出級別 |
stream |
定義輸出流,用來初始化 StreamHandler 物件,不能 filename 引數一起使用,否則會ValueError 異常 |
handles |
定義處理器,用來建立 Handler 物件,不能和 filename 、stream 引數一起使用,否則也會丟擲 ValueError 異常 |
logging程式碼
logging.debug("debug") logging.info("info") logging.warning("warning") logging.error("error")5 logging.critical("critical")
測試結果
WARNING:root:warning
ERROR:root:error
CRITICAL:root:critical
但是當發生異常時,直接使用無引數的 debug() 、 info() 、 warning() 、 error() 、 critical() 方法並不能記錄異常資訊,需要設定 exc_info=True 才可以,或者使用 exception() 方法,還可以使用 log() 方法,但還要設定日誌級別和 exc_info 引數
a = 5 b = 0 try: c = a / b except Exception as e: # 下面三種方式三選一,推薦使用第一種 logging.exception("Exception occurred") logging.error("Exception occurred",exc_info=True) logging.log(level=logging.ERROR,msg="Exception occurred",exc_info=True)
|4logging之Formatter物件
Formatter 物件用來設定具體的輸出格式,常用格式如下表所示
格式 |
變數描述 |
---|---|
%(asctime)s |
將日誌的時間構造成可讀的形式,預設情況下是精確到毫秒,如 2018-10-13 23:24:57,832,可以額外指定 datefmt 引數來指定該變數的格式 |
%(name) |
日誌物件的名稱 |
%(filename)s |
不包含路徑的檔名 |
%(pathname)s |
包含路徑的檔名 |
%(funcName)s |
日誌記錄所在的函式名 |
%(levelname)s |
日誌的級別名稱 |
%(message)s |
具體的日誌資訊 |
%(lineno)d |
日誌記錄所在的行號 |
%(pathname)s |
完整路徑 |
%(process)d |
當前程序ID |
%(processName)s |
當前程序名稱 |
%(thread)d |
當前執行緒ID |
%threadName)s |
當前執行緒名稱 |
|5logging封裝類
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = logging工具類 __Time__ = 2019/8/8 19:26 """ import logging from logging import handlers class Loggers: __instance = None def __new__(cls,*args,**kwargs): if not cls.__instance: cls.__instance = object.__new__(cls,**kwargs) return cls.__instance def __init__(self): # 設定輸出格式 formater = logging.Formatter( '[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] : %(message)s') # 定義一個日誌收集器 self.logger = logging.getLogger('log') # 設定級別 self.logger.setLevel(logging.DEBUG) # 輸出渠道一 - 檔案形式 self.fileLogger = handlers.RotatingFileHandler("./test.log",maxBytes=5242880,backupCount=3) # 輸出渠道二 - 控制檯 self.console = logging.StreamHandler() # 控制檯輸出級別 self.console.setLevel(logging.DEBUG) # 輸出渠道對接輸出格式 self.console.setFormatter(formater) self.fileLogger.setFormatter(formater) # 日誌收集器對接輸出渠道 self.logger.addHandler(self.fileLogger) self.logger.addHandler(self.console) def debug(self,msg): self.logger.debug(msg=msg) def info(self,msg): self.logger.info(msg=msg) def warn(self,msg): self.logger.warning(msg=msg) def error(self,msg): self.logger.error(msg=msg) def excepiton(self,msg): self.logger.exception(msg=msg) loggers = Loggers() if __name__ == '__main__': loggers.debug('debug') loggers.info('info')
|6logzero封裝類
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __title__ = logzero日誌封裝類 __Time__ = 2019/8/8 19:26 """ import logging import logzero from logzero import logger class Logzero(object): __instance = None def __new__(cls,**kwargs) return cls.__instance def __init__(self): self.logger = logger # console控制檯輸入日誌格式 - 帶顏色 self.console_format = '%(color)s' \ '[%(asctime)s]-[%(levelname)1.1s]-[%(filename)s]-[%(funcName)s:%(lineno)d] 日誌資訊: %(message)s ' \ '%(end_color)s ' # 建立一個Formatter物件 self.formatter = logzero.LogFormatter(fmt=self.console_format) # 將formatter提供給setup_default_logger方法的formatter引數 logzero.setup_default_logger(formatter=self.formatter) # 設定日誌檔案輸出格式 self.formater = logging.Formatter( '[%(asctime)s]-[%(levelname)s]-[%(filename)s]-[%(funcName)s:%(lineno)d] 日誌資訊: %(message)s') # 設定日誌檔案等級 logzero.loglevel(logging.DEBUG) # 輸出日誌檔案路徑和格式 logzero.logfile("F:\\imocInterface\\log/tests.log",formatter=self.formater) def debug(self,msg): self.logger.info(msg=msg) def warning(self,msg): self.logger.error(msg=msg) def exception(self,msg): self.logger.exception(msg=msg) logzeros = Logzero() if __name__ == '__main__': logzeros.debug("debug") logzeros.info("info") logzeros.warning("warning") logzeros.error("error") a = 5 b = 0 try: c = a / b except Exception as e: logzeros.exception("Exception occurred")
總結
以上所述是小編給大家介紹的Python中logging日誌庫例項詳解,希望對大家有所幫助,也非常感謝大家對我們網站的支援!