Python logging模塊進行封裝實現原理解析
1. 簡介
追蹤某些軟件運行時所發生事件的方法, 可以在代碼中調用日志中某些方法來記錄發生的事情
一個事件可以用一個可包含可選變量數據的消息來描述
事件有自己的重要性等級
2. 使用logging日志系統四大組件
loggers日志器 提供應用程序代碼直接使用的接口 handlers處理器 用于將日志記錄發送到指定的目的位置 filters過濾器 過濾, 決定哪些輸出哪些日志記錄, 其余忽略 formatters格式器 控制日志輸出格式使用代碼如下
import os, time, logging, sysfrom Common.plugs.get_config import r_configBASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))if sys.platform == 'win32': ENV_CONF_DIR = os.path.join(BASE_DIR, ’Common/conf/env_config.ini’).replace(’/’, ’’)else: ENV_CONF_DIR = os.path.join(BASE_DIR, ’Common/conf/env_config.ini’)log_path = r_config(ENV_CONF_DIR, 'log', 'log_path')class Log: def __init__(self, log_path): self.logName = os.path.join(log_path, ’{0}.log’.format(time.strftime(’%Y-%m-%d’))) def console_log(self, level, message): # 創建一個logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 創建一個handler,用于 debug 寫入日志文件 debug_file = logging.FileHandler(self.logName, ’a+’, encoding=’utf-8’) debug_file.setLevel(logging.DEBUG) # 再創建一個handler,用于輸出到控制臺 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # 定義handler的輸出格式 formatter = logging.Formatter(’%(asctime)s - %(name)s - %(levelname)s - %(message)s’) debug_file.setFormatter(formatter) ch.setFormatter(formatter) # 給logger添加handler logger.addHandler(debug_file) logger.addHandler(ch) # 記錄一條日志 if level == ’info’: logger.info(message) elif level == ’debug’: logger.debug(message) elif level == ’warning’: logger.warning(message) elif level == ’error’: logger.error(message) elif level == ’critical’: logger.critical(message) logger.removeHandler(ch) logger.removeHandler(debug_file) debug_file.close() def debug(self, message): #最詳細日志信息, 多用于問題診斷 self.console_log(’debug’, message) def info(self, message): #僅次于DEBUG, 多用于記錄關鍵點信息, 確保程序按預期執行 self.console_log(’info’, message) def warning(self, message): #低等級故障, 但程序仍能運行, 如磁盤空間不足警告 self.console_log(’warning’, message) def error(self, message): #由于比WARNING嚴重的問題, 導致某些功能不能正常運行時的記錄 self.console_log(’error’, message) def critical(self, message): 嚴重錯誤, 導致應用程序不能繼續運行時的記錄 self.console_log(’critical’, message)if __name__ == ’__main__’: Log(log_path).info('adasd') Log(log_path).error('dsadasddasd')’’’
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章: