Reputation: 199
I am writing the below code to log messages into a file:
#!/usr/bin/python3
import logging
## init logger
logger = logging.getLogger(__name__)
## create handler file
handler = logging.FileHandler('mylog3.log')
## set log level
handler.setLevel(logging.INFO)
## add handler to logger
logger.addHandler(handler)
l = [1, 2, 3, 4]
i = 3
logger.info('This is an info message')
logger.warning('This is a warning message')
logger.debug('This is a debug message. I=%d l=%s', i, l)
logger.error('This is an error message. l =%s', l)
logger.fatal('This is a fatal error message')
The problem I am seeing is that no matter what setting I give, it always prints the warning, error and fatal error messages in file. The debug and info messages are never written.
I verified that I am seeing the issue w/ both PyCharm on Windows and also on my Ubuntu linux Python 3. So, it must be that I am doing something wrong. What can it be? I am at a loss!
Upvotes: 1
Views: 586
Reputation: 99355
Both loggers and handlers have levels. You've set the level for the handler, but not for the logger - and that defaults to WARNING
. If you do e.g. logger.setLevel(logging.DEBUG)
, you should see DEBUG
and INFO
messages as well (if you don't set a level on the handler at all) or INFO
messages but not DEBUG
messages (if you set the handler's level to logging.INFO
).
See this diagram for more info on the information flow in logging.
Upvotes: 1
Reputation: 3279
The debug and info messages are not shown because of the line handler.setLevel(logging.INFO)
. This causes all messages of level logging.INFO
or less (only info and debug) to not be shown. You can replace loggign.INFO
with logging.NOTSET
to fix this.
Upvotes: 1