How to use logging NullHandler in python 2.6

2020-04-13 08:05发布

问题:

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.

回答1:

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


回答2:

Here is my recommended solution:

#!/usr/bin/env python2.6

import os
import logging
modlog = logging.getLogger(__name__)
modlog.addHandler(logging.FileHandler(os.devnull))

# ... remaining code