Lesson 4 of 8 Amazon CloudWatch

Writing Structured Logs with Powertools for AWS Lambda

This lesson explains how structured logs are written as JSON fields rather than free text, which makes them easy to search, filter and aggregate.

Learning outcomes

After completing this lesson, you will be able to:

  • Identify the fields a structured log entry should contain, including a correlation ID.
  • Choose the right log level for an event.
  • Describe how the Powertools for AWS Lambda Logger, Metrics and Tracer utilities implement these practices.

What a structured log entry contains

Include a consistent set of fields, such as timestamp, level, service, request ID and a correlation ID that follows a request across services, plus fields specific to the event:

{"level":"ERROR","service":"orders","correlation_id":"abc","order_id":"123","message":"payment declined"}

Logs Insights discovers JSON fields automatically, so this entry is found with filter level = "ERROR" and service = "orders".

Log levels

Every log entry is given a level that states its importance. DEBUG entries contain detail that helps while developing or investigating, such as intermediate values. INFO entries record normal significant events, such as an order being placed. WARN entries record unexpected conditions that the application handled, such as a retry, and ERROR entries record failures that need attention.

The application is configured with a minimum level, and entries below it are discarded. A development environment might log at DEBUG, while production logs at INFO or WARN, which reduces log volume and cost without changing the code. During an incident, the level can be lowered temporarily to capture more detail. The following table summarises the levels.

LevelUse for
DEBUGDetail needed while developing
INFONormal events
WARN, ERRORProblems

Lambda's advanced logging controls output JSON natively and set the log level per function without code changes, reducing log volume and cost in production.

Sort into groups

Choose the log level

Exam skills 4.2.1

Give each log entry the right level.

Log in to try this activity Interactive activities are free with an account.

Powertools for AWS Lambda

Powertools for AWS Lambda is an open-source library, available for Python, TypeScript, Java and .NET, that implements the logging, metrics and tracing practices in this lesson with a few lines of code.

The Logger writes structured JSON log entries and adds Lambda context to each one automatically, including the function name, request ID and whether the invocation was a cold start, and it can extract a correlation ID from the incoming event. The Metrics utility collects custom metrics during an invocation and writes them as a single Embedded Metric Format log entry at the end, so metrics cost no API calls. The Tracer wraps the handler and selected functions in X-Ray subsegments and records their responses and exceptions. Other utilities implement idempotency for handlers that may receive duplicate events, partial failure reporting for batches from SQS, Kinesis and DynamoDB Streams, cached retrieval of parameters and secrets, and data masking. The following table summarises the utilities.

UtilityWhat it does
LoggerStructured logs enriched with Lambda context
MetricsCustom metrics in Embedded Metric Format
TracerX-Ray integration
OthersIdempotency, batch processing, parameters and data masking
from aws_lambda_powertools import Logger, Metrics, Tracer
from aws_lambda_powertools.logging import correlation_paths
from aws_lambda_powertools.metrics import MetricUnit

logger = Logger(service="orders")
tracer = Tracer(service="orders")
metrics = Metrics(namespace="MyApp", service="orders")

@logger.inject_lambda_context(correlation_id_path=correlation_paths.API_GATEWAY_REST)
@tracer.capture_lambda_handler
@metrics.log_metrics(capture_cold_start_metric=True)
def handler(event, context):
    order = parse(event)
    logger.info("Order placed", extra={"order_id": order.id, "total": order.total})
    metrics.add_metric(name="OrdersPlaced", unit=MetricUnit.Count, value=1)
    return {"statusCode": 201}

The resulting log line:

{"level":"INFO","message":"Order placed","service":"orders","order_id":"9017","total":249.99,
 "function_request_id":"c6af9ac6-...","correlation_id":"9a1b2c...","cold_start":false,"timestamp":"2026-10-07T09:12:44Z"}

Whatever tools you use, set a retention period on every log group and never log secrets or personal data.

Match the pairs

Powertools utilities

Exam skills 4.2.1 · 4.2.2 · 4.2.4

Match each Powertools utility or setting with what it does.

Log in to try this activity Interactive activities are free with an account.
Worked example

Finding one customer's failed requests

A customer reports a failed order at about 14:00. With unstructured text logs, finding their requests means guessing at text patterns. With structured logs from Powertools, every line includes the customer ID and a correlation ID, so one query finds them:

fields @timestamp, level, message, correlation_id
| filter customer_id = "C-1042" and level = "ERROR"
| sort @timestamp desc

The correlation ID then links those lines to the same request's logs in other services and to its X-Ray trace. Structured logging turns log searching into querying.

Check yourself

Why write logs as JSON with a correlation ID rather than as plain text?

Show answer

Fields such as the order ID can be queried and filtered directly, for example in CloudWatch Logs Insights, and the correlation ID links every entry that belongs to one request across services.

Exam Tips

Remember for the exam

  • For logs you can query by field, use JSON structured logging and CloudWatch Logs Insights.
  • To apply logging, metrics and tracing best practices in Lambda with little code, use Powertools for AWS Lambda.
  • To follow a request across services, use correlation IDs.
  • To reduce log volume in production without code changes, set the Lambda application log level.