Python 禁用日志记录减慢脚本

Python disabled logging slowing script

我正在为我的脚本使用内置的 Python“日志记录”模块。当我将冗长改为“信息”时,我的“调试”消息似乎显着减慢了我的脚本速度。

我的一些“调试”消息会打印大字典,我猜 Python 在意识到“调试”消息被禁用之前正在扩展文本。示例:

import pprint
pp = pprint.PrettyPrinter(indent=4)
logger.debug(f"Large Dict Object: {pp.pformat(obj)}")

我怎样才能提高我的表现?我更愿意仍然使用 Python 的内置日志模块。但是需要想出一个“干净”的方法来解决这个问题。

检查当前等级是否足够好:

if logger.getEffectiveLevel() <= logging.DEBUG:
    logger.debug(f"Large Dict Object: {pp.pformact(obj)}")
    

这不是特别干净,但是我能想到的最好的。如果性能瓶颈

,你只需要包含这个

dankal444 提到的功能已经有 a feature 个日志记录,稍微整洁一些:

if logger.isEnabledFor(logging.DEBUG):
    logger.debug(f"Large Dict Object: {pp.pformat(obj)}")

另一种可能的方法是使用 %-格式化,它只在实际需要时进行格式化(记录事件必须由处理程序和记录器处理才能达到这一点)。我知道 f-strings 是新的(ish)热度并且性能很好,但这完全取决于具体情况,以提供最好的结果。

利用惰性 % 格式化的示例:

class DeferredFormatHelper:
    def __init__(self, func, *args, *kwargs):
        self.func = func  # assumed to return a string
        self.args = args
        self.kwargs = kwargs

    def __str__(self):
        # This is called because the format string contains
        # a %s for this logging argument, lazily if and when
        # the formatting needs to happen
        return self.func(*self.args, **self.kwargs)

if logger.isEnabledFor(logging.DEBUG):
    arg = DeferredFormatHelper(pp.pformat, obj)
    logger.debug('Large Dict Object: %s', arg)

我无法验证你的瓶颈在哪里,但如果是因为 pprint 库,你的记录器将永远没有机会对此做任何事情。重写以澄清。

from pprint import PrettyPrinter
import logging

logger = logging.getLogger()

large_object = {"very": "large container"}
pp = PrettyPrinter(indent=4)

# This is done first.
formatted_msg = pp.pformat(large_object)
# It's already formatted when it's sent to your logger.
logger.debug(f"Large dict object: {formatted_msg}")