To log messages to both a file and stdout using Python’s logging
module, you just need to add a second handler—for example, a StreamHandler
for stdout—in addition to your existing RotatingFileHandler
.
# Stream handler (stdout)
stream_handler = logging.StreamHandler(sys.stdout)
stream_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
stream_handler.setFormatter(stream_formatter)
# add stream handler to logger
logger.addHandler(stream_handler)
For a deeper guide on setting up logging the right way in Python web apps (including best practices, gotchas, and advanced tips), check out this article:
👉 The Right Way to Maintain Logs in Python Web Apps (Part 1)