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)上給出的教程都是寫(xiě)死的,如果我在線上之前使用了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 loggingimport sysimport 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 edef 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=ERRORdir=log
以下為unittest內(nèi)容:
import unittestimport logging_classimport osimport 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:Myworkspacepythonlogging_modulelogging_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:Myworkspacepythonlogging_modulelogging_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:Myworkspacepythonlogging_modulelogging_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 begintest endtest begintest endtest begin2016-12-15 17:59:04,059 logging_module_test.py[line:48] ERROR ddddstest 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 loggingimport 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.loggerif __name__ == '__main__': log = Log().getlog() log.debug('hello')
以上這篇python將logging模塊封裝成單獨(dú)模塊并實(shí)現(xiàn)動(dòng)態(tài)切換Level方式就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. HTML <!DOCTYPE> 標(biāo)簽2. 5個(gè)HTML5的常用本地存儲(chǔ)方式詳解與介紹3. asp在iis7報(bào)錯(cuò)行號(hào)不準(zhǔn)問(wèn)題的解決方法4. asp批量添加修改刪除操作示例代碼5. 告別AJAX實(shí)現(xiàn)無(wú)刷新提交表單6. msxml3.dll 錯(cuò)誤 800c0019 系統(tǒng)錯(cuò)誤:-2146697191解決方法7. HTML中的XML數(shù)據(jù)島記錄編輯與添加8. CSS代碼檢查工具stylelint的使用方法詳解9. 三個(gè)不常見(jiàn)的 HTML5 實(shí)用新特性簡(jiǎn)介10. 原生js XMLhttprequest請(qǐng)求onreadystatechange執(zhí)行兩次的解決
