简体   繁体   中英

Python library default NullHandler causing error when unit testing

I'm trying to setup a default logger for an api library I'm writing. The Python documentation states to setup a NullHandler in the library and then let the developers who use the library determine how the logging should be handled.

Note It is strongly advised that you do not add any handlers other than NullHandler to your library's loggers. This is because the configuration of handlers is the prerogative of the application developer who uses your library. The application developer knows their target audience and what handlers are most appropriate for their application: if you add handlers 'under the hood', you might well interfere with their ability to carry out unit tests and deliver logs which suit their requirements.

https://docs.python.org/3/howto/logging.html#logging-advanced-tutorial

import logging
logging.getLogger('foo').addHandler(logging.NullHandler())

So, for a module such as myapi.py, I might have:

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

class MyApi: ...

And then in a unit test file, I would set the actual log handler.

import logging
log = logging.getLogger('myapi')
log.handlers = []
log.addHandler(logging.StreamHandler(sys.stdout))
log.setLevel(logging.DEBUG)

class MyApiTests(unittest.TestCase): ...

The problem I'm having is that the NullHandler causes an error message to come up when running the unit tests.

  File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1590, in callHandlers
  if record.levelno >= hdlr.level:
  AttributeError: type object 'NullHandler' has no attribute 'level'

I've tried several things to remove the error. First, I've tried to remove the existing handler; log.handlers = []. That didn't seem to make any change. I also tried to set a log level; log.setLevel(logging.DEBUG). I still get the error.

I must be missing something. Can anyone explain how to remove the NullHandler or prevent the error message?

It's because you're adding the class instead of an instance to handlers list.

log.addHandler(logging.NullHandler)

should be

log.addHandler(logging.NullHandler())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM