I have some python like this:
def foo():
logger = logging.getLogger()
# do something here
logger.debug(\'blah blah {}\'.format(expensive_func()))
As Vinay Sajip suggests, you can do the following:
def foo():
logger = logging.getLogger()
if logger.isEnabledFor(logging.DEBUG):
logger.debug('blah blah {}'.format(expensive_func()))
logger.debug('Message: {}'.format(expf_1(expf_2(some_arg))))
logger.debug('Message: {}', Lazy(expf_1, Lazy(expf_2, some_arg)))
foo()
Which is already lazy!
That's because the then-expressions
logger.debug('blah blah {}'.format(expensive_func()))
logger.debug('Message: {}'.format(expf_1(expf_2(some_arg))))
logger.debug('Message: {}', Lazy(expf_1, Lazy(expf_2, some_arg)))
are only evaluated if and only if logger.isEnabledFor(logging.DEBUG) returns True, i.e. if and only if their evaluation is needed.
Even more
logging.info(DeferredMessage(expensive_func, 1, 2))
is not as lazy as one may think: DeferredMessage(expensive_func, 1, 2) have to be evaluated in an eager fashion. Which is in addition slower than evaluating:
if logger.isEnabledFor(logging.DEBUG):