Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use logging NullHandler in python 2.6

Most of my code at this point has been designed to run on python 2.76. So the library I wrote uses the following code so that any consumers of my libraries can have debug logging coming from the library:

So in each library file I have this:

log = logging.getLogger(__name__)
log.addHandler(logging.NullHandler())

This way if a client script using my library instantiates a logger object, the library will have log output as well.

However, I now need to tweak this library so it runs on python 2.6 and it's complaining about this bit of code:

Traceback (most recent call last):
  File "./LCMTool.py", line 36, in <module>
    from lcm_zfssa  import *
  File "/devel/v2/lcm_zfssa.py", line 20, in <module>
    log.addHandler(logging.NullHandler())
  AttributeError: 'module' object has no attribute 'NullHandler'

Is there a way to tweak this so that this will work with python 2.6?

Thx for any help.

like image 630
BenH Avatar asked Apr 23 '26 08:04

BenH


1 Answers

Depending on how distributed your issue is, the solution from the Python Guide (and ultimately from requests source) might work: try importing NullHandler and in the except ImportError clause, define the class like so:

# Set default logging handler to avoid "No handler found" warnings.
import logging
try:  # Python 2.7+
    from logging import NullHandler
except ImportError:
    class NullHandler(logging.Handler):
        def emit(self, record):
            pass

logging.getLogger(__name__).addHandler(NullHandler())

Though if using the logging namespace, you'll then want to insert the class:

# in the except clause, after the class def:
logging.NullHandler = NullHandler
like image 55
Ryan de Kleer Avatar answered Apr 24 '26 23:04

Ryan de Kleer