Python 禁用日志记录减慢脚本

标签 python python-3.x performance logging optimization

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

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

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

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

最佳答案

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

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

另一种可能的方法是使用 %-formatting,它只在实际需要时才进行格式化(记录事件必须由处理程序和记录器处理才能达到这一点)。我知道 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)

关于Python 禁用日志记录减慢脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70717205/

相关文章:

javascript canvas html5性能问题

python - 如何设置 OpenCV 将原点用作图像的左下角?

Python:如何在 __repr__ 方法中获取对象的地址?

python - 我如何告诉我的 ModelAdmin 的过滤器在默认情况下不显示所有记录?

python - 如何使函数 "make_archive"包含python中的父目录

python - 如何正确编写模块?

python - 在 Python 中字节对象相对于字符串对象有哪些优势?

python-3.x - 无法使用pip在Windows上安装h5py

c# - 测试 C# 与 Java 性能(执行)时要关注哪些方面?

Python-在数组中创建唯一值的掩码