1. 程式人生 > >python將logging模組封裝成單獨模組並實現動態切換Level

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