您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

懒惰的记录器消息字符串评估

懒惰的记录器消息字符串评估

日志记录模块已经对您要执行的操作提供了部分支持。做这个:

log.debug("Some message: a=%s b=%s", a, b)

…代替这个:

log.debug("Some message: a=%s b=%s" % (a, b))

日志记录模块足够聪明,不会产生完整的日志消息,除非该消息实际记录在某处。

要将此功能应用于您的特定请求,可以创建一个lazyjoin类。

class lazyjoin:
    def __init__(self, s, items):
        self.s = s
        self.items = items
    def __str__(self):
        return self.s.join(self.items)

像这样使用它(请注意使用生成器表达式,这会增加延迟):

logger.info('Stupid log message %s', lazyjoin(' ', (str(i) for i in range(20))))

这是展示此作品的演示。

>>> import logging
>>> logging.basicConfig(level=logging.INFO)
>>> logger = logging.getLogger("log")
>>> class DoNotStr:
...     def __str__(self):
...         raise AssertionError("the code should not have called this")
... 
>>> logger.info('Message %s', DoNotstr())
Traceback (most recent call last):
...
AssertionError: the code should not have called this
>>> logger.debug('Message %s', DoNotstr())
>>>

在演示中,logger.info()调用遇到了断言错误,而logger.debug()并没有解决

其他 2022/1/1 18:30:00 有465人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶