Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (19k points)

Is there a way to make Python logging using the logging module automatically output things to stdout in addition to the log file where they are supposed to go? For example, I'd like all calls to logger.warning, logger.critical, logger.error to go to their intended places but in addition always be copied to stdout. This is to avoid duplicating messages like:

mylogger.critical("something failed")

print "something failed"

1 Answer

0 votes
by (106k points)

For making Python loggers output all messages to stdout in addition to the log file you can use the following method which is using logging and sys module to :

import logging

import sys

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

One thing to note that all the logging output is handled by the handlers, you just need to add logging.StreamHandler() to the logger which is root.

Below is an example that is using stdout instead of the default stderr and also adding it to the root logger.

import logging

import sys

root = logging.getLogger()


handler = logging.StreamHandler(sys.stdout) handler.setLevel(logging.DEBUG)

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')



For more information, kindly refer to our Python course. 

Browse Categories