Optional use of logging library module

Eric DeWall edewall at qualcomm.com
Tue Jun 22 21:40:01 CEST 2004

In trying to clean up the inevitable debug printing littered through some
code, I started reading up on the 'logging' module.  Browsing groups
indicates that the design of the module is controversial but personally I'm
very happy to see such a full-featured logger as part of the standard
distribution.  Here's my problem though (using 2.3.3) - I'm trying to write
some reusable classes that _optionally_ use the logging module.  So a class
might look like:

class SomeClass:
    def __init__( self, logger=None):
        self.logger = logger

User of the class passes in a Logger object they have already set up with
handlers, etc., class simply calls log methods on the logger when
appropriate.  But I can't find a way to create a good "null" logging object
that the class can use by default if no Logger is passed in.  I'd like a
simple approach that doesn't involve extending the existing logging library.

Options I've considered:

1) if self.logger: self.logger.log( 'some message' )    [throughout class
Constantly check if the logger exists - what a pain.

2) [in __init__:]  if not logger: self.logger = logging.getLogger("null")
This would be great if a "null" logger was directly supported by the library
and set to do nothing.  But it's not, so handlers would need to be
installed, and there's no guarantee for "null" to be unique anyway

3) class NullLogger:
        def debug(self, msg, *args, **kwargs): pass
        def info(self, msg, *args, **kwargs): pass
        def warning(self, msg, *args, **kwargs): pass
        def error(self, msg, *args, **kwargs): pass
        def exception(self, msg, *args): pass
        def critical(self, msg, *args, **kwargs): pass
        warn = warning
        fatal = critical
Works well, but again I'd rather not extend the original library and this to
be imported all over.

I've also looked at ways of creating a separate logging.Manager, but it is
very coupled to logging.Logger for reasons I can't quite understand from
glancing the code.

Any help is kindly appreciated!

More information about the Python-list mailing list