Skip to content

Logger

It’s a wrapper of Python’s logging library that provides extra capabilities such as JSON output configuration (and many more).

Logger

Key features

  • Capture key fields from Lambda context, cold start and structures logging output as JSON
  • Log Lambda event when instructed (disabled by default)
  • Append additional keys to structured log at any point in time

Usage in Handler

my_handler.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import json
from http import HTTPStatus
from typing import Any

from aws_lambda_powertools.logging.logger import Logger
from aws_lambda_powertools.utilities.typing import LambdaContext

logger: Logger = Logger(service='service')  # JSON output format, service name can be set by environment variable "POWERTOOLS_SERVICE_NAME"


def my_handler(event: dict[str, Any], context: LambdaContext) -> dict[str, Any]:
    logger.set_correlation_id(context.aws_request_id)
    logger.debug('my_handler is called')
    return {'statusCode': HTTPStatus.OK, 'headers': {'Content-Type': 'application/json'}, 'body': json.dumps({'message': 'success'})}

Blog Reference

Read more about the importance of the logger and how to use AWS CloudWatch logs in my blog. Click HERE

More Details

You can find more information at the official documentation.

Go to https://docs.powertools.aws.dev/lambda-python/latest/core/logger/