logging – Making Python loggers output all messages to stdout in addition to log file

logging – Making Python loggers output all messages to stdout in addition to log file

All logging output is handled by the handlers; just add a logging.StreamHandler() to the root logger.

Heres an example configuring a stream handler (using stdout instead of the default stderr) and adding it to the root logger:

import logging
import sys

root = logging.getLogger()
root.setLevel(logging.DEBUG)

handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.DEBUG)
formatter = logging.Formatter(%(asctime)s - %(name)s - %(levelname)s - %(message)s)
handler.setFormatter(formatter)
root.addHandler(handler)

The simplest way to log to stdout:

import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)

logging – Making Python loggers output all messages to stdout in addition to log file

You could create two handlers for file and stdout and then create one logger with handlers argument to basicConfig. It could be useful if you have the same log_level and format output for both handlers:

import logging
import sys

file_handler = logging.FileHandler(filename=tmp.log)
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG, 
    format=[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s,
    handlers=handlers
)

logger = logging.getLogger(LOGGER_NAME)

Leave a Reply

Your email address will not be published. Required fields are marked *