日志记录模块已经对您要执行的操作提供了部分支持。做这个:
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())
>>>