如何防止库修改根记录器?

时间:2016-01-14 10:29:00

标签: python logging

有些像oslo_log modify the root logger这样的库,完全消除了我自己的日志配置。

为了防止这种情况,我在这里修改了标准的日志记录库:

def hackyCustomGetLogger(name=None, true_behavior=False):
    """
    a replacement for the logging.getLogger function that returns a fake
    root logger if called with name=None and true_behavior=False.

    this is to prevent third party libraries from altering the root logger
    configuration.
    """
    if name:
        return logging.Logger.manager.getLogger(name)
    else:
        if true_behavior:
            return logging.root
        # if no name is specified, and `true_behavior` is not forced to True,
        # we return a fake logger
        warning = ('you called an altered version of logging.getLogger, '
                   'that returns a fake root logger. see {} ({})')
        logging.root.warning(warning.format(__name__, __file__))
        return logging.RootLogger(logging.WARNING)

logging.getLogger = hackyCustomGetLogger

它有效,但是......猴子修补python标准库听起来像是一个非常坏主意。有没有更好的方法来实现这一目标?

1 个答案:

答案 0 :(得分:1)

库不应该尝试修改日志记录设置。我自己认为这是一个错误。

我注意到,如果没有配置root_logger,您引用的示例仅进行设置:

# Sometimes logging occurs before logging is ready (e.g., oslo_config).
# To avoid "No handlers could be found," temporarily log to sys.stderr.
root_logger = logging.getLogger(None)
if not root_logger.handlers:
    root_logger.addHandler(logging.StreamHandler())

所以也许更好的解决方法是确保已经定义了记录器?