问题
I created a logger in the Python3 interactive prompt:
>>> import logging
>>> logger = logging.getLogger('foo')
>>> logger.setLevel(logging.INFO)
>>> logger.warn('bar')
bar
>>> logger.info('bar')
>>>
I'd expect logger.info
to output the bar
in this case, since I've explicitly set the logging level. But it's not the case here. Why?
回答1:
Actually, in your case neither should output anything since you haven't configured logging. You'll need to run logging.basicConfig()
or add a handler to your logger to expect any output:
In [1]: import logging
In [2]: logger = logging.getLogger('foo')
In [3]: logger.setLevel(logging.INFO)
In [4]: logger.warn('foo')
No handlers could be found for logger "foo"
In [5]: logger.info('foo')
In [6]: logging.basicConfig()
In [7]: logger.info('foo')
INFO:foo:foo
In [8]: logger.warn('foo')
WARNING:foo:foo
As mentioned by larsks in the comments, in Python 3 logging is configured by default with level WARNING
(which means you'll get output if you use warning()
or any higher level by default). In your case, you either can call logging.basicConfig()
to add a default handler to all loggers as in the example above, or add a handler to your logger:
logger.addHandler(logging.StreamHandler())
来源:https://stackoverflow.com/questions/39068465/python-logger-doesnt-adhere-to-the-set-level