1 min read

SAM local invoke function logs with Python

Get SAM local invoke functions logging properly with Python

I was shocked how hard it was to view my function's logs when using the sam local invoke command with a Python function.

I just wanted to see my function's log output, like I would in the CloudWatch Logs console, but the only output I got was the function start/stop time, and the final return value.

The first gotcha - don't use logging.basicConfig, which is what's used in the offical docs for logging. This old issue on the repo points out that this happens in the actual Lambda runtime, so SAM is doing the "right" thing, but it is confusing. Why the Lambda Python rutime doesn't support basicConfig I don't know 🤷‍♂️


With the following set up, I was able to set the log level via an environment variable string (e.g. "DEBUG", "INFO", etc) and have it translated to the right log level at runtime:

import logging
import os

level = logging.getLevelName(os.environ.get('LOG_LEVEL', 'INFO'))
log = logging.getLogger(__name__)

Also remember to build your function before calling sam local invoke, as it will look at the built version, and not the actual code - I spent way too many times looking at the output of an older version of my code because I forgot to rebuild.