4.2.7 Implement Structured Logging

Structured Logging for Application Events

Why Structured Logging?

{
  "timestamp": "2025-01-15T10:30:00Z",
  "level": "INFO",
  "message": "Order created",
  "requestId": "abc-123",
  "userId": "user-456",
  "orderId": "order-789",
  "duration_ms": 150
}
  • Dễ parse, filter, query trong Logs Insights
  • Consistent format across services
  • Machine-readable

Lambda Powertools — Logger

from aws_lambda_powertools import Logger

logger = Logger(service="order-service")

@logger.inject_lambda_context(log_event=True)
def handler(event, context):
    logger.info("Processing order", extra={
        "order_id": "order-123",
        "customer_id": "cust-456"
    })

Correlation IDs

API Gateway → Lambda A → SQS → Lambda B → DynamoDB
     ↓            ↓                ↓
  requestId    requestId       requestId (propagated)
  • Pass requestId through all service calls
  • Filter logs across services by correlation ID

Exam Tip: Structured logging = JSON format. Lambda Powertools = easiest way. Correlation IDs cho cross-service tracing.