I just discovered a different behavior of Python logging, depending on if I use logging with fileconfig and logging with programmatic config.
To demonstrate, I created two minimal examples.
In the first example I'm configuring logging programmatically. This example works as expected - the debug log message is printed to the console.
# foo.py
import logging
logger = logging.getLogger(__name__)
class Foo(object):
def __init__(self):
logger.debug('debug log from Foo')
##########################################################################
# loggingtest.py
import logging.config
from foo import Foo
if __name__ == '__main__':
consoleLogger = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)-6s: %(name)s - %(levelname)s - %(message)s')
consoleLogger = logging.StreamHandler()
consoleLogger.setLevel(logging.DEBUG)
consoleLogger.setFormatter(formatter)
rootLogger = logging.getLogger()
rootLogger.addHandler(consoleLogger)
rootLogger.setLevel(logging.NOTSET)
# prints debug log message to console
foo = Foo()
In my second example, I'm configuring logging with fileConfig. As far as I can see, the log-config-file should have the exact same behavior. But still, the debug log message is NOT printed in this example.
# foo.py (same as above)
import logging
logger = logging.getLogger(__name__)
class Foo(object):
def __init__(self):
logger.debug('debug log from Foo')
##########################################################################
# loggingtest.py
import logging.config
from foo import Foo
if __name__ == '__main__':
logging.config.fileConfig('logging.cfg')
# does NOT print debug log message to console. WHY???
foo = Foo()
##########################################################################
# logging.cfg
[loggers]
keys = root
[logger_root]
level = NOTSET
handlers = consoleHandler
[formatters]
keys = complex
[formatter_complex]
format = %(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s
[handlers]
keys = consoleHandler
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=complex
args=(sys.stdout,)
So why is the second example using a logging fileconfig NOT printing my debug log message to the console?
Since
fileConfig
disables existing loggers by default, callbefore
or call