Making Python loggers output all messages to stdout in addition to log file
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"
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)
Note
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 for python logging stdout, using stdout instead of the default stderr and also 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)