繁体   English   中英

Python,如何避免对当前级别以下的日志语句进行参数评估

[英]Python, how to avoid argument evaluation for logging statements below current level

假设我有这样的声明

logging.debug('%r', do_really_expensive_computation())
or
logging.debug('%r', find_my_object().do_really_expensive_computation())

当日志记录级别设置高于DEBUG将无法登录,但它仍然会调用之前评估的参数logging.debug()和执行do_really_expensive_computation()find_my_object()可能会相当沉重。

当低于当前水平时,是否有任何好的模式可以跳过记录中涉及的所有计算?

一种方法是使用__repr__方法创建一个辅助类,该方法返回给定回调函数的值,并将用昂贵的函数对象初始化的辅助类实例传递给记录器以进行延迟评估:

class r:
    def __init__(self, callback):
        self.callback = callback

    def __repr__(self):
        return repr(self.callback())

以便:

import logging

def expensive():
    print('this is expensive')
    return 1

print('debug:')
logging.debug('%r', r(expensive))
print('error:')
logging.error('%r', r(expensive))

输出:

debug:
error:
this is expensive
ERROR:root:1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM