Reputation: 2994
I come from SLF4J and Log4J, so that might be the reason why I don't get how logging works in Python.
I have the following
---- logging.yaml
version: 1
handlers:
console:
class: logging.StreamHandler
level: DEBUG
stream: ext://sys.stderr
formatter: simpleFormatter
file:
class: logging.FileHandler
filename: app.log
mode: w
level: DEBUG
formatter: simpleFormatter
formatters:
simpleFormatter:
#class: !!python/name:logging.Formatter
#class: logging.Formatter
format: '%(name)s %(asctime)s %(levelname)s %(message)s'
datefmt: '%d/%m/%Y %H:%M:%S'
root:
level: INFO
handlers: [console, file]
mod:
level: DEBUG
----- mod.py
import logging
def foo ():
log = logging.getLogger ( __name__ )
log.debug ( 'Hello from the module' )
---- main.py
from logging.config import dictConfig
import yaml
with open ( 'logging.yaml' ) as flog:
dictConfig ( yaml.load ( flog ) )
import logging
from mod import foo
if __name__ == '__main__':
log = logging.getLogger ( __name__ )
log.debug ( 'Hello from main' )
foo ()
With the config above, I would expect to see only the message 'Hello from the module'
. Instead, nothing is printed. When I set DEBUG
for the root logger, both messages are printed.
So, aren't the messages forwarded to the upper loggers? Isn't the mod
logger a child of root
? Doesn't the mod
logger inherit the handlers
configuration? (I've tried to repeat handlers
in mod
, but nothing changes).
How can I achieve a configuration saying: default level is INFO
, the level for this module and sub-modules is DEBUG
, everything goes to the handlers defined for root
?
Upvotes: 4
Views: 6685
Reputation: 121976
You have a fairly simple error: note that, per the docs, configuration for loggers other than root
should be under the loggers
key as:
a dict in which each key is a logger name and each value is a dict describing how to configure the corresponding Logger instance
Adding this key and indenting the appropriate lines, to give:
loggers:
mod:
level: DEBUG
works as expected:
$ python main.py
mod 20/07/2016 14:35:32 DEBUG Hello from the module
$ cat app.log
mod 20/07/2016 14:35:32 DEBUG Hello from the module
Upvotes: 3