iTayb iTayb - 9 months ago 43
Python Question

Implementing an optional logger in code

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.

Answer Source

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():
    def __init__(self):
    def __getattr__(self, name):
        return (lambda *x: None)

logger = logger or DummyObject()

Nesting every debug statement in a block:

if logger: