I'd like to implement an optional logger in a function. Something like:
def foo(arg1, arg2, arg3, logger=None):
logger = logger or (lambda *x: None)
...
self.logger.debug("The connection is lost.")
I want the logging to happen in case a logger exists. Otherwise, the logger's debugging won't do a thing.
Basically the easy way to achieve it is to nest every debug statement in an if logger
block, but it seems messy when there are many debug statements.
Logging an exception in python with an error can be done in the logging. exception() method. This function logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message.
Few options:
Create a dummy logger (my favorite):
logger = logger or logging.getLogger('dummy') # without configuring dummy before.
Create a dummy object with one level null
effect:
class DummyObject(object):
def __getattr__(self, name):
return lambda *x: None
logger = logger or DummyObject()
Nesting every debug statement in a block:
if logger:
logger.debug("abc")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With