Skip to content

Feature request: Add typing for log parameter in LambdaPowertoolsFormatter #2401

Closed
@erikayao93

Description

@erikayao93

Use case

Change discussed in #2014
Improve the existing mechanism of the LambdaPowertoolsFormatter by typing the log parameter with TypedDict

Solution/User Experience

Create a new types.py for the logger that will include the new TypedLog class, similar to:

from typing_extensions import TypedDict


class TypedLog(TypedDict, total=False):
    level: str
    location: str
    timestamp: str
    service: str
    event: str

When overriding the serialize() function of the LambdaPowertoolsFormatter, customers can have type checking on our log fields using the new TypedLog class, similar to:

from aws_lambda_powertools import Logger
from aws_lambda_powertools.logging.formatter import LambdaPowertoolsFormatter
from aws_lambda_powertools.logging.types import TypedLog


class CustomFormatter(LambdaPowertoolsFormatter):
    def serialize(self, log: TypedLog) -> str:
        """Serialize final structured log dict to JSON str"""
        log["event"] = log.pop("message")  # rename message key to event
        return self.json_serializer(log)  # use configured json serializer


logger = Logger(service="payment", logger_formatter=CustomFormatter())
logger.info("hello")

Alternative solutions

No response

Acknowledgment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions