debugpythonCritical
Making Python loggers output all messages to stdout in addition to log file
Viewed 0 times
alllogpythonmessagesadditionmakingstdoutoutputfileloggers
Problem
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")Solution
All logging output is handled by the handlers; just add a
Here's an example configuring a stream handler (using
logging.StreamHandler() to the root logger.Here's 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)Code Snippets
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)Context
Stack Overflow Q#14058453, score: 953
Revisions (0)
No revisions yet.