Skip to content

Instantly share code, notes, and snippets.

@instantiator
Created January 13, 2026 16:45
Show Gist options
  • Select an option

  • Save instantiator/3b5505997e05f1b1dc4653f70226a071 to your computer and use it in GitHub Desktop.

Select an option

Save instantiator/3b5505997e05f1b1dc4653f70226a071 to your computer and use it in GitHub Desktop.
A short script to retrieve logs from a specified Lambda function in a specified CloudFormation stack.
#!/bin/bash
# A script to view logs for a specific Lambda function in a CloudFormation stack.
set -e
set -o pipefail
function usage() {
echo "View logs for a specific Lambda function in a CloudFormation stack."
echo "Usage: $0 -s <stack-name> -f <function-name> [-r <region>] [<other-aws-logs-args>]"
echo ""
echo " -s, --stack-name The name of the CloudFormation stack."
echo " -f, --function-name The name of the Lambda function (as defined in the stack)."
echo " -r, --region AWS region (default: eu-west-1)."
echo
echo " (all other arguments) Additional arguments to pass to 'aws logs tail'."
}
# Check for jq
if ! command -v jq &> /dev/null; then
echo "'jq' is required to review and select the most recent log group."
echo "Please install 'jq' to use this script (eg. `brew install jq` on macOS)."
exit 1
fi
# Defaults
STACK_NAME=""
FUNCTION_NAME=""
OTHER_ARGS=()
REGION="eu-west-1"
while [[ $# -gt 0 ]]; do
case $1 in
-s|--stack-name)
STACK_NAME="$2"
shift 2
;;
-f|--function-name)
FUNCTION_NAME="$2"
shift 2
;;
-r | --region)
REGION="$2"
shift 2
;;
-h|--help)
usage
exit 0
;;
*)
OTHER_ARGS+=("$1")
shift
;;
esac
done
# Validate inputs - stack and function name are required
if [ -z "$STACK_NAME" ] || [ -z "$FUNCTION_NAME" ]; then
usage
exit 1
fi
# Find the log group
LOG_GROUP_PREFIX="/aws/lambda/${STACK_NAME}"
# Use AWS CLI to find the log group name by listing all and grepping
# Sort by creationTime to get the most recent log group if multiple exist
# echo "Searching for log group with prefix '$LOG_GROUP_PREFIX' containing '$FUNCTION_NAME'..."
LOG_GROUP_NAME=$(aws logs describe-log-groups \
--region "$REGION" \
--log-group-name-prefix "$LOG_GROUP_PREFIX" \
--query "logGroups[?contains(logGroupName, '$FUNCTION_NAME')].[creationTime, logGroupName]" \
--output json | jq -r 'sort_by(.[0]) | reverse | .[0][1]')
# Check if a log group was found
if [ -z "$LOG_GROUP_NAME" ] || [ "$LOG_GROUP_NAME" == "null" ]; then
echo "No log group found for stack '$STACK_NAME' and function '$FUNCTION_NAME'."
exit 1
fi
# echo "Using most recent log group: $LOG_GROUP_NAME"
# echo "Additional arguments: ${OTHER_ARGS[*]}"
exec aws logs tail "$LOG_GROUP_NAME" --region "$REGION" "${OTHER_ARGS[@]}"
@instantiator
Copy link
Author

Typical usage

./view-function-log.sh -s <stack> -f <function> -r <region> --since 10m

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment