Look at this part of the documentation.
Update: Logging already supports lazy evaluation, but slightly differently to the way described in your comnment. For example, see the following script:
import logging
def expensive_func(*args):
print('Expensive func called: %s' % (args,))
return sum(args)
class DeferredMessage(object):
def __init__(self, func, *args):
self.func = func
self.args = args
def __str__(self):
return 'Message {0}'.format(self.func(*self.args))
if __name__ == '__main__':
logging.basicConfig()
logging.info(DeferredMessage(expensive_func, 1, 2))
logging.warning(DeferredMessage(expensive_func, 3, 4))
logging.error(DeferredMessage(expensive_func, 5, 6))
When the above script is run, it should print
Expensive func called: (3, 4)
WARNING:root:Message 7
Expensive func called: (5, 6)
ERROR:root:Message 11
which shows that a potentially expensive function is only called when necessary. The example above can, of course, be generalised to allow the format string to be passed to the DeferredMessage
, and to use kwargs
, and so on.