国产成人精品久久免费动漫-国产成人精品天堂-国产成人精品区在线观看-国产成人精品日本-a级毛片无码免费真人-a级毛片毛片免费观看久潮喷

您的位置:首頁(yè)技術(shù)文章
文章詳情頁(yè)

python將logging模塊封裝成單獨(dú)模塊并實(shí)現(xiàn)動(dòng)態(tài)切換Level方式

瀏覽:63日期:2022-07-25 17:06:01

查找了很多資料,但網(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)。

標(biāo)簽: Python 編程
相關(guān)文章:
主站蜘蛛池模板: 亚洲美女色成人综合 | 日本特级淫片免费看 | 日韩精品不卡 | 国产成人精品视频一区 | 日本www在线播放 | 亚洲视频在线精品 | 精品在线免费观看 | 欧美日韩一区二区综合在线视频 | 午夜精品一区二区三区在线观看 | 免费人成在线观看视频不卡 | 一级毛片在线播放 | 成年人免费在线视频观看 | 久久久久久久久久久久久久久久久久 | 国产玖玖在线 | 韩日三级视频 | 久久橹| 国产精品成人免费视频不卡 | 亚洲精品国产成人一区二区 | 亚洲成人一区在线 | 中文字幕一区二区三区精品 | 国产最爽的乱淫视频国语对 | 精品久久久久久亚洲 | 成人欧美一区二区三区黑人免费 | 久久久综合结合狠狠狠97色 | 中文字幕s级优女区 | 亚洲欧美专区精品久久 | 手机看片欧美 | 亚洲一区二区三区精品影院 | 99精品一区二区三区 | 国产午夜精品久久理论片 | 成人午夜影院在线观看 | 免费在线观看黄色毛片 | 国产精品三级在线观看 | 国内成人精品亚洲日本语音 | 婷婷色综合久久五月亚洲 | 色熟 | 狼伊千合综网中文 | 日本免费高清视频二区 | 亚洲加勒比 | 亚洲男人a天堂在线2184 | 涩涩网站|