Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing an optional logger in code

Tags:

python

logging

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.

like image 590
iTayb Avatar asked Nov 23 '12 01:11

iTayb


People also ask

What is logger exception in Python?

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.


1 Answers

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")
like image 155
iTayb Avatar answered Oct 17 '22 15:10

iTayb