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

标签 python python-logging

我正在使用 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/

相关文章:

python - 对 Pandas 中 Python Lambda 函数的澄清/思考

python - 如何在调试日志中查看 Python 请求使用哪个 IP 地址进行连接?

python - 登录 Python 脚本不起作用 : results in empty log files

python - 使用 langchain 和 websockets 完成流式聊天

python - 使用 LineCollection 绘制 shapefile 显示所有边缘,但部分填充它们

python - 使用 Pandas 进行棘手的聚合

python - 如何逐步在 Python Selenium 中向下滚动

python - basicConfig只能在根记录器上使用,而处理程序/格式化程序只能在命名记录器上使用吗?

python - 日志文件中的 matplotlib.font_manager 调试消息