最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2020年05月12日 14:12:20   作者:long111  
這篇文章主要介紹了python將logging模塊封裝成單獨(dú)模塊并實(shí)現(xiàn)動(dòng)態(tài)切換Level方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

查找了很多資料,但網(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è)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python實(shí)現(xiàn)去除列表中重復(fù)元素的方法總結(jié)【7種方法】

    Python實(shí)現(xiàn)去除列表中重復(fù)元素的方法總結(jié)【7種方法】

    今天小編就為大家分享一篇關(guān)于Python實(shí)現(xiàn)去除列表中重復(fù)元素的方法總結(jié)【7種方法】,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • 將Django使用的數(shù)據(jù)庫(kù)從MySQL遷移到PostgreSQL的教程

    將Django使用的數(shù)據(jù)庫(kù)從MySQL遷移到PostgreSQL的教程

    這篇文章主要介紹了將Django使用的數(shù)據(jù)庫(kù)從MySQL遷移到PostgreSQL的教程,同時(shí)提到了一些注意事項(xiàng),需要的朋友可以參考下
    2015-04-04
  • Python實(shí)現(xiàn)字符串中某個(gè)字母的替代功能

    Python實(shí)現(xiàn)字符串中某個(gè)字母的替代功能

    小編想實(shí)現(xiàn)這樣一個(gè)功能:將輸入字符串中的字母 “i” 變成字母 “p”。想著很簡(jiǎn)單,怎么實(shí)現(xiàn)呢?下面小編給大家?guī)?lái)了Python實(shí)現(xiàn)字符串中某個(gè)字母的替代功能,感興趣的朋友一起看看吧
    2019-10-10
  • 跟老齊學(xué)Python之復(fù)習(xí)if語(yǔ)句

    跟老齊學(xué)Python之復(fù)習(xí)if語(yǔ)句

    是否記得,在上一部分,有一講專門介紹if語(yǔ)句的:從if開(kāi)始語(yǔ)句的征程。在學(xué)習(xí)if語(yǔ)句的時(shí)候,對(duì)python編程的基礎(chǔ)知識(shí)了解的還不是很多,或許沒(méi)有做什么太復(fù)雜的東西。本講要對(duì)它進(jìn)行一番復(fù)習(xí),通過(guò)復(fù)習(xí)提高一下。如果此前有的東西忘記了,建議首先回頭看看前面那講。
    2014-10-10
  • Python中的測(cè)試模塊unittest和doctest的使用教程

    Python中的測(cè)試模塊unittest和doctest的使用教程

    這篇文章主要介紹了Python中的測(cè)試模塊unittest和doctest的使用教程,本文來(lái)自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • 最新評(píng)論

    得荣县| 镇坪县| 逊克县| 防城港市| 巧家县| 菏泽市| 南汇区| 太湖县| 太湖县| 加查县| 汝州市| 黄龙县| 镇雄县| 乌审旗| 延津县| 陇川县| 昌江| 连平县| 屏边| 闽清县| 嘉峪关市| 沂源县| 梧州市| 沧源| 淄博市| 巴林左旗| 罗定市| 怀来县| 普兰店市| 临沭县| 长垣县| 太白县| 遵化市| 淮北市| 贺兰县| 丹寨县| 大悟县| 凌海市| 县级市| 休宁县| 宜州市|