一、Log的作用及Python Logging模塊簡介
在程序開發中,日誌是開發者必不可少的一部分。它可以記錄程序運行的一些狀態及出現的錯誤,便於後續的排查和優化。而Python Logging模塊則是Python自帶的一個內置日誌管理模塊,它可以方便地記錄日誌並對日誌進行分類處理,同時還支持自定義日誌格式、日誌級別等功能。
Python Logging模塊中常用的四個組件分別為:Logger、Handler、Formatter、Filter。Logger代表著一個日誌記錄器,用於記錄日誌,在Logger中可以設定日誌的級別、輸出目標以及日誌記錄器的名稱等;Handler則是用於將日誌信息輸出到特定的位置,如控制台、文件等,一個Logger可以同時綁定多個Handler;Formatter則是定義的日誌輸出格式,可以包括時間、日誌級別、線程ID、日誌內容等;Filter則是對日誌記錄進行過濾,只有符合過濾條件的才能輸出,否則忽略此記錄。
下面是一個簡單的Python Logging模塊使用示例:
import logging # 創建Logger對象 logger = logging.getLogger('example_logger') logger.setLevel(logging.DEBUG) # 創建FileHandler對象 file_handler = logging.FileHandler('example.log') file_handler.setLevel(logging.INFO) # 創建Formatter對象 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) # 綁定Handler logger.addHandler(file_handler) # 輸出日誌 logger.info('Info message') logger.debug('Debug message') logger.warning('Warning message')
二、Python Logging模塊高級功能
Python Logging模塊除了基本的日誌記錄外,還支持一些高級功能,如:
1、日誌輪替
在日誌記錄中,如果一直向同一個文件輸出日誌,那麼文件大小會不停增大,不方便後續的查看和管理。因此,日誌輪替可以實現定時或按日誌文件大小生成新的日誌文件並寫入日誌信息。
日誌輪替有兩種方式,一種是根據時間輪替,另一種是根據日誌文件大小輪替。以下是一個根據時間輪替的示例:
import logging import logging.handlers # 創建TimeRotatingFileHandler對象 file_handler = logging.handlers.TimedRotatingFileHandler('example.log', when='midnight', interval=1, backupCount=5) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) logger = logging.getLogger('example_logger') logger.addHandler(file_handler) logger.info('Info message') logger.debug('Debug message') logger.warning('Warning message')
2、日誌回滾
在日誌記錄中,如果出現程序異常導致日誌輸出被打斷,那麼在之後的日誌記錄中將無法繼續寫入原來的日誌文件中,因此,可以使用日誌回滾功能,將程序異常中斷前未寫入的日誌記錄存儲到本地的其他文件中以保證日誌記錄的完整性。
以下是一個根據程序異常回滾的示例:
import logging import logging.handlers # 創建RotatingFileHandler對象 file_handler = logging.handlers.RotatingFileHandler('example.log', maxBytes=100, backupCount=5) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') file_handler.setFormatter(formatter) logger = logging.getLogger('example_logger') logger.addHandler(file_handler) try: # 執行程序代碼 except Exception as e: logger.error('Exception occurred: %s', e, exc_info=True) logger.info('Info message') logger.debug('Debug message') logger.warning('Warning message')
三、Python Logging模塊案例分享
下面是一個模擬銀行交易系統的Python Logging模塊案例:
import logging from logging.handlers import TimedRotatingFileHandler class BankSystemLogging: def __init__(self, logger_name): self.logger = logging.getLogger(logger_name) self.logger.setLevel(logging.DEBUG) # 定義日誌格式 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # 控制台輸出日誌 console_handler = logging.StreamHandler() console_handler.setLevel(logging.WARNING) console_handler.setFormatter(formatter) # 按天輪替日誌文件 file_handler = TimedRotatingFileHandler('bank_transaction.log', when='midnight', interval=1, backupCount=5, encoding='utf-8') file_handler.setLevel(logging.DEBUG) file_handler.setFormatter(formatter) self.logger.addHandler(console_handler) self.logger.addHandler(file_handler) # 記錄交易日誌 def transaction(self, account, amount): self.logger.info('Transaction: account=%s, amount=%s', account, amount) # 記錄異常日誌 def exception(self, msg): self.logger.error(msg, exc_info=True) # 使用示例 logger = BankSystemLogging('bank_system') try: # 執行銀行交易代碼 except Exception as e: logger.exception('Exception occurred: %s', str(e))
四、總結
Python Logging模塊是Python自帶的一個內置日誌管理模塊,可以方便地記錄日誌並對日誌進行分類處理,同時支持自定義日誌格式、日誌級別等高級功能。在程序開發中,合理利用Python Logging模塊可以提高程序的開發效率。
原創文章,作者:MXIA,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/138740.html