[python] How to write to a file, using the logging Python module?

Here is two examples, one print the logs (stdout) the other write the logs to a file:

import logging
import sys

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')

stdout_handler = logging.StreamHandler(sys.stdout)
stdout_handler.setLevel(logging.DEBUG)
stdout_handler.setFormatter(formatter)

file_handler = logging.FileHandler('logs.log')
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(formatter)


logger.addHandler(file_handler)
logger.addHandler(stdout_handler)

With this example, all logs will be printed and also be written to a file named logs.log

Use example:

logger.info('This is a log message!')
logger.error('This is an error message.')