Lazy logger message string evaluation

前端 未结 6 727
囚心锁ツ
囚心锁ツ 2020-12-02 11:12

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

import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(\"log\")
whi         


        
6条回答
  •  误落风尘
    2020-12-02 11:35

    As Shane points out, using

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

    ... instead of this:

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

    saves some time by only performing the string formatting if the message is actually logged.

    This does not completely solve the problem, though, as you may have to pre-process the values to format into the string, such as:

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

    In that case, obj.get_a() and obj.get_b() will be computed even if no logging happens.

    A solution to that would be to use lambda functions, but this requires some extra machinery:

    class lazy_log_debug(object):
        def __init__(self, func):
            self.func = func
            logging.debug("%s", self)
        def __str__(self):
            return self.func()
    

    ... then you can log with the following:

    lazy_log_debug(lambda: "Some message: a=%s b=%s" % (foo.get_a(), foo.get_b()))
    

    In that case, the lambda function will only be called if log.debug decides to perform the formatting, hence calling the __str__ method.

    Mind you: the overhead of that solution may very well exceed the benefit :-) But at least in theory, it makes it possible to do perfectly lazy logging.

提交回复
热议问题