Reset default python log handlers

Snippet

import logging

formatter = logging.Formatter('FOO: %(message)s')

root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)

# This is the key line that removes the double logging
root_logger.handlers.clear()

# Must add a custom logger back otherwise there will be no log output
sys_stream = logging.StreamHandler()
sys_stream.setFormatter(formatter)
root_logger.addHandler(sys_stream)


logger = logging.getLogger(__name__)

Description

AWS lambdas seem to add their own custom logging to the python logger, causing all logs to output twice when also adding your own custom logger. You may not see any change when running this locally, but it does make a difference when running in a aws lambda.

By xtream1101 Updated 2025-03-04 18:33