Sub topic 14
Access logs, metrics and CloudWatch Logs
This chapter assumes you have deployed an HTTP API with a Lambda proxy integration, as in the earlier chapters on SAM and stages. You should also know what a CloudWatch log group is. By the end you will be able to turn on access logs, read the built-in metrics, and trace one failed request from the API to your function.
Three sources of evidence
An HTTP API request leaves traces in three places. Each answers a different question.
| Source | Where it lives | Question it answers |
|---|---|---|
| Access logs | A log group you create and attach to the stage | What requests arrived, and what status did API Gateway return? |
| API metrics | CloudWatch namespace `AWS/ApiGateway` | How many requests, how many errors, how slow? |
| Function logs and metrics | `/aws/lambda/<function-name>` and namespace `AWS/Lambda` | What did my code do? |
HTTP APIs have no execution logging. That feature exists only for REST APIs. For HTTP APIs, the access log is the only API-side log. This makes the request ID important, because it ties the access log line to your function's log lines.
Turning on access logs
Access logging is a stage setting with two parts: a destination ARN (the log group) and a format string. The format is a template. API Gateway fills in $context.* variables for each request and writes one line.
The format must contain $context.requestId. Writing it as JSON makes the lines searchable by field in CloudWatch Logs Insights.
Create the log group in the same template, so you control retention. Without a retention setting, logs are kept forever and you pay for storage.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Resources:
ApiAccessLogs:
Type: AWS::Logs::LogGroup
Properties:
RetentionInDays: 14
ItemsApi:
Type: AWS::Serverless::HttpApi
Properties:
StageName: prod
AccessLogSettings:
DestinationArn: !GetAtt ApiAccessLogs.Arn
Format: >-
{"requestId":"$context.requestId",
"routeKey":"$context.routeKey",
"status":"$context.status",
"ip":"$context.identity.sourceIp",
"responseLatency":"$context.responseLatency",
"integrationLatency":"$context.integrationLatency",
"integrationStatus":"$context.integration.status",
"integrationError":"$context.integrationErrorMessage",
"errorMessage":"$context.error.message"}
DefaultRouteSettings:
DetailedMetricsEnabled: true
ItemsFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.13
Handler: app.handler
CodeUri: src/
Events:
GetItem:
Type: HttpApi
Properties:
ApiId: !Ref ItemsApi
Path: /items/{id}
Method: GETThe >- folds the format onto one line. The line breaks inside the JSON are therefore replaced by spaces and the output stays valid JSON.
The variables that matter most when debugging:
$context.statusis the status code API Gateway returned to the client.$context.integration.statusis the status the integration returned. For Lambda this is the status of the invoke call itself, not yourstatusCodefield.$context.integrationErrorMessageexplains integration failures, such as a function that timed out.$context.error.messageexplains failures that API Gateway raised itself, such as an authorizer denial or a missing route.$context.responseLatencyis the total time in milliseconds.$context.integrationLatencyis the part spent in the integration. The difference is overhead in API Gateway.
Reading the built-in metrics
HTTP APIs publish these metrics to AWS/ApiGateway with the dimensions ApiId and Stage:
| Metric | Meaning |
|---|---|
| `Count` | Total requests |
| `4xx` | Requests that ended in a client error |
| `5xx` | Requests that ended in a server error |
| `Latency` | Time from receiving the request to returning the response |
| `IntegrationLatency` | Time from sending to the backend to receiving its response |
| `DataProcessed` | Bytes processed |
Metrics are aggregated per stage by default. Setting DetailedMetricsEnabled: true, as in the template above, adds a Route dimension, so you can see that GET /items/{id} is slow while POST /items is healthy. Detailed metrics are billed as custom metrics, so enable them where you need per-route data.
Use the Sum statistic for Count, 4xx and 5xx. Use p90 or p99 for latency, because an average hides slow outliers. A common alarm is 5xx summed over five minutes above a small threshold, which catches function crashes and timeouts.
Lambda publishes its own metrics in AWS/Lambda: Invocations, Errors, Duration and Throttles. These help locate the failing layer:
- API
5xxrises and LambdaErrorsrises: the function is failing. - API
5xxrises and LambdaErrorsstays flat: look atThrottles, or at API-side errors in the access log. IntegrationLatencyis close toLatency: the time is in your function, not in API Gateway.
Writing function logs you can correlate
Anything your function prints to standard output goes to /aws/lambda/<function-name>, as long as the execution role allows logging. The managed policy AWSLambdaBasicExecutionRole grants that, and SAM adds it for you.
For payload format 2.0, event["requestContext"]["requestId"] equals the $context.requestId in the access log. If you include it in every log line, you can jump from an access log entry straight to the matching function lines.
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def log(request_id, message, **fields):
logger.info(json.dumps({"requestId": request_id, "message": message, **fields}))
def handler(event, context):
request_id = event["requestContext"]["requestId"]
route = event["requestContext"]["routeKey"]
log(request_id, "request received", route=route)
try:
item_id = event["pathParameters"]["id"]
log(request_id, "looking up item", itemId=item_id)
return {
"statusCode": 200,
"headers": {"content-type": "application/json"},
"body": json.dumps({"id": item_id}),
}
except Exception:
logger.exception("unhandled error for request %s", request_id)
return {
"statusCode": 500,
"headers": {"content-type": "application/json"},
"body": json.dumps({"message": "Internal error"}),
}logger.exception writes the stack trace. Catching the exception and returning a 500 yourself is optional. If you let it propagate, Lambda records the error and API Gateway returns {"message":"Internal Server Error"} with status 500.
Tracing one failed request
Here is a typical flow when a user reports an error.
- Get the time and, if possible, the route. Open the access log group and filter for failures.
- Read
status,integrationStatusand the two error fields. They tell you which side failed. - Take the
requestIdand search the function log group for it.
This Logs Insights query, run against the access log group, lists recent server errors:
fields @timestamp, requestId, routeKey, status, integrationError, errorMessage
| filter status like /^5/
| sort @timestamp desc
| limit 20The values are strings, because the format quoted them, so the filter matches the first digit with a regular expression. Run this one against the function log group to see everything for one request:
fields @timestamp, @message
| filter requestId = "abc123-example-request-id"
| sort @timestamp ascYou can also tail the function logs from a terminal with the AWS CLI v2:
aws logs tail /aws/lambda/ItemsFunction --since 15m --followReplace ItemsFunction with the physical function name from your stack. The generated name includes a suffix.
Reading the symptoms
| Access log shows | Likely cause |
|---|---|
| `status` 500, `integrationStatus` 200 | The function returned a malformed response, or `statusCode` was 500. Check the function log. |
| `status` 500 or 502, `integrationError` mentions a timeout | The function exceeded its timeout, or the 30-second API Gateway integration limit. |
| `status` 404, no `integrationStatus` | No route matched and no `$default` route exists. |
| `status` 401 or 403 with `errorMessage` set | An authorizer denied the request before your function ran. No function log exists. |
| `status` 429 | Throttling at the stage or route. |
If a request produces an access log line but no function log, the function never ran. If it produces neither, the request did not reach this stage, so check the URL, stage name or custom domain.
Exercise
A client reports intermittent errors on GET /items/{id}. The access log lines for these requests show status 500, integrationStatus 200 and an empty integrationError. Which log should you read next, and what do you expect to find?
Show answer
Read the function's log group, searching for the requestId from the access log line. The integration status of 200 means the Lambda invocation itself succeeded, so API Gateway had no trouble reaching the function. The 500 therefore came from the response your code returned. Either the handler set statusCode to 500 deliberately, or it returned a response that was not valid for payload format 2.0. The function log with the matching requestId shows the stack trace or the message that explains which.
Exercise
Why would you enable DetailedMetricsEnabled on the stage, and what is the cost of doing so?
Show answer
It adds a Route dimension to the API metrics, so Count, 4xx, 5xx and latency can be viewed and alarmed per route instead of only per stage. This lets you spot one slow or failing route that stage-wide averages hide. The cost is that these metrics are billed as custom CloudWatch metrics, so enabling them on many routes raises your monitoring bill.