如何获取当前的python日志配置?

问题描述

我正在使用python logging库为输入法配置记录器,如下所示:

logging.config.dictConfig(config)

我有一个特殊的功能,应该使用新功能,然后在功能结束时切换回原始记录器。原始记录器可能会有所不同,因此我不想对其进行硬编码。一些伪代码来描述我想要的东西:

def switch_logger_for_this_code():
    old_logging_config = logger.get_current_logging_config(). # This is what I want to accomplish

    logging.config.dictConfig(new_logging_config)
    logging.info('This log goes to the new config!')
    logging.config.dictConfig(old_logging_config)
    logging.info('This log goes to the old config!')
    return

这与日志记录库有关吗?

解决方法

我不相信有任何内置的方式来检索已初始化记录器的配置并将其存储到变量中。我不确定这是否适用于您的项目,但是您是否考虑过仅创建一个临时记录器对象以在函数范围内使用?

vowel = ('A','E','I','O','U','a','e','i','o','u')
sentence = 'Write a script that encodes phrases'
def pig_latin(sentence):
    aggregator = ''
    for words in sentence.split():
        if words[0] in vowel:
            words = words + 'ay'
        else: 
            words = words[1:]+ words[0] + 'ay'
        aggregator = aggregator + ' ' + words
   return aggregator
    
pig_latin(sentence)

此方法背后的主要思想是不会修改原始记录器对象,但是您仍然可以使用临时记录器以所需的格式记录您最初想要的内容。

,

我只是浏览了logging模块的源代码,但看不到任何获取内部配置的方法,内部配置从传入的配置开始,但是可以被其他调用修改到日志系统。