查找了很多资料,但网上给出的教程都是大同小异的,而我想将代码进一步精简,解耦,想实现如下两个目标
1. 将logging模块的初始化,配置,设置等代码封装到一个模块中;
2. 能根据配置切换logging.level, 网上给出的教程都是写死的,如果我在线上之前使用了logging.info(msg),现在想切换为logging.debug(msg)怎么办?需要能够根据配置文件中的 设置配置logging.level
两个文件:
logging_class:将logging模块的初始化,配置,设置等代码封装到一此模块中,读取配置文件中对于log等级的设置项;需要使用log功能的模块import 这个模块
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)
#必须设置,否则无法输出
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内容:
[log] log_level=ERROR dir=log
以下为unittest内容:
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
补充知识:一种logging封装方法,不会产生重复log
在调试logging的封装的时候,发现已经调用了logging封装的函数,在被其它函数再调用时,会出现重复的logging。原因是不同的地方创建了不同的handler,所以会重复,可以使用暴力方法解决
暴力方式就是每次创建新的对象就清空logger.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"
# 在进程路径创建log文件夹
# self.log_path = os.path.join(os.getcwd() + "\\log")
# 固定在mylog上一级创建
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)
#因为多出调用logger会生成多个handlers,所以每次调用清空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模块封装成单独模块并实现动态切换Level方式就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]