Using python Logging with AWS Lambda Using python Logging with AWS Lambda python python

Using python Logging with AWS Lambda


Copied straight from the top answer in the question @StevenBohrer's answer links to (this did the trick for me, replacing the last line with my own config):

root = logging.getLogger()if root.handlers:    for handler in root.handlers:        root.removeHandler(handler)logging.basicConfig(format='%(asctime)s %(message)s',level=logging.DEBUG)


The reason that logging does not seem to work is because the AWS Lambda Python runtime pre-configures a logging handler that, depending on the version of the runtime selected, might modify the format of the message logged, and might also add some metadata to the record if available. What is not preconfigured though is the log-level. This means that no matter the type of log-message you try to send, it will not actually print.

As AWS documents themselves, to correctly use the logging library in the AWS Lambda context, you only need to set the log-level for the root-logger:

import logginglogging.getLogger().setLevel(logging.INFO)

If you want your Python-script to be both executable on AWS Lambda, but also with your local Python interpreter, you can check whether a handler is configured or not, and fall back to basicConfig (which creates the default stderr-handler) otherwise:

if len(logging.getLogger().handlers) > 0:    # The Lambda environment pre-configures a handler logging to stderr. If a handler is already configured,    # `.basicConfig` does not execute. Thus we set the level directly.    logging.getLogger().setLevel(logging.INFO)else:    logging.basicConfig(level=logging.INFO)


I had a similar problem, and I suspect that the lambda container is calling logging.basicConfig to add handlers BEFORE the lambda code is imported. This seems like bad form...

Workaround was to see if root logger handlers were configured and if so, remove them, add my formatter and desired log level (using basicConfig), and restore the handlers.

See this article Python logging before you run logging.basicConfig?