Sub topic 13
Observing Functions with CloudWatch and X-Ray
This chapter assumes you can deploy a function with SAM, understand its execution role, and know how invocation types differ. It covers the three signals Lambda produces (logs, metrics and traces), how to configure each, and how to use them to find a failing or slow function.
The three signals
Lambda sends data to two AWS services. Amazon CloudWatch receives logs and metrics. AWS X-Ray receives traces. Each answers a different question.
| Signal | Service | Question it answers | Granularity |
|---|---|---|---|
| Logs | CloudWatch Logs | What happened inside this invocation? | One line per event you write, plus platform lines |
| Metrics | CloudWatch Metrics | Is the function healthy over time? | Aggregates per minute |
| Traces | X-Ray | Where did the time go across services? | One trace per sampled request |
Logs
Anything your code writes to standard output or standard error becomes a log event. Lambda delivers it to a log group named /aws/lambda/<function-name>. Each execution environment writes to its own log stream, so one function usually has many streams.
For delivery to work, the execution role needs logs:CreateLogGroup, logs:CreateLogStream and logs:PutLogEvents. The managed policy AWSLambdaBasicExecutionRole grants these. SAM adds it automatically when you use the Policies property. If you write the role by hand and omit these actions, the function still runs and returns normally, but you get no logs. This is the most common reason for an empty log group.
Lambda also writes three platform lines for every invocation:
START RequestId: ...END RequestId: ...REPORT RequestId: ...withDuration,Billed Duration,Memory Size,Max Memory Used, andInit Duration
Init Duration appears only on cold starts, so you can count cold starts from the logs alone. Comparing Max Memory Used with Memory Size tells you whether the memory setting from the configuration chapter is right.
Structured logging
Plain text logs are hard to filter. Lambda can emit JSON logs for you if you set the log format. In Python, the standard logging module then produces JSON that includes the timestamp, level, message and request ID. Fields you pass through extra become top-level keys.
import logging
logger = logging.getLogger()
def handler(event, context):
order_id = event.get("order_id", "unknown")
logger.info("processing order", extra={"order_id": order_id})
try:
if order_id == "unknown":
raise ValueError("missing order_id")
except ValueError:
logger.exception("order failed", extra={"order_id": order_id})
raise
return {"ok": True}Re-raising after logging matters. If you swallow the exception, Lambda reports a successful invocation, the Errors metric stays at zero, and retries never happen.
Retention
New log groups keep logs forever by default, and storage is billed. Set a retention period in your template. The SAM template later in this chapter does this.
Metrics
Lambda publishes metrics to the AWS/Lambda namespace without any code from you. The ones you will use most:
Invocations: requests, whether they succeed or not.Errors: invocations that raised an exception or timed out. It does not count throttles.Throttles: invocations rejected because of a concurrency limit.Duration: run time in milliseconds. Use the p95 or p99 statistic rather than the average.ConcurrentExecutions: environments running at the same time.IteratorAge: for stream sources, how old the last record was when it was read. A rising value means the function is falling behind.DeadLetterErrorsandDestinationDeliveryFailures: failures sending to a dead-letter queue or destination.AsyncEventsDropped: asynchronous events discarded after all retries.
Custom metrics with Embedded Metric Format
Calling the CloudWatch PutMetricData API from inside a handler adds latency and cost. The Embedded Metric Format (EMF) avoids this. You print a specially shaped JSON line, and CloudWatch extracts metrics from it asynchronously.
import json
import time
def emit_metric(name, value, **dimensions):
print(json.dumps({
"_aws": {
"Timestamp": int(time.time() * 1000),
"CloudWatchMetrics": [{
"Namespace": "Orders",
"Dimensions": [list(dimensions.keys())],
"Metrics": [{"Name": name, "Unit": "Count"}],
}],
},
name: value,
**dimensions,
}))
def handler(event, context):
emit_metric("OrdersCreated", 1, Service="orders")
return {"statusCode": 201}The dimension values and the metric value appear as top-level keys, as shown. A mismatch between the names listed under _aws and the keys in the object means the metric is silently not created.
Tracing with X-Ray
A trace follows one request through several services. This helps when a slow API call could be caused by the function, DynamoDB or a downstream HTTP service.
Turn on active tracing and Lambda creates a segment for each sampled invocation. It also records an Initialization subsegment on cold starts. The role needs xray:PutTraceSegments and xray:PutTelemetryRecords. SAM adds them when you set Tracing: Active.
Sampling is not 100 percent. With active tracing, Lambda records the first request each second and 5 percent of the rest. If an upstream service such as API Gateway has already made a sampling decision and passed it along, Lambda follows that decision.
To see calls to other AWS services, instrument the SDK. The X-Ray SDK for Python patches boto3 so each call becomes a subsegment.
from aws_xray_sdk.core import patch_all, xray_recorder
patch_all()
def handler(event, context):
with xray_recorder.in_subsegment("validate") as subsegment:
subsegment.put_annotation("order_id", event.get("order_id", "unknown"))
subsegment.put_metadata("raw_event", event)
return {"ok": True}An annotation is an indexed key and value you can search by. Metadata is stored but not searchable. The code opens a subsegment because the segment Lambda creates for the function cannot be modified from your code, so annotations must go on a subsegment you create.
Configuring it all in SAM
This template turns on JSON logs, active tracing, a managed log group with retention, and an alarm on errors.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Runtime: python3.12
Timeout: 10
Tracing: Active
Resources:
OrdersFunction:
Type: AWS::Serverless::Function
Properties:
Handler: app.handler
CodeUri: src/
LoggingConfig:
LogFormat: JSON
ApplicationLogLevel: INFO
SystemLogLevel: WARN
LogGroup: !Ref OrdersLogGroup
OrdersLogGroup:
Type: AWS::Logs::LogGroup
Properties:
RetentionInDays: 14
OrdersErrorsAlarm:
Type: AWS::CloudWatch::Alarm
Properties:
Namespace: AWS/Lambda
MetricName: Errors
Dimensions:
- Name: FunctionName
Value: !Ref OrdersFunction
Statistic: Sum
Period: 300
EvaluationPeriods: 1
Threshold: 5
ComparisonOperator: GreaterThanOrEqualToThreshold
TreatMissingData: notBreachingTreatMissingData: notBreaching matters because an idle function publishes no data points. Without it, the alarm can sit in INSUFFICIENT_DATA and look broken.
Investigating with Logs Insights
CloudWatch Logs Insights queries one or more log groups. Because the REPORT line is parsed into fields, you can build a performance summary without changing any code.
filter @type = "REPORT"
| stats count() as invocations,
count(@initDuration) as coldStarts,
avg(@duration) as avgMs,
pct(@duration, 95) as p95Ms,
max(@maxMemoryUsed / 1000 / 1000) as maxMemoryMB
by bin(5m)To find failures, filter on your own structured fields instead, for example filter level = "ERROR" and order_id = "A-1001". This works because JSON logs make each key a queryable field.
Common problems
| Symptom | Likely cause | Fix |
|---|---|---|
| Function runs but log group is missing or empty | Role lacks the `logs:*` permissions | Attach `AWSLambdaBasicExecutionRole` |
| `Errors` is zero but callers see failures | Handler caught the exception and returned an error body | Re-raise, or alarm on your own metric |
| No traces in X-Ray | Active tracing is off, or the role lacks X-Ray permissions | Set `Tracing: Active` |
| Some requests missing from traces | Sampling | Expected behavior. Use annotations to find the ones you have |
| Custom EMF metric never appears | Metric name or dimension keys not present in the JSON | Match `_aws` declarations to top-level keys |
| Log costs keep growing | Retention left at never expire | Set `RetentionInDays` |
| Log lines appear several seconds late | Logs are delivered asynchronously | Wait, and do not rely on logs for control flow |
A debugging routine
- Check
Invocations,ErrorsandThrottlesfor the time window to see which kind of problem you have. - Open the log group and find the failing request ID. Read the lines for that ID in order.
- If the cause is not in the function, open the trace and look for the longest or errored subsegment.
- Use the
REPORTline to check for timeouts (Durationclose to your configured timeout) and memory pressure. - Add a structured log field or annotation for whatever you had to guess, so the next failure is easier to trace.
Exercise
A function triggered asynchronously by S3 fails for some objects. The Errors alarm never fires, and nobody notices missing output. Name two metrics or settings that would have surfaced the problem, and explain why Errors alone was not enough.
Show answer
Errors only counts invocations that ran and failed in a given period. If the alarm was set with a high threshold or evaluated over a long window, a few failures stay below it. More importantly, an asynchronous event that exhausts its retries is dropped, which shows up in AsyncEventsDropped, and a failed delivery to a dead-letter queue or destination shows up in DeadLetterErrors or DestinationDeliveryFailures. Alarming on AsyncEventsDropped, or configuring an on-failure destination and alarming on messages arriving there, would have surfaced the lost events. Throttled events are not counted in Errors either, so Throttles is also worth an alarm.
Exercise
You call xray_recorder.put_annotation("order_id", "A-1") directly inside a Lambda handler and get an error. What is the cause and the fix?
Show answer
Lambda creates the function's segment itself, and your code cannot modify it. Open a subsegment with with xray_recorder.in_subsegment("name") as subsegment: and call subsegment.put_annotation(...) on that.