這篇文章主要介紹了Python中l(wèi)ogging模塊進(jìn)行封裝的案例分析,具有一定借鑒價值,需要的朋友可以參考下。希望大家閱讀完這篇文章后大有收獲。下面讓小編帶著大家一起了解一下。
1. 簡介
追蹤某些軟件運(yùn)行時所發(fā)生事件的方法, 可以在代碼中調(diào)用日志中某些方法來記錄發(fā)生的事情
一個事件可以用一個可包含可選變量數(shù)據(jù)的消息來描述
事件有自己的重要性等級
2. 使用logging日志系統(tǒng)四大組件
使用代碼如下
import os, time, logging, sys from Common.plugs.get_config import r_config BASE_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): # 創(chuàng)建一個logger logger = logging.getLogger() logger.setLevel(logging.DEBUG) # 創(chuàng)建一個handler,用于 debug 寫入日志文件 debug_file = logging.FileHandler(self.logName, 'a+', encoding='utf-8') debug_file.setLevel(logging.DEBUG) # 再創(chuàng)建一個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): #最詳細(xì)日志信息, 多用于問題診斷 self.console_log('debug', message) def info(self, message): #僅次于DEBUG, 多用于記錄關(guān)鍵點(diǎn)信息, 確保程序按預(yù)期執(zhí)行 self.console_log('info', message) def warning(self, message): #低等級故障, 但程序仍能運(yùn)行, 如磁盤空間不足警告 self.console_log('warning', message) def error(self, message): #由于比WARNING嚴(yán)重的問題, 導(dǎo)致某些功能不能正常運(yùn)行時的記錄 self.console_log('error', message) def critical(self, message): 嚴(yán)重錯誤, 導(dǎo)致應(yīng)用程序不能繼續(xù)運(yùn)行時的記錄 self.console_log('critical', message) if __name__ == '__main__': Log(log_path).info("adasd") Log(log_path).error("dsadasddasd") '''
網(wǎng)站欄目:Python中l(wèi)ogging模塊進(jìn)行封裝的案例分析-創(chuàng)新互聯(lián)
分享地址:http://www.ekvhdxd.cn/article14/dojege.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站排名、定制開發(fā)、手機(jī)網(wǎng)站建設(shè)、建站公司、網(wǎng)站建設(shè)、網(wǎng)站策劃
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容