Implementing an optional logger in code

logging, python

Solution

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 *args, **kwargs: None

logger = logger or DummyObject()

Nesting every debug statement in a block:

if logger:
    logger.debug("abc")

Problem

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.

Original source

Related problems