Releases: aws-powertools/powertools-lambda-python
v1.0.1
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
- 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):
...
- 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:
v1.0.0
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
- Enable via
- 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%
- Enable via
- 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
- Serverless shopping cart microservice
- Serverless e-commerce platform
- Serverless Airline
- Airline project is still using the original version as a shared lib; we'll migrate to this version afterwards
🌟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:
- new method structure_logs(append=True, **kwargs) you can use to append additional keys you want available across all log statements
- High level imports
- You can now import core utilities more easily
from aws_lambda_powertools import Tracer, Metrics, Logger
- You can now import core utilities more easily
- 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 constructorMetrics(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
0.11.0
Changes
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.
🌟 Minor Changes
- fix: metrics default dimension creation (#74) by @cakepietoast
- chore(deps): bump graphql-playground-html from 1.6.19 to 1.6.25 in /docs (#72) by @dependabot
- feat: improve error handling for log_metrics decorator (#71) by @cakepietoast
- feat: add high level imports (#70) by @heitorlessa
📜 Documentation updates
- docs: fix major WCAG contrast issues (#73) by @heitorlessa
This release was made possible by the following contributors:
@cakepietoast and @heitorlessa
0.10.1
0.10.0
Changes
This release primarily consists of changes to the Metrics
core utility. Most notably:
- The
Metrics
constructor now accepts aservice
parameter (alternatively thePOWERTOOLS_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. - You can now specify the namespace by passing a
namespace
parameter to the Metrics constructor, or by supplying thePOWERTOOLS_METRICS_NAMESPACE
env var. This should be preferred to using theadd_namespace
method, which has been deprecated and will be removed in a future release. - To avoid repetition for the common task of recording metrics for Lambda cold starts, you can now achieve this by passing the
capture_cold_start_metric
parameter to thelog_metrics
decorator.
🌟New features and non-breaking changes
- feat: add capture_cold_start_metric for log_metrics (#67) by @heitorlessa
- improv: update metrics interface to resemble other core utils (#60) by @cakepietoast
- improv: Better namespace/dimension handling for Metrics (#62) by @cakepietoast
🌟 Minor Changes
- chore(deps): bump websocket-extensions from 0.1.3 to 0.1.4 in /docs (#66) by @dependabot
- chore: rename Makefile target docs-dev to docs-local (#65) by @cakepietoast
- feat: automate publishing to pypi (#58) by @heitorlessa
- feat: add pre-commit hooks (#64) by @heitorlessa
- improv: include example tests in
make tests
(#63) by @cakepietoast - feat: add codecov service (#59) by @heitorlessa
- feat: add security and complexity baseline #33 (#57) by @heitorlessa
- feat: add release drafter (#56) by @heitorlessa
- feat: add stale issues bot (#55) by @heitorlessa
- feat: enforce semantic PR titles (#54) by @heitorlessa
This release was made possible by the following contributors:
@cakepietoast, @danilohgds, @heitorlessa, @jfuss and @nmoutschen