我正在使用 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
这可能与日志库有关吗?
最佳答案
我认为没有任何内置方法可以检索已初始化记录器的配置并将其存储到变量中。我不确定这是否适用于您的项目,但您是否考虑过创建一个临时记录器对象以在函数范围内使用?
import logging
from sys import stdout
def switch_logger_for_this_code(msg) -> None:
# Create logging.Formatter for output customization
formatter = logging.Formatter(
fmt="[%(asctime)s.%(msecs)d] %(message)s",
datefmt="%Y/%m/%d %H:%M:%S"
)
handler = logging.StreamHandler(stdout) # Create output handler
handler.setLevel(logging.ERROR) # Specify logging level
handler.setFormatter(formatter) # Apply desired format
temp_log = logging.getLogger("temp") # Get new or existing Logger
temp_log.addHandler(handler) # Add output handler
temp_log.error(msg) # Log the message
switch_logger_for_this_code("hello world") # Log 'hello world'
# Which would output the following
# [2020/10/20 15:09:18.548] hello world
这种方法背后的主要思想是原始记录器对象不会被修改,但您仍然可以使用临时记录器以您想要的格式记录您最初打算的内容。
关于python - 如何获取当前的 python 日志记录配置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64452594/