Skip to content

Releases: aws-powertools/powertools-lambda-python

v1.3.1

22 Aug 09:06
Compare
Choose a tag to compare

Changes

Fixed issue with capture_method returning not working properly when the decorated function made us of context managers during its execution.

Patch

  • fix(capture_method): should yield inside with for generator method using a context manager (#124) by @michaelbrewer

Chore

  • chore(deps): bump elliptic from 6.5.2 to 6.5.3 in /docs (#120) by @dependabot
  • chore(deps): bump prismjs from 1.20.0 to 1.21.0 in /docs (#121) by @dependabot

This release was made possible by the following contributors:

@cakepietoast, @dependabot, @heitorlessa and @michaelbrewer

v1.3.0

21 Aug 14:06
41824b1
Compare
Choose a tag to compare

Changes

Sample code snippet of the parameters utility

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")

🌟 Minor Changes

This release was made possible by the following contributors:

@nmoutschen

v1.2.0

20 Aug 16:21
8621d4e
Compare
Choose a tag to compare

Changes

The Tracer capture_method decorator can now be used to capture execution of generator functions, including context managers.

  • chore: bump version to 1.2.0 (#119) by @cakepietoast

🌟 Minor Changes

  • feat: add support for tracing of generators using capture_method decorator (#113) by @cakepietoast

This release was made possible by the following contributors:

@cakepietoast

v1.1.3

18 Aug 20:28
81539a0
Compare
Choose a tag to compare

Changes

Fix logged messages being emitted twice, once structured and once unstructured - We now remove the root logger handler set by Lambda during initialization.

Patch

Chore

This release was made possible by the following contributors:

@heitorlessa

v1.1.2

16 Aug 17:39
6b66e0b
Compare
Choose a tag to compare

Changes

Minor patch to improve Tracer documentation on reusability, and ensures PyCharm/VSCode Jedi Language Server can autocomplete log statements for Logger.

📜 Documentation updates

This release was made possible by the following contributors:

@heitorlessa @michaelbrewer

v1.1.1

14 Aug 19:18
24a3bdf
Compare
Choose a tag to compare

Changes

Fix Logger regression introduced in 1.1.0 when using int for setting log level, for example Logger(level=logging.INFO).

Patch

Chore

This release was made possible by the following contributors:

@heitorlessa, and big thanks to @zroger for spotting and raising this regression

v1.1.0

14 Aug 16:10
d3feb63
Compare
Choose a tag to compare

Changes

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"])

🌟 Minor Changes

Chore

  • chore(deps): bump lodash from 4.17.15 to 4.17.19 in /docs (#93) by @dependabot

This release was made possible by the following contributors:

@heitorlessa @alexanderluiscampino

v1.0.2

16 Jul 14:23
6db7263
Compare
Choose a tag to compare

Changes

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).

Chore

This release was made possible by the following contributors:

@Nr18 and @heitorlessa

v1.0.1

05 Jul 19:46
0670e5e
Compare
Choose a tag to compare

Changes

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

  1. Additional keys added as part of global scope
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):
    ...
  1. Additional keys added as part of a custom middleware or a Layer that executed before
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)

🐛 Bug and hot fixes

  • fix: append structured logs when injecting lambda context (#86) by @heitorlessa

This release was made possible by the following contributors:

@heitorlessa

v1.0.0

18 Jun 15:48
2161823
Compare
Choose a tag to compare

Changes

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.

Quick links: 📜Documentation | 🐍PyPi | Feature request | Bug Report | Kitchen sink example

Tracer

🤩 Key features 🤩

  • Capture cold start as annotation, and responses as well as full exceptions as metadata
  • Run functions locally with SAM CLI without code change to disable tracing
  • Explicitly disable tracing via env var POWERTOOLS_TRACE_DISABLED="true"
  • Support tracing async methods
  • Auto patch supported modules, or a tuple of explicit modules supported by AWS X-Ray
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)
    ...

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)
    • Enable via POWERTOOLS_LOGGER_LOG_EVENT="true" or explicitly via decorator param
  • Log sampling enables DEBUG log level for a percentage of requests (disabled by default)
    • Enable via POWERTOOLS_LOGGER_SAMPLE_RATE=0.1, ranges from 0 to 1, where 0.1 is 10% and 1 is 100%
  • Append additional keys to structured log at any point in time
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"))

Metrics

🤩 Key features 🤩

  • Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob)
  • Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc)
  • Metrics are created asynchronously by CloudWatch service, no custom stacks needed
  • Context manager to create an one off metric with a different dimension
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)

Bring your own middleware

🤩 Key features 🤩

  • Run logic before, after, and handle exceptions
  • Trace each middleware when requested
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):
    ...

Sample projects using Powertools

🌟Special thank you

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


🧐What's New for Beta customers

If you've been following the Beta, these are the new changes available in GA:

  • Metrics:
    • add_metadata method to add any metric metadata you'd like to ease finding metric related data via CloudWatch Logs
    • new parameter to log_metrics decorator to create a cold start metric to remove unnecessary boilerplate capture_cold_start_metric=True
  • Logger:
  • High level imports
    • You can now import core utilities more easily from aws_lambda_powertools import Tracer, Metrics, Logger
  • Contributors:
    • new Contributing guide with instructions on how to setup dev env, and running documentation locally - both docs website as well as API reference website

Breaking and subtle changes from beta to GA:

  • Metrics:
    • add_namespace has been removed in favour of a new parameter in the constructor Metrics(namespace="ServerlessBooking")
    • Empty metrics no longer return SchemaValidationError and are an opt-in behaviour
  • Logger
    • log_metrics has been removed in favour of Metrics
  • Tracer
    • capture_method supports both sync and async functions
    • Escape hatch mechanism to use methods/functions from AWS X-Ray SDK