懒惰的记录器消息字符串评估 [英] Lazy logger message string evaluation

查看:80
本文介绍了懒惰的记录器消息字符串评估的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在python应用程序中使用标准的python日志记录模块:

I'm using standard python logging module in my python application:


import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("log")
while True:
  logger.debug('Stupid log message " + ' '.join([str(i) for i in range(20)]) )
  # Do something

问题在于,尽管未启用调试级别,但在每次循环迭代时都会评估该愚蠢的日志消息,从而严重损害性能.

The issue is that although debug level is not enable, that stupid log message is evaluated on each loop iteration, which harms performance badly.

有什么解决方案吗?

在C ++中,我们有log4cxx软件包,它提供了这样的宏:
LOG4CXX_DEBUG(logger, messasage)
有效评估为

In C++ we have log4cxx package that provides macros like this:
LOG4CXX_DEBUG(logger, messasage)
That effectively evaluates to


if (log4cxx::debugEnabled(logger)) {
    log4cxx.log(logger,log4cxx::LOG4CXX_DEBUG, message)
}

但是,由于Python(AFAIK)中没有宏,是否有一种有效的日志记录方法?

But since there are no macros in Python (AFAIK), if there a efficient way to do logging?

推荐答案

日志记录模块已经部分支持您要执行的操作.这样做:

The logging module already has partial support for what you want to do. Do this:

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

...代替这个:

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

日志记录模块足够聪明,除非实际将消息记录到某处,否则不会生成完整的日志消息.

The logging module is smart enough to not produce the complete log message unless the message actually gets logged somewhere.

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

To apply this feature to your specific request, you could create a lazyjoin class.

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

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

Use it like this (note the use of a generator expression, adding to the laziness):

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

这是一个演示此工作的演示.

Here is a demo that shows this works.

>>> 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()并没有解决这个问题.

In the demo, The logger.info() call hit the assertion error, while logger.debug() did not get that far.

这篇关于懒惰的记录器消息字符串评估的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆