python将logging模块封装成单独模块并实现动态切换Level

查找了很多资料,但网上给出的教程都是大同小异的,而我想将代码进一步精简,解耦,想实现如下两个目标

1. 将logging模块的初始化,配置,设置等代码封装到一个模块中;

2. 能根据配置切换logging.level, 网上给出的教程都是写死的,如果我在线上之前使用了logging.info(msg),现在想切换为logging.debug(msg)怎么办?需要能够根据配置文件中的 设置配置logging.level

demo如下:

两个文件:

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


OK





Pythonlogging模块提供了灵活的日志记录功能,可以将日志输出到文件、控制台、网络等各种目标。下面是一个简单的logging封装示例,您可以根据自己的需求进行修改和扩展。 ```python import logging class Logger: def __init__(self, name=__name__, level=logging.DEBUG): self.logger = logging.getLogger(name) self.logger.setLevel(level) formatter = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s') console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) self.logger.addHandler(console_handler) file_handler = logging.FileHandler('app.log') file_handler.setFormatter(formatter) self.logger.addHandler(file_handler) def debug(self, message): self.logger.debug(message) def info(self, message): self.logger.info(message) def warning(self, message): self.logger.warning(message) def error(self, message): self.logger.error(message) def critical(self, message): self.logger.critical(message) ``` 在上述代码中,我们定义了一个Logger类,它包含了一个logger对象和几个日志级别的方法。在初始化时,我们设置了日志级别、日志格式和两个Handler(控制台和文件)。日志级别可以根据需要进行调整,常见的级别包括DEBUG、INFO、WARNING、ERROR和CRITICAL。日志格式可以根据自己的需要进行修改,上面的格式包含了时间、级别、日志名称和消息内容。 使用该Logger类时,可以先创建一个实例对象,然后调用对应的方法记录日志,例如: ```python logger = Logger(__name__) logger.debug('This is a debug message') logger.info('This is an info message') logger.warning('This is a warning message') logger.error('This is an error message') logger.critical('This is a critical message') ``` 该示例中,我们创建了一个名为loggerLogger对象,并记录了五个不同级别的日志。控制台和文件中将分别输出这些日志信息。 当然,上述示例只是一个简单的封装,您可以根据自己的需求进行扩展,例如添加网络输出、邮件通知等功能。同时,您还可以使用Pythonlogging模块提供的其他功能,例如过滤器、处理器、格式化器等,以满足更复杂的日志需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值