临时更改日志记录级别 - 安全

问题描述 投票:0回答:1

根据动态更改日志级别而不重新启动应用程序我可以临时更改日志记录级别:

logger_level = my_logger.level
my_logger.setLevel(logging.DEBUG)
a = do_something_with_higher_logging1()
b,c = do_something_with_higher_logging2()
d = do_something_with_higher_logging3()
my_logger.setLevel(logger_level)

问题是,如果

do_something_with_higher_logging[123]
引发异常(在该异常之外捕获,因此我的程序不会终止),
my_logger
的级别不会重置回来并保持在
DEBUG

我可以做

def call_with_loglevel(logger, level, f, **kwargs):
    "Call f with logger at a different level"
    saved_logger_level = logger.level
    logger.setLevel(level)
    try:
        return f(**kwargs)
    finally:
        logger.setLevel(saved_logger_level)

但这需要我从

f
中定义
do_something_with_higher_logging[123]
...

我想要的是类似的东西

with my_logger.setLevel(logging.DEBUG):
    a = do_something_with_higher_logging1()
    b,c = do_something_with_higher_logging2()
    d = do_something_with_higher_logging3()
python logging error-handling python-logging
1个回答
1
投票

使

Logger.setLevel
返回上下文管理器似乎是一个向后兼容的更改(我应该创建一个RFE吗?)但现在看起来我可以做

from contextlib import contextmanager

@contextmanager
def log_level(logger, level):
    "Run body with logger at a different level"
    saved_logger_level = logger.level
    logger.setLevel(level)
    try:
        yield saved_logger_level
    finally:
        logger.setLevel(saved_logger_level)
© www.soinside.com 2019 - 2024. All rights reserved.