Two logs, one logger.

Though the Python logging documentation doesn’t make it entirely clear, it is possible to log to two different places with a single logger object. It’s even possible to dynamically adjust the log level of each output handler.

The trick is to get a handle on a single logger (you can use a named logger if you don’t want to use “root”. We’ll kick off the process by making sure we have the logging module imported.

import logging

We must set the root logger level to at least as low as all other loggers or it will choke the logging of the other handlers.

root_logger = logging.getLogger("")

You can then add as many log handlers to that logger as you like, each with its own log level.

file_logger = logging.FileHandler(....)

console_logger = logging.StreamHandler()

Then elsewhere in your code, you simply use:"This will go to both handlers.")
logging.debug("This will only go to the file logger.")

Hopefully that’s been educational. A working example can be found in my boilerplate repository as usual.

Leave a Reply