python將logging模塊封裝成單獨(dú)模塊并實(shí)現(xiàn)動(dòng)態(tài)切換Level方式
查找了很多資料,但網(wǎng)上給出的教程都是大同小異的,而我想將代碼進(jìn)一步精簡(jiǎn),解耦,想實(shí)現(xiàn)如下兩個(gè)目標(biāo)
1. 將logging模塊的初始化,配置,設(shè)置等代碼封裝到一個(gè)模塊中;
2. 能根據(jù)配置切換logging.level, 網(wǎng)上給出的教程都是寫死的,如果我在線上之前使用了logging.info(msg),現(xiàn)在想切換為logging.debug(msg)怎么辦?需要能夠根據(jù)配置文件中的 設(shè)置配置logging.level
兩個(gè)文件:
logging_class:將logging模塊的初始化,配置,設(shè)置等代碼封裝到一此模塊中,讀取配置文件中對(duì)于log等級(jí)的設(shè)置項(xiàng);需要使用log功能的模塊import 這個(gè)模塊
applogconfig.ini: 配置文件
logging_class:
import logging import sys import ConfigParser def log_building(log_file): try: #set format format_str=logging.Formatter("%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s") #create stander output handler crit_hand=logging.StreamHandler(sys.stderr) crit_hand.setFormatter(format_str) #create file handler file_hand=logging.FileHandler(log_file,'a') file_hand.setFormatter(format_str) app_log=logging.getLogger(__name__) app_log.addHandler(crit_hand) app_log.addHandler(file_hand) #必須設(shè)置,否則無(wú)法輸出 app_log.setLevel(logging.NOTSET) return app_log except Exception as e: logging.shutdown() raise e def config_file_get(fpath): try: cnf_dict={} cfg=ConfigParser.SafeConfigParser() cfg.read(fpath) for section in cfg.sections(): #將ini中的item組合到字典中,key=section+_option for item in cfg.items(section): key= section+'_'+item[0] value=item[1] if cnf_dict.get(key,None)==None: cnf_dict[key]=value return cnf_dict except Exception as e: raise e def log_level_get(level): DEBUG_LEVEL={'CRITICAL':logging.CRITICAL,'ERROR':logging.ERROR,'WARNING':logging.WARNING, 'INFO':logging.INFO,'DEBUG':logging.DEBUG } try: return DEBUG_LEVEL.get(level.upper()) except Exception as e: raise e
applogconfig.ini內(nèi)容:
[log] log_level=ERROR dir=log
以下為unittest內(nèi)容:
import unittest import logging_class import os import logging class Test(unittest.TestCase): cfg={} def setUp(self): print 'test begin' self.cfg={} def tearDown(self): print 'test end' def testlog_level_get(self): currentWorkingPath = r'E:\Myworkspace\python\logging_module\logging_module' ini_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'applogconfig.ini'))) self.cfg=logging_class.config_file_get(ini_file) self.assertEqual(self.cfg['log_log_level'].upper(), 'ERROR', 'OK') def testlog_level_set(self): currentWorkingPath = r'E:\Myworkspace\python\logging_module\logging_module' ini_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'applogconfig.ini'))) self.cfg=logging_class.config_file_get(ini_file) #print self.cfg['log_log_level'] self.assertEqual(logging_class.log_level_get(self.cfg['log_log_level']), logging.ERROR, 'OK') def testlog_building(self): currentWorkingPath = r'E:\Myworkspace\python\logging_module\logging_module' ini_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'applogconfig.ini'))) log_file=os.path.normpath(os.path.abspath(os.path.join(currentWorkingPath,'b.log'))) self.cfg=logging_class.config_file_get(ini_file) #print self.cfg['log_log_level'] level=logging_class.log_level_get(self.cfg['log_log_level']) log=logging_class.log_building(log_file) log.log(level, 'dddds') log.debug('msg') if __name__ == "__main__": #import sys;sys.argv = ['', 'Test.testName'] unittest.main()
輸出:
Finding files... done. Importing test modules ... done. test begin test end test begin test end test begin 2016-12-15 17:59:04,059 logging_module_test.py[line:48] ERROR dddds test end ---------------------------------------------------------------------- Ran 3 tests in 0.004s
補(bǔ)充知識(shí):一種logging封裝方法,不會(huì)產(chǎn)生重復(fù)log
在調(diào)試logging的封裝的時(shí)候,發(fā)現(xiàn)已經(jīng)調(diào)用了logging封裝的函數(shù),在被其它函數(shù)再調(diào)用時(shí),會(huì)出現(xiàn)重復(fù)的logging。原因是不同的地方創(chuàng)建了不同的handler,所以會(huì)重復(fù),可以使用暴力方法解決
暴力方式就是每次創(chuàng)建新的對(duì)象就清空l(shuí)ogger.handlers
我常用的封裝如下
import logging import time,os ''' 使用方法: import mylog log = mylog.Log().getlog() log.debug("###") ''' class Log(): def __init__(self,logger="mylog"): self.logger = logging.getLogger(logger) self.logger.setLevel(logging.DEBUG) self.log_time = "\\"+time.strftime("%Y-%m-%d_%H_%M", time.localtime())+".log" # 在進(jìn)程路徑創(chuàng)建log文件夾 # self.log_path = os.path.join(os.getcwd() + "\\log") # 固定在mylog上一級(jí)創(chuàng)建 self.log_path = os.path.join(os.path.dirname(os.path.dirname(__file__)) + "\\log") if os.path.exists(self.log_path) and os.path.isdir(self.log_path): pass else: os.makedirs(self.log_path) self.log_name = os.path.join(self.log_path + self.log_time) #因?yàn)槎喑稣{(diào)用logger會(huì)生成多個(gè)handlers,所以每次調(diào)用清空handler self.logger.handlers = [] fh = logging.FileHandler(self.log_name, 'a', encoding='utf-8') formatter = logging.Formatter('[%(levelname)s][%(asctime)s] [%(filename)s]->[%(funcName)s] line:%(lineno)d ---> %(message)s') fh.setLevel(logging.DEBUG) fh.setFormatter(formatter) self.logger.addHandler(fh) ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) ch.setFormatter(formatter) self.logger.addHandler(ch) fh.close() def getlog(self): return self.logger if __name__ == "__main__": log = Log().getlog() log.debug("hello")
以上這篇python將logging模塊封裝成單獨(dú)模塊并實(shí)現(xiàn)動(dòng)態(tài)切換Level方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- python 日志模塊logging的使用場(chǎng)景及示例
- Python的logging模塊基本用法
- python logging模塊的使用詳解
- python logging模塊的使用
- Python logging模塊handlers用法詳解
- Python logging模塊原理解析及應(yīng)用
- Python logging模塊進(jìn)行封裝實(shí)現(xiàn)原理解析
- Python logging日志模塊 配置文件方式
- Python logging模塊異步線程寫日志實(shí)現(xiàn)過(guò)程解析
- Python logging模塊寫入中文出現(xiàn)亂碼
- Python日志處理模塊logging用法解析
- python 日志 logging模塊詳細(xì)解析
- 多個(gè)python文件調(diào)用logging模塊報(bào)錯(cuò)誤
- Python基礎(chǔ)之logging模塊知識(shí)總結(jié)
相關(guān)文章
python腳本實(shí)現(xiàn)mp4中的音頻提取并保存在原目錄
這篇文章主要介紹了python腳本實(shí)現(xiàn)mp4中的音頻提取并保存在原目錄,本文給大家通過(guò)實(shí)例代碼介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-02-02python實(shí)現(xiàn)監(jiān)控windows服務(wù)并自動(dòng)啟動(dòng)服務(wù)示例
這篇文章主要介紹了python實(shí)現(xiàn)監(jiān)控windows服務(wù)并自動(dòng)啟動(dòng)服務(wù)示例,需要的朋友可以參考下2014-04-04python獲取酷狗音樂(lè)top500的下載地址 MP3格式
這篇文章主要介紹了python獲取酷狗音樂(lè)top500的下載地址 MP3格式,文中給大家提到了python--爬取酷狗TOP500的數(shù)據(jù),需要的朋友可以參考下2018-04-04利用Python腳本生成sitemap.xml的實(shí)現(xiàn)方法
最近項(xiàng)目中需要用腳本生成sitemap,中間學(xué)習(xí)了一下sitemap的格式和lxml庫(kù)的用法。把結(jié)果記錄一下,方便以后需要直接拿來(lái)用。下面這篇文章主要介紹了利用Python腳本生成sitemap.xml的實(shí)現(xiàn)方法,需要的朋友可以參考借鑒,一起來(lái)看看吧。2017-01-01python創(chuàng)建文件時(shí)去掉非法字符的方法
今天小編就為大家分享一篇python創(chuàng)建文件時(shí)去掉非法字符的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-10-10python+pytest自動(dòng)化測(cè)試函數(shù)測(cè)試類測(cè)試方法的封裝
這篇文章主要介紹了python+pytest自動(dòng)化測(cè)試函數(shù)測(cè)試類測(cè)試方法的封裝,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-06-06python游戲開發(fā)之視頻轉(zhuǎn)彩色字符動(dòng)畫
這篇文章主要為大家詳細(xì)介紹了python游戲開發(fā)之視頻轉(zhuǎn)彩色字符動(dòng)畫,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-04-04