If you want one logger for the screen and one for the log file, try this:
import logging
log = logging.getLogger('logger')
log.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(message)s')
fh = logging.FileHandler('test.log', mode='w', encoding='utf-8')
fh.setLevel(logging.DEBUG)
fh.setFormatter(formatter)
log.addHandler(fh)
ch = logging.StreamHandler()
ch.setLevel(logging.INFO)
ch.setFormatter(formatter)
log.addHandler(ch)
This creates two log handlers. When you call log.debug
/info
/warning
etc, it will log to each of your handlers. If the level they are set at is the same or higher, it will log the message, otherwise it won't.
In this example calling log.debug("test message")
will save the str
"test message to test.log
, but you will not see the output on the screen because the StreamHandler()
's level is above the debug
debug.
When you call log.info("test message")
, it will save the str
"test message to test.log
and output it to the console because StreamHandler()
's level is info
log.setLevel(logging.DEBUG)
ensures that everything will be logged. If you exclude this line, the default of WARNING
will be enforced, and even if you set the level lower in a separate handler, you won't be able to log anything >= that level
The levels for logging are as follows:
DEBUG
INFO
WARNING
ERROR
CRITICAL