NewYour coding agent can read the release notes before it upgrades.Set up the MCP server →
PyPI · #997 most downloaded on PyPI
Powertools for AWS Lambda (Python) is a developer toolkit to implement Serverless best practices and increase developer velocity.
Last release 16 days ago
15 Sep 2026
Ships fairly regularly
a new release about every 3 weeks
Nearly every release is documented
notes for 58 of the last 60 stable releases
3 versions withdrawn
withdrawn after publishing
7 years old
530 releases · first in 2019
This release has three major goodies: 1/ Idempotency utility is now GA, 2/ New API Gateway and ALB event handler, and 3/ MANY enhancements to Logger.
This release has three major goodies: 1/ Idempotency utility is now GA, 2/ New API Gateway and ALB event handler, and 3/ MANY enhancements to Logger.
Idempotency utility was introduced in 1.11.0 as beta. If you haven't used it yet, it converts Lambda functions into idempotent operations that are safe to retry - This is mostly needed when your code is not idempotent.
Since launch, we've made improvements to error handling and documentation updates. This gives us confidence that the UX won't radically change and therefore can be used safely moving forward.
huge thanks to @michaelbrewer
This new utility provides a lightweight routing to reduce boilerplate for API Gateway REST/HTTP API and ALB. It also natively integrates with Data classes utility giving you handy methods and self-documented properties of API Gateway and ALB events.
It's important to note that this is not a replacement for fully fledged web frameworks like Flask and Djano, or microframeworks like Chalice. Instead, this gives you a nearly zero overhead (~1-2ms) lightweight solution to build applications on top of either API Gateway or ALB.
As a trade-off for being so lightweight, you have to setup infrastructure to use Lambda Proxy Integration using your preferred framework be that CloudFormation, SAM, CDK, Terraform, etc. Rest assured we provide a sample template to demonstrate how you can configure it if you haven't done this yet.
Did I say CORS is simplified too? :)
This release makes Logger more flexible by allowing you to bring your own Logging Formatter and Handler. It also includes a ton of improvements such as:
LambdaPowertoolsFormatterutc=True flagappend_keys() and remove_keys(). The previous method, structure_logs(append=True, ...), will continue to work for backwards compatibility and will be effectively when we decide to cut a major version (2.0) - warnings will be place in time toosampling_rate key only gets added when feature is addedtimestamp key now includes timezone at the end: from 2021-05-03 11:47:12,494 to 2021-05-03 11:47:12,494+0200huge thanks to @risenberg-cyberark
You can now easily parse and run deep data validation with APIGatewayProxyEvent in Parser, including an envelope ApiGatewayEnvelope.
Last but not least, you can now set default metric dimensions to ensure these will always be added across all metrics: metrics.set_default_dimensions(environment="prod", another="one")
cors=None setting (#421) by @michaelbrewer@carlos-alberto, @heitorlessa, @michaelbrewer and @risenberg-cyberark
One column per quarter.
This release a new Event Handlers core utility, and enables versioning for documentation so you can access staging docs early or a specific release do
This release a new Event Handlers core utility, and enables versioning for documentation so you can access staging docs early or a specific release doc.
Additionally, there are a number of enhancements in the documentation, Parser's support for S3 Object Lambda event, a better support for MyPy (more to come), etc.
This is a new core utility to help you reduce boilerplate when working with Event Sources. For example, you can now have clearly defined single purpose methods to be called depending on what's inside the event instead of nested flow controls (if/else/elif).
AWS AppSync is our first event handler (thanks to @michaelbrewer), and we would love to hear from you what other event handlers would be useful to boost your experience even further.
Notice how you can combine AppSync scalar utilities, Logger correlation ID, Tracer, and have tiny functions to compute a given GraphQL field or type now.
Some of you might have already noticed a new version switch at the top of the documentation, including additional stats from GitHub directly on the top right corner.
This means you can now access early versions of the documentation before we release as well as the last two releases. This opens the door for a possible nightly build release :)
make pr (#368) by @michaelbrewer@heitorlessa, @michaelbrewer, @risenberg-cyberark and @rtrive
Discussion: https://github.com/awslabs/aws-lambda-powertools-python/discussions/394
Quick release to add support for the new S3 Object Lambda event within Event Source Data Classes utility - Thanks to @michaelbrewer
Quick release to add support for the new S3 Object Lambda event within Event Source Data Classes utility - Thanks to @michaelbrewer
Event Source Data Classes utility provides self-documented schema for multiple Lambda Event Sources, and helper methods to easily parse, decode, and fetch common attributes, headers, and data in various forms.
tests/THIRD-PARTY-LICENSES to root (#352) by @michaelbrewer@BrockReece, @heitorlessa and @michaelbrewer
This release brings a number of minor but importance enhancements in Logger, Parameters, Data Classes, Idempotency.
This release brings a number of minor but importance enhancements in Logger, Parameters, Data Classes, Idempotency.
Also, this release wouldn't have been possible without @michaelbrewer relentless contribution - Thank you, Michael!!
You can now inject correlation IDs coming from any Event Source using JMESPath expressions, or by manually injecting a string with set_correltion_id.
Another enhancement that goes nicely with any Logging Analytics solution such as Amazon CloudWatch Logs Insights, Kibana, Datadog, Splunk, Loggly, etc is the ability to enumerate exceptions across all your functions - A new field exception_name will be added to your Logs when using logger.exception().
You can now have a self-documented schema for AppSync Lambda Resolvers whether you use Direct Lambda Resolver feature, or @function GraphQL Transformer with Amplify CLI. More importantly, scalar type utilities such as timestamps, timezone offsets, UUIDs, are also available!
Another enhancement is additional documentation for Cognito custom auth challenges.
A minor enhancement but important for sensitive parameters that cannot be cached. You can now use force_fetch=True parameter to always fetch the latest from your preferred parameter provider be that Parameter Store, Secrets Manager, AppConfig, DynamoDB, or your own.
We have also refreshed Parameters documentation using the new Getting started vs Advanced, including surfacing how you can control in-memory cache TTL for parameters retrieved.
Besides error handling improvements, thanks to @dunedan and @michaelbrewer (#318), you can now reuse a single DynamoDB table to store idempotency state. All new idempotency states stored in your DynamoDB table, as part of this release, will now contain your function name as a prefix for the hash key.
This is one step forward towards GA for Idempotency - The last missing feature before it's GA is allowing an exception callback mechanism so you can handle any exceptions to more easily return custom responses for event sources like API Gateway, AppSync, etc.
@heitorlessa and @michaelbrewer
This is our most special release this quarter, as we are happy to announce:
This is our most special release this quarter, as we are happy to announce:
Initially led by @igorlg RFC on Idempotency, and its implementation that started in mid December by @cakepietoast, with a gigantic effort by both @cakepietoast and @michaelbrewer on UX and correctness following Amazon Builder's Library and Stripe designs -- We now have it in Beta as part of this release.
Given the amount of serious work for this utility and its logic, we've decided it'd be best to launch as Beta as we'd like feedback on UX before we release as stable.
Key features at launch:
We truly hope you enjoy it :-)
@Sordie, @cakepietoast, @heitorlessa and @michaelbrewer
No code changes. Release to re-trigger layer publish.
No code changes. Release to re-trigger layer publish.
@cakepietoast
Releasing a new version primarily to update the published "extras" Lambda layer, as it was not being built correctly (see #290). Also including some f
Releasing a new version primarily to update the published "extras" Lambda layer, as it was not being built correctly (see #290). Also including some fixes for the recently updated documentation thanks to @michaelbrewer.
@cakepietoast, @heitorlessa and @michaelbrewer
This patch release fixes a) a bug in Tracer when multiple traces are collected and reach Lambda X-Ray agent payload limit, and b) a minor type issue i
This patch release fixes a) a bug in Tracer when multiple traces are collected and reach Lambda X-Ray agent payload limit, and b) a minor type issue in Parser that made mypy unable to validate models.
This release also marks our documentation system migration from Gatsby to MKdocs, including navigation improvements to address customers feedback on finding getting started vs advanced information.
@am29d, @heitorlessa and @nmoutschen
batch processing utility when dealing with multiple exceptions when processing SQS records
This quick release fixes:
@cakepietoast, @heitorlessa, @michaelbrewer and @nadobando
This release patches a model mismatch when using SNS -> SQS -> Lambda as opposed to SNS -> Lambda. The former changes three keys that are incompatible
This release patches a model mismatch when using SNS -> SQS -> Lambda as opposed to SNS -> Lambda. The former changes three keys that are incompatible with the model we derived from Lambda:
MessageAttributes key is not presentUnsubscribeUrl becomes UnsubscribeURLSigningCertUrl becomes SigningCertURLThis release also introduces a new envelope, SnsSqsEnvelope, to make this process seamless and easier when processing messages in Lambda that come from SNS -> SQS. This will extract the original SNS published payload, unmarshall it, and parse it using your model.
from aws_lambda_powertools.utilities.parser import BaseModel, envelopes, event_parser
class MySnsBusiness(BaseModel):
message: str
username: str
@event_parser(model=MySnsBusiness, envelope=envelopes.SnsSqsEnvelope)
def handle_sns_sqs_json_body(event: List[MySnsBusiness], _: LambdaContext):
assert len(event) == 1
assert event[0].message == "hello world"
assert event[0].username == "lessa"
@heitorlessa
This release adds a number of new features to Logger, Tracer, Validator, and Parameters, a new Lambda Layer with extra packages installed (e.g. parser
This release adds a number of new features to Logger, Tracer, Validator, and Parameters, a new Lambda Layer with extra packages installed (e.g. parser), and documentation fixes.
Detailed information about these features are at the bottom.
For the next release (1.11.0), we'll be focusing on a new Idempotency utility, import time performance improvements for those not using Tracer utility, and possibly a new Circuit Breaker utility.
@am29d, @heitorlessa, @michaelbrewer, @n2N8Z, @risenberg-cyberark and @suud
Logger now supports extra parameter in the standard logging when logging new messages. You can pass in any dictionary to this new parameter, and its keys and values will be available within the root of the structure - This is ephemeral and keys do not persist with its counterpart structure_logs(append=True, ...) method.
Excerpt
from aws_lambda_powertools import Logger
logger = Logger(service="payment")
fields = { "request_id": "1123" }
logger.info("Hello", extra=fields)
Log sample
{
"timestamp": "2021-01-12 14:08:12,357",
"level": "INFO",
"location": "collect.handler:1",
"service": "payment",
"sampling_rate": 0.0,
"request_id": "1123", // highlight-line
"message": "Collecting payment"
}
Pytest Live Log support will output logging records as they are emitted directly into the console with colours.
Since Logger drops duplicate log records as of 1.7.0, you can now explicitly override this protection when running tests locally to make use of Pytest Live Log:
POWERTOOLS_LOG_DEDUPLICATION_DISABLED="1" pytest -o log_cli=1
When using Tracer decorators, capture_method or capture_lambda_handler, we auto-capture its responses and exceptions, serialize them and inject as tracing metadata to ease troubleshooting.
There are times when serializing objects can cause side effects, for example reading S3 streaming objects if not read before. You can now override this behaviour either by parameter or via env var: POWERTOOLS_TRACER_CAPTURE_RESPONSE, POWERTOOLS_TRACER_CAPTURE_ERROR
You can now retrieve and cache configuration stored in AppConfig natively - Thanks to Ran from CyberArk.
from aws_lambda_powertools.utilities import parameters
def handler(event, context):
# Retrieve a single configuration, latest version
value: bytes = parameters.get_app_config(name="my_configuration", environment="my_env", application="my_app")
You can now use formats parameter to instruct Validator utility how to deal with any custom integer or string - Thanks to @n2N8Z
Custom format snippet in a JSON Schema
{
"lastModifiedTime": {
"format": "int64",
"type": "integer"
}
}
Excerpt ignoring int64 and a positive format instead of failing
from aws_lambda_powertools.utilities.validation import validate
event = {} # some event
schema_with_custom_format = {} # some JSON schema that defines a custom format
custom_format = {
"int64": True, # simply ignore it,
"positive": lambda x: False if x < 0 else True
}
validate(event=event, schema=schema_with_custom_format, formats=custom_format)
This patch release fixes a bug when multiple parent Loggers with the same name are configured multiple times, as per #249.
This patch release fixes a bug when multiple parent Loggers with the same name are configured multiple times, as per #249.
from aws_lambda_powertools import Logger
class Class1:
logger = Logger("class_1")
@staticmethod
def f_1():
Class1.logger.info("log from class_1")
class Class2:
logger = Logger("class_1")
@staticmethod
def f_2():
Class2.logger.info("log from class_2")
Class1.f_1()
Class2.f_2()
This release also adds brings staged changes initially planned for 1.10 such as minor improvements in Tracer documentation, brings equality checks to ease testing Event source data classes utility, and initial work for MyPy support (PEP 561).
capture_method (#244) by @cakepietoast@GroovyDan, @Nr18, @cakepietoast, @dependabot, @dependabot[bot], @gmcrocetti, @heitorlessa and @michaelbrewer
This release adds support for Kinesis, S3, CloudWatch Logs, Application Load Balancer, and SES models in Parser - Exclusively added by Ran (once again
This release adds support for Kinesis, S3, CloudWatch Logs, Application Load Balancer, and SES models in Parser - Exclusively added by Ran (once again) from CyberArk.
Docs clarified Logger keys that cannot be suppressed, a broken link, and the sidebar menu is now always expanded by default for improved UX.
@heitorlessa, @igorlg, @pankajagrawal16, @risenberg-cyberark, Pankaj Agrawal and Ran Isenberg
This release adds support for SNS model in Parser, API Gateway HTTP API IAM and Lambda Authorization support in Event source data classes, and the new
This release adds support for SNS model in Parser, API Gateway HTTP API IAM and Lambda Authorization support in Event source data classes, and the new EventBridge Replay field in both Parser and Event source data classes.
Docs now have a new FAQ section within Logger to answer a common question on boto3 debugging logs, least privilege IAM permission to deploy Lambda Layers, and fix a typo in SES data class example.
@Nr18, @am29d, @cakepietoast, @heitorlessa, @michaelbrewer, @risenberg-cyberark and Ran Isenberg, and @mwarkentin
This release adds support for Cognito Authentication Challenge Lambda Triggers for create, define and verify trigger sources. It also enhances get_hea
This release adds support for Cognito Authentication Challenge Lambda Triggers for create, define and verify trigger sources. It also enhances get_header_value method by optionally supporting case insensitive headers.
Credits: Thanks to @michaelbrewer from Gyft for both enhancements.
Parser is a new utility that provides parsing and deep data validation using Pydantic Models - It requires an optional dependency (Pydantic) to work.
It uses Pydantic Model classes, similar to dataclasses, to model the shape of your data, enforce type hints at runtime, serialize your models to JSON, JSON Schema, and with third party tools you can also auto-generate Model classes from JSON, YAML, OpenAPI, etc.
from aws_lambda_powertools.utilities.parser import event_parser, BaseModel, ValidationError
from aws_lambda_powertools.utilities.typing import LambdaContext
import json
class OrderItem(BaseModel):
id: int
quantity: int
description: str
class Order(BaseModel):
id: int
description: str
items: List[OrderItem] # nesting models are supported
optional_field: Optional[str] # this field may or may not be available when parsing
@event_parser(model=Order)
def handler(event: Order, context: LambdaContext):
assert event.id == 10876546789
assert event.description == "My order"
assert len(event.items) == 1
order_items = [items for item in event.items]
...
payload = {
"id": 10876546789,
"description": "My order",
"items": [
{
"id": 1015938732,
"quantity": 1,
"description": "item xpto"
}
]
}
handler(event=payload, context=LambdaContext())
# also works if event is a JSON string
handler(event=json.dumps(payload), context=LambdaContext())
With this release, we provide a few built-in models to start with such as Amazon EventBridge, Amazon DynamoDB, and Amazon SQS - You can extend them by inheriting and overriding their properties to plug-in your models.
from aws_lambda_powertools.utilities.parser import parse, BaseModel
from aws_lambda_powertools.utilities.parser.models import EventBridgeModel
from typing import List, Optional
class OrderItem(BaseModel):
id: int
quantity: int
description: str
class Order(BaseModel):
id: int
description: str
items: List[OrderItem]
# Override `detail` key of a custom event in EventBridge from str to Order
class OrderEventModel(EventBridgeModel):
detail: Order
payload = {...} # EventBridge event dict with Order inside detail as JSON
order = parse(model=OrderEventModel, event=payload) # parse input event into OrderEventModel
assert order.source == "OrderService"
assert order.detail.description == "My order"
assert order.detail_type == "OrderPurchased" # we rename it to snake_case since detail-type is an invalid name
# We can access our Order just as fine now
for order_item in order.detail.items:
...
# We can also serialize any property of our parsed model into JSON, JSON Schema, or as a Dict
order_dict = order.dict()
order_json = order.json()
order_json_schema_as_dict = order.schema()
order_json_schema_as_json = order.schema_json(indent=2)
Similar to Validator utility, it provides an envelope feature to parse known structures that wrap your event. It's useful when you you want to parse both the structure and your model but only return your actual data from the envelope.
Example using one of the built-in envelopes provided from day one:
from aws_lambda_powertools.utilities.parser import event_parser, parse, BaseModel, envelopes
from aws_lambda_powertools.utilities.typing import LambdaContext
class UserModel(BaseModel):
username: str
password1: str
password2: str
payload = {
"version": "0",
"id": "6a7e8feb-b491-4cf7-a9f1-bf3703467718",
"detail-type": "CustomerSignedUp",
"source": "CustomerService",
"account": "111122223333",
"time": "2020-10-22T18:43:48Z",
"region": "us-west-1",
"resources": ["some_additional_"],
"detail": {
"username": "universe",
"password1": "myp@ssword",
"password2": "repeat password"
}
}
ret = parse(model=UserModel, envelope=envelopes.EventBridgeModel, event=payload)
# Parsed model only contains our actual model, not the entire EventBridge + Payload parsed
assert ret.password1 == ret.password2
# Same behaviour but using our decorator
@event_parser(model=UserModel, envelope=envelopes.EventBridgeModel)
def handler(event: UserModel, context: LambdaContext):
assert event.password1 == event.password2
Credits: Thanks to @risenberg-cyberark from CyberArk for the idea, implementation, and guidance on how to best support Pydantic to provide both parsing and deep data validation. Also, special thanks to @koxudaxi for helping review with his extensive Pydantic experience.
@bmicklea, @dependabot, @dependabot[bot], @heitorlessa, @michaelbrewer, @risenberg-cyberark, @nr18, and @koxudaxi
Bug fixed for event source data classes utillity - accessing boolean atribute values in DynamoDB streams events (bool_value) now works correctly. Than
Bug fixed for event source data classes utillity - accessing boolean atribute values in DynamoDB streams events (bool_value) now works correctly. Thanks @whisller for the fix!
@cakepietoast and @whisller
New utility to easily describe event schema of popular event sources, including helper methods to access common objects (s3 bucket key) and data deser
<img width="1119" alt="image" src="https://user-images.githubusercontent.com/3340292/93908175-9f233980-fcfe-11ea-9db4-d0b9ce8e5d77.png">
New utility to easily describe event schema of popular event sources, including helper methods to access common objects (s3 bucket key) and data deserialization (records from Kinesis, CloudWatch Logs, etc).
Huge prop to @michaelbrewer for the contribution, and @cakepietoast for the comprehensive docs with examples.
New utility to quickly validate inbound events and responses using JSON Schema. It also supports unwrapping events using JMESPath expressions, so you can validate only the payload or key that interests you.
Oh, before I forget! This also includes custom JMESPath functions for de-serializing JSON Strings, base64, and ZIP compressed data before applying validation too 🥰
Metrics utility now support adding multiple values to the same metric - This was updated in CloudWatch EMF, and Powertools happily support that too ;) - Thanks to @dunedan for spotting that
We added a Testing your code section for Logger and Metrics for customers like @patrickwerz who had difficulties to do unit testing their code with Powertools - Pytest fixture and examples are now provided!
We also increased the content width to ease reading more elaborate sections, and gives us room to start tinkering with a Tutorial/Guide section in coming releases \ o /
@cakepietoast, @heitorlessa, @jamesls and @michaelbrewer
Add a new utility to handle partial failures when processing batches of SQS messages in Lambda. The default behaviour with Lambda - SQS is to return a
Add a new utility to handle partial failures when processing batches of SQS messages in Lambda. The default behaviour with Lambda - SQS is to return all messages to the queue when there is a failure during processing. This utility provides functionality to handle failures individually at the message level, and avoid re-processing messages. Thanks to @gmcrocetti who contributed this utility.
The xray_trace_id key is now added to log output when tracing is active. This enables the log correlation functionality in ServiceLens to work with applications using powertools.
You can now import a static type for the Lambda context object from this library. Thanks to @Nr18 for the implementation. <p align="center"> <img src="https://raw.githubusercontent.com/awslabs/aws-lambda-powertools-python/develop/docs/content/media/utilities_typing.png"/> </p>
You can now change the order of the fields output by the logger. Thanks to @michaelbrewer for the implementation.
Thanks to @michaelbrewer, the parameters utility can now automatically decide how to deserialize parameter values (json/base64) based on the key name.
Lots of improvements made to the documentation. Thanks to the community contributors: @Nr18 for adding a troubleshooting section, @michaelbrewer and @bls20AWS for several housekeeping contributions.
json_default in logs (#132) by @michaelbrewer@Nr18, @am29d, @bls20AWS, @cakepietoast, @gmcrocetti, @heitorlessa, @michaelbrewer and @pankajagrawal16
We now provide an official Lambda Layer via AWS Serverless Application Repository (SAR) App. SAR App follows semantic versioning, and it is synchroniz
We now provide an official Lambda Layer via AWS Serverless Application Repository (SAR) App. SAR App follows semantic versioning, and it is synchronized with what's published on PyPi.
| SAR App | ARN |
|---|---|
| aws-lambda-powertools-python-layer | arn:aws:serverlessrepo:eu-west-1:057560766410:applications/aws-lambda-powertools-python-layer |
A big thanks to @am29d for the implementation, and to Keith Rosario, a long standing contributor, and beta customer, who created the first Layers through his KLayers project - Lambda Layers for Python on GitHub before.
Thanks to @michaelbrewer, SSMProvider within Parameters utility now have decrypt and recursive parameters correctly defined to support autocompletion.
For customers returning sensitive information from their methods and Lambda handlers, Tracer decorators capture_method and capture_lambda_handler now support capture_response=False parameter to override this behaviour.
This release ensures Metrics utility creates a Cold Start metric with dedicated CloudWatch dimensions function_name and service to explicitly separate Application metrics from System metrics.
Previously, when capturing cold start metric via capture_cold_start_metric parameter, we would add ColdStart metric to an existing metric set along with function_name as a dimension. This caused the problem of Application metrics having data points in two separate metrics with the same name, since one of them would have an additional function_name dimension in the event of a cold start.
Content in Tracer and Logger have been reordered to match what customers are looking for. Tracer docs have less main sections to improve navigation, a new section named Patching Modules, and a note for customers capturing sensitive information they might not want Tracer to capture it.
@am29d, @heitorlessa and @michaelbrewer
Fixed issue with capture_method returning not working properly when the decorated function made us of context managers during its execution.
Fixed issue with capture_method returning not working properly when the decorated function made us of context managers during its execution.
@cakepietoast, @dependabot, @heitorlessa and @michaelbrewer
Add a new utility to fetch and cache parameter values from AWS Systems Manager Parameter Store, AWS Secrets Manager or Amazon DynamoDB. It also provid
<p align="center"> <img src="https://user-images.githubusercontent.com/15308855/90899393-201da700-e3c8-11ea-9d01-aeb835ad1267.png" alt="Sample code snippet of the parameters utility"/> </p>
Add a new utility to fetch and cache parameter values from AWS Systems Manager Parameter Store, AWS Secrets Manager or Amazon DynamoDB. It also provides a base class to create your parameter provider implementation.
Retrieve values from Systems Manager Parameter Store:
from aws_lambda_powertools.utilities import parameters
def handler(event, context):
# Retrieve a single parameter
value = parameters.get_parameter("/my/parameter")
# Retrieve multiple parameters from a path prefix recursively
# This returns a dict with the parameter name as key
values = parameters.get_parameters("/my/path/prefix")
for k, v in values.items():
print(f"{k}: {v}")
Retrieve secrets from AWS Secrets Managers:
from aws_lambda_powertools.utilities import parameters
def handler(event, context):
# Retrieve a single secret
value = parameters.get_secret("my-secret")
@nmoutschen
The Tracer capture_method decorator can now be used to capture execution of generator functions, including context managers.
The Tracer capture_method decorator can now be used to capture execution of generator functions, including context managers.
@cakepietoast
Fix logged messages being emitted twice, once structured and once unstructured - We now remove the root logger handler set by Lambda during initializa
Fix logged messages being emitted twice, once structured and once unstructured - We now remove the root logger handler set by Lambda during initialization.
@heitorlessa
Minor patch to improve Tracer documentation on reusability, and ensures PyCharm/VSCode Jedi Language Server can autocomplete log statements for Logger
Minor patch to improve Tracer documentation on reusability, and ensures PyCharm/VSCode Jedi Language Server can autocomplete log statements for Logger.
@heitorlessa @michaelbrewer
Fix Logger regression introduced in 1.1.0 when using int for setting log level, for example Logger(level=logging.INFO).
Fix Logger regression introduced in 1.1.0 when using int for setting log level, for example Logger(level=logging.INFO).
@heitorlessa, and big thanks to @zroger for spotting and raising this regression
This release add support for reusing Logger across multiple files in your code base via the new child parameter 🎉🎉🎉
This release add support for reusing Logger across multiple files in your code base via the new child parameter 🎉🎉🎉
Child Loggers will be named after the convention {service}.{filename} - It now follows the Python Logging inheritance mechanics. Here's a code excerpt to demonstrate how this feature looks like:
app.py - Your typical parent logger will be at your Lambda function handler
# POWERTOOLS_SERVICE_NAME: "payment"
import shared # Creates a child logger named "payment.shared"
from aws_lambda_powertools import Logger
logger = Logger()
def handler(event, context):
shared.inject_payment_id(event) # highlight-line
logger.structure_logs(append=True, order_id=event["order_id"]) # highlight-line
...
shared.py - You can use Logger(child=True) to explicit tell Logger this should be the child
# POWERTOOLS_SERVICE_NAME: "payment"
from aws_lambda_powertools import Logger
logger = Logger(child=True) # highlight-line
def inject_payment_id(event):
logger.structure_logs(append=True, payment_id=event["payment_id"])
@heitorlessa @alexanderluiscampino
This release allows the latest version of X-Ray SDK (2.6.0) to be installed, and no longer locks to the previous version (2.5.0).
This release allows the latest version of X-Ray SDK (2.6.0) to be installed, and no longer locks to the previous version (2.5.0).
@Nr18 and @heitorlessa
Quick bugfix to Logger causing additional keys to be dropped when added before logger.inject_lambda_context was called.
Quick bugfix to Logger causing additional keys to be dropped when added before logger.inject_lambda_context was called.
This only happened in two typical situations, and is now fixed with this release
from aws_lambda_powertools import Logger
logger = Logger()
logger.structured_logs(some_key="some_value") # some_key won't be available within the handler
@logger.inject_lambda_context
def handler(evt, ctx):
...
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
@lambda_handler_decorator(trace_execution=True)
def process_booking_handler(
handler: Callable, event: Dict, context: Any, logger: Logger = None
) -> Callable:
if logger is None:
logger = Logger()
# Add Step Functions specific keys from state into the Logger
# Add Lambda contextual info incl cold start into the Logger
_logger_inject_process_booking_sfn(logger=logger, event=event)
handler = logger.inject_lambda_context(handler)
return handler(event, context)
@heitorlessa
With this release, we move from release candidate to General Availability 🎉🎉🎉!
With this release, we move from release candidate to General Availability 🎉🎉🎉!
This means APIs for the core utilities Tracer, Logger, and Metrics as well as Middleware factory are now stable.
<!-- More information in the AWS OpenSource Blog: LINK -->
Quick links: 📜Documentation | 🐍PyPi | Feature request | Bug Report | Kitchen sink example
🤩 Key features 🤩
POWERTOOLS_TRACE_DISABLED="true"from aws_lambda_powertools import Tracer
tracer = Tracer()
@tracer.capture_method
def collect_payment(charge_id: str):
...
@tracer.capture_lambda_handler
def handler(event, context):
charge_id = event.get('charge_id')
payment = collect_payment(charge_id)
...
🤩 Key features 🤩
POWERTOOLS_LOGGER_LOG_EVENT="true" or explicitly via decorator paramPOWERTOOLS_LOGGER_SAMPLE_RATE=0.1, ranges from 0 to 1, where 0.1 is 10% and 1 is 100%from aws_lambda_powertools import Logger
logger = Logger(sample_rate=0.1) # sample 1% of debugging logs
@logger.inject_lambda_context # add contextual lambda runtime info to structured logging
def handler(event, context):
logger.info("Collecting payment")
# You can log entire objects too
logger.info({
"operation": "collect_payment",
"charge_id": event['charge_id']
})
# Exceptions will be structured under `exceptions` key
logger.exception(ValueError("Incorrect user id"))
🤩 Key features 🤩
from aws_lambda_powertools import Metrics
from aws_lambda_powertools.metrics import MetricUnit
@metrics.log_metrics(capture_cold_start_metric=True)
def lambda_handler(event, context):
...
check_out_cart() # Function to process the checkout
metrics.add_metric(name="CartCheckedOut", unit=MetricUnit.Count, value=1)
🤩 Key features 🤩
from aws_lambda_powertools.middleware_factory import lambda_handler_decorator
@lambda_handler_decorator(trace_execution=True)
def my_middleware(handler, event, context):
return handler(event, context)
@my_middleware
def lambda_handler(event, context):
...
We'd like to extend our gratitude to the following people who helped with contributions, feedbacks, and their opinions while we were in Beta:
@cakepietoast, @nmoutschen, @jfuss, @danilohgds, @pcolazurdo, @marcioemiranda, @bahrmichael, @keithrozario, @ranman
If you've been following the Beta, these are the new changes available in GA:
add_metadata method to add any metric metadata you'd like to ease finding metric related data via CloudWatch Logslog_metrics decorator to create a cold start metric to remove unnecessary boilerplate capture_cold_start_metric=Truefrom aws_lambda_powertools import Tracer, Metrics, LoggerBreaking and subtle changes from beta to GA:
add_namespace has been removed in favour of a new parameter in the constructor Metrics(namespace="ServerlessBooking")SchemaValidationError and are an opt-in behaviourlog_metrics has been removed in favour of Metricscapture_method supports both sync and async functionsFix a bug with Metrics causing an exception to be thrown when logging metrics if dimensions were not explicitly added. No longer throw exception when
Fix a bug with Metrics causing an exception to be thrown when logging metrics if dimensions were not explicitly added. No longer throw exception when no metrics are emitted while using the log_metrics decorator. Top level module imports now available for core utils, eg: from aws_lambda_powertools import Logger, Metrics, Tracer.
This is the last planned release before this library becomes GA.
@cakepietoast and @heitorlessa
Fix a bug with Metrics causing an exception to be thrown when logging metrics if dimensions were not explicitly added.
Fix a bug with Metrics causing an exception to be thrown when logging metrics if dimensions were not explicitly added.
@cakepietoast
This should be preferred to using the add_namespace method, which has been deprecated and will be removed in a future release.
This release primarily consists of changes to the Metrics core utility. Most notably:
Metrics constructor now accepts a service parameter (alternatively the POWERTOOLS_SERVICE_NAME env var), as with the Tracer and Logger interfaces. This will create a default dimension named "service", with the value provided. Note that if you're already using the env var, this new dimension will start being recorded after upgrading to this version.namespace parameter to the Metrics constructor, or by supplying the POWERTOOLS_METRICS_NAMESPACE env var. This should be preferred to using the add_namespace method, which has been deprecated and will be removed in a future release.capture_cold_start_metric parameter to the log_metrics decorator.make tests (#63) by @cakepietoast@cakepietoast, @danilohgds, @heitorlessa, @jfuss and @nmoutschen
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Nothing published for this version
Your coding agent can read these notes before it upgrades. Set up the MCP server →