日志记录模块已经对您要执行的操作提供了部分支持。做这个:
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 pre should not have called this")... >>> logger.info('Message %s', DonotStr())Traceback (most recent call last):...AssertionError: the pre should not have called this>>> logger.debug('Message %s', DonotStr())>>>在演示中,logger.info()调用遇到了断言错误,而logger.debug()并没有解决。



