Skip to content

Releases: aws-powertools/powertools-lambda-dotnet

1.20

11 Feb 13:32
a358563
Compare
Choose a tag to compare

Summary

As part of our ongoing effort to make Powertools fully AOT compatible, we're thrilled to announce Idempotency support for native ahead-of-time (AOT) compilation.
Additionally, we've introduced custom key prefix support for Idempotency.
We've also addressed a bug in our Tracing utility that affected implementations using Top Level Statements.

Special thanks to @nCubed for bringing the Tracing issue to our attention.

Idempotency AOT

Docs

To enable Idempotency utility with AOT support, you need to configure the serialization context by adding WithJsonSerializationContext() to your Idempotency configuration.

In the example below, we use the default LambdaFunctionJsonSerializerContext. If you're using the Logging utility, you can alternatively use the PowertoolsSourceGeneratorSerializer.For more information visit our documentation

Idempotency.Configure(builder =>
builder.WithJsonSerializationContext(LambdaFunctionJsonSerializerContext.Default)));

Full example

public static class Function
{
    private static async Task Main()
    {
        var tableName = Environment.GetEnvironmentVariable("IDEMPOTENCY_TABLE_NAME");
        Idempotency.Configure(builder =>
            builder
                .WithJsonSerializationContext(LambdaFunctionJsonSerializerContext.Default)
                .WithOptions(optionsBuilder => optionsBuilder
                    .WithExpiration(TimeSpan.FromHours(1)))
                .UseDynamoDb(storeBuilder => storeBuilder
                    .WithTableName(tableName)
                ));

        Func<APIGatewayProxyRequest, ILambdaContext, APIGatewayProxyResponse> handler = FunctionHandler;
        await LambdaBootstrapBuilder.Create(handler,
                new SourceGeneratorLambdaJsonSerializer<LambdaFunctionJsonSerializerContext>())
            .Build()
            .RunAsync();
    }

    [Idempotent]
    public static APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest apigwProxyEvent,
        ILambdaContext context)
    {
        return new APIGatewayProxyResponse
            {
                Body = JsonSerializer.Serialize(response, typeof(Response), LambdaFunctionJsonSerializerContext.Default),
                StatusCode = 200,
                Headers = new Dictionary<string, string> { { "Content-Type", "application/json" } }
            };
    }
}

[JsonSerializable(typeof(APIGatewayProxyRequest))]
[JsonSerializable(typeof(APIGatewayProxyResponse))]
[JsonSerializable(typeof(Response))]
public partial class LambdaFunctionJsonSerializerContext : JsonSerializerContext
{
}

Idempotency custom key prefix

Docs

By default, the idempotency key follows the format [ClassName].[DecoratedMethodName]#[PayloadHash].
With this release, You can now customize this prefix by setting the KeyPrefix property in the Idempotency decorator, making code refactoring more manageable without impacting existing idempotency items.

public class Function
{
    public Function()
    {
        var tableName = Environment.GetEnvironmentVariable("IDEMPOTENCY_TABLE_NAME");
        Idempotency.Configure(builder => builder.UseDynamoDb(tableName));
    }

    [Idempotent(KeyPrefix = "MyCustomKeyPrefix")]
    public APIGatewayProxyResponse FunctionHandler(APIGatewayProxyRequest apigwProxyEvent, ILambdaContext context)
    {
        return TestHelper.TestMethod(apigwProxyEvent);
    }
}

Tracing segment name sanitization

Tracing segment name docs and X-Ray docs

Previously, string names automatically generated from Tracing-decorated methods weren't sanitized, which could silently fail and prevent traces from appearing in X-Ray due to invalid characters. While this could be addressed by specifying a custom segment name in the Tracing decorator, the custom string itself might still contain invalid characters.
To resolve this, we've implemented two improvements:

  1. Added documentation describing valid characters for segment names
  2. Implemented automatic string sanitization for both auto-generated and custom segment names

These changes ensure that no traces are dropped due to invalid characters in segment names, maintaining reliable trace data collection in X-Ray.

  /// <summary>
  ///     Set custom segment name for the operation.
  ///     The default is '## {MethodName}'.
  ///
  ///     The logical name of the service that handled the request, up to 200 characters. 
  ///     Names can contain Unicode letters, numbers, and whitespace, and the following symbols: \_, ., :, /, %, &amp;, #, =, +, \\, -, @
  /// </summary>
  public string SegmentName { get; set; } = "";
using System.Text.RegularExpressions;

public static string SanitizeString(string input)
{
    // Define a regular expression pattern to match allowed characters
    string pattern = @"[^a-zA-Z0-9\s_\.\:/%&#=+\-@]";
    
    // Replace any character that does not match the pattern with an empty string
    return Regex.Replace(input, pattern, string.Empty);
}

Changes

📜 Documentation updates

  • chore: Roadmap 2025 update (#757) by @hjgraca
  • chore: Update docs Idempotency custom prefix (#758) by @hjgraca
  • chore: Sync main with develop for release 1.20 (#752) by @hjgraca
  • chore(deps): bump squidfunk/mkdocs-material from 7e841df to c62453b in /docs (#748) by @dependabot[bot]
  • chore: Add privacy plugin to mkdocs (#747) by @hjgraca
  • chore: AOT support for Idempotency (#653) by @hjgraca
  • chore(deps): bump squidfunk/mkdocs-material from 471695f to 7e841df in /docs (#744) by @dependabot[bot]
  • chore(deps): bump squidfunk/mkdocs-material from 41942f7 to 471695f in /docs (#739) by @dependabot[bot]

🔧 Maintenance

  • chore(deps): bump aws-actions/configure-aws-credentials from 4.0.3 to 4.1.0 (#755) by @dependabot[bot]
  • chore(deps): bump actions/upload-artifact from 4.5.0 to 4.6.0 (#754) by @dependabot[bot]
  • chore(deps): bump github/codeql-action from 3.27.9 to 3.28.9 (#753) by @dependabot[bot]
  • chore: Roadmap 2025 update (#757) by @hjgraca
  • chore: Update docs Idempotency custom prefix (#758) by @hjgraca
  • chore: Sync main with develop for release 1.20 (#752) by @hjgraca
  • chore: update versions for release 1.20 (#743) by @hjgraca
  • chore(deps): bump pygments from 2.13.0 to 2.15.0 (#355) by @dependabot[bot]
  • chore(deps): bump github/codeql-action from 3.28.8 to 3.28.9 (#751) by @dependabot[bot]
  • chore(deps): bump zgosalvez/github-actions-ensure-sha-pinned-actions from 3.0.20 to 3.0.21 (#750) by @dependabot[bot]
  • chore(deps): bump squidfunk/mkdocs-material from 7e841df to c62453b in /docs (#748) by @dependabot[bot]
  • chore: Add support for custom key prefixes in Idempotency utility (#745) by @hjgraca
  • chore: Add privacy plugin to mkdocs (#747) by @hjgraca
  • chore: AOT support for Idempotency (#653) by @hjgraca
  • chore(deps): bump squidfunk/mkdocs-material from 471695f to 7e841df in /docs (#744) by @dependabot[bot]
  • chore: idempotency e2e tests (#738) by @hjgraca
  • chore: Tracing Sanitize SegmentName to avoid unsupported characters (#741) by @hjgraca
  • chore(deps): bump squidfunk/mkdocs-material from 41942f7 to 471695f in /docs (#739) by @dependabot[bot]
  • chore(deps): bump actions/setup-dotnet from 4.2.0 to 4.3.0 (#736) by @dependabot[bot]
  • chore(deps): bump github/codeql-action from 3.28.6 to 3.28.8 (#737) by @dependabot[bot]
  • chore: Update api docs build to dotnet 8 (#734) by @hjgraca
  • chore(deps): bump github/codeql-action from 3.28.5 to 3.28.6 (#727) by @dependabot[bot]
  • chore(deps): bump aws-actions/configure-aws-credentials from 4.0.2 to 4.0.3 (#725) by @dependabot[bot]
  • chore(deps): bump actions/setup-python from 5.3.0 to 5.4.0 (#726) by @dependabot[bot]
  • chore: Update test projects to no be packable (#731) by @hjgraca

This release was made possible by the following contributors:

@dependabot[bot], @hjgraca and dependabot[bot]

1.19

28 Jan 10:56
ff2403e
Compare
Choose a tag to compare

Summary

This release addresses a regression introduced in version 1.6.0 of the Logging utility. The bug prevented the Service property from being updated after the initial Logger instantiation, even when set through the Handler.

Logging v1.6.4

Special thanks to @nCubed for reporting this issue (#702) and huge thanks to our first-time contributor @ankitdhaka07!
We greatly appreciate your contributions!

Service Property Priority Resolution

Docs

The root level Service property now correctly follows this priority order:

  1. LoggingAttribute.Service (property value set in the decorator)
  2. POWERTOOLS_SERVICE_NAME (environment variable)

Previously, if the Logger was initialized before the handler execution and the POWERTOOLS_SERVICE_NAME environment variable was set, the service value would remain unchanged even when the handler decorator specified a different value.

image

This release ensures that the Service property is correctly updated according to the priority resolution order, allowing the decorator's value to take precedence when specified.

Changes

📜 Documentation updates

🐛 Bug and hot fixes

  • fix: pin FluentAssertions NuGet version to prevent license issues (#698) by @ankitdhaka07

🔧 Maintenance

This release was made possible by the following contributors:

@ankitdhaka07, @dependabot[bot], @hjgraca, @leandrodamascena, dependabot[bot]

1.18

14 Jan 16:30
69660a5
Compare
Choose a tag to compare

Summary

In this release we added support for structured logging of inner exceptions in the Logging utility.
This feature is available starting on version 1.6.3 of Logging

⭐ Thank you @joaope for the feature request

Include inner exceptions in error messages

Before

{
    "exception": {
        "type": "System.InvalidOperationException",
        "message": "Parent exception message"
    }
}

After

{
    "exception": {
        "type": "System.InvalidOperationException", 
        "message": "Parent exception message",
        "inner_exception": {
            "type": "System.ArgumentNullException",
            "message": "Very important inner exception message"
        }
    }
}

Usage Example

Logger.LogError(
    new InvalidOperationException("Parent message", 
        new ArgumentNullException("input", "Inner message")),
    "Operation failed with {arg}", 
    12345
);

Changes

🔧 Maintenance

This release was made possible by the following contributors:

@hjgraca

1.17

12 Nov 11:39
46d5b86
Compare
Choose a tag to compare

Summary

AWS Lambda Powertools for .NET - Tracing 1.6.0

🐛 Bug Fixes

  • Fixed a NotSupportedException that occurred when using the Tracing utility in native AOT mode with async methods that don't return a value (Task)
  • Special thanks to @matthewwilson for reporting this issue! ⭐

📦 Package Information

  • Version: 1.6.0
  • Package: AWS.Lambda.Powertools.Tracing

Native AOT Support

Important

To allow Tracing to work with your types in native AOT mode, you must add **WithTracing()** to your source generator configuration. This works with either:

  • The default SourceGeneratorLambdaJsonSerializer
  • The Powertools Logging utility source generator PowertoolsSourceGeneratorSerializer

Tip

For detailed implementation guidelines, please refer to our AOT support documentation.

Implementation Examples

Using Default Source Generator

using AWS.Lambda.Powertools.Tracing;
using AWS.Lambda.Powertools.Tracing.Serializers;

private static async Task Main()
{
    Func<string, ILambdaContext, string> handler = FunctionHandler;
    await LambdaBootstrapBuilder.Create(handler, new SourceGeneratorLambdaJsonSerializer<LambdaFunctionJsonSerializerContext>()
    .WithTracing())
        .Build()
        .RunAsync();
}

Using Powertools Logging Source Generator

using AWS.Lambda.Powertools.Logging;
using AWS.Lambda.Powertools.Logging.Serializers;
using AWS.Lambda.Powertools.Tracing;
using AWS.Lambda.Powertools.Tracing.Serializers;

private static async Task Main()
{
    Func<string, ILambdaContext, string> handler = FunctionHandler;
    await LambdaBootstrapBuilder.Create(handler, 
        new PowertoolsSourceGeneratorSerializer<LambdaFunctionJsonSerializerContext>()
        .WithTracing())
            .Build()
            .RunAsync();
}

Changes

📜 Documentation updates

  • chore: Tracing Fix async Task Handler exception (#675) by @hjgraca

🔧 Maintenance

  • chore: Tracing Fix async Task Handler exception (#675) by @hjgraca

This release was made possible by the following contributors:

@hjgraca

1.16

22 Oct 09:33
81acc01
Compare
Choose a tag to compare

Summary

In this release we have fixed an issue with Enum serialization.
The fix addresses an edge case where enum values weren't properly serialized when using C# top-level statements (file-scoped namespaces) in Lambda functions. This ensures proper logging functionality regardless of your chosen code structure.

Logging version: 1.6.2

  • Fixed Enum serialization when using top-level statements in Lambda functions
  • Resolves incorrect enum value handling in structured logging
  • Ensures consistent logging behavior across different Lambda function styles

Special thanks to @nCubed for:

  • Reporting the issue
  • Providing detailed reproduction steps
  • Assisting with troubleshooting and validation

Changes

🐞 Fixes

This release was made possible by the following contributors:

@nCubed and @hjgraca

1.15

08 Oct 14:46
a979415
Compare
Choose a tag to compare

Summary

In this release we are excited to announce a new feature in the Batch processing utility and bug fixes in Tracing and Logging.

New Feature: ThrowOnFullBatchFailure

This release introduces a new batch processing option: ThrowOnFullBatchFailure. This option controls whether a BatchProcessingException should be raised on full batch failure.

⭐ Special thanks to @lachriz-aws for developing this feature.

Batch processing 1.2.0

The ThrowOnFullBatchFailure option can be set via:

  • A new ThrowOnFullBatchFailure field on the BatchProcessor attribute (applied in non-utility mode)
  • A new environment variable POWERTOOLS_BATCH_THROW_ON_FULL_BATCH_FAILURE (applied in non-utility mode)
  • Directly on the AWS.Lambda.Powertools.BatchProcessing.ProcessingOptions in utility mode

ThrowOnFullBatchFailure attribute usage
ThrowOnFullBatchFailure ProcessingOptions usage

Behavior

When processing of an entire batch fails:

  • If ThrowOnFullBatchFailure is set to false, the Batch Processor will not throw an exception after batch processing has completed. Instead, it will return the IDs of the failed items (all batch items in this case) and exit gracefully.
  • If a Lambda function is configured with ErrorHandlingPolicy = StopOnFirstBatchItemFailure and the first batch item fails processing, the entire batch is marked as failed (as per the documentation). In this case, if ThrowOnFullBatchFailure is set to false, the behavior described above will apply.

Note: The new ThrowOnFullBatchFailure option is compatible with the existing error handling policies.

Bug Fixes

Tracing Update

  • Updated to version 1.5.2
  • Fixed issue #659: Lambda timeout when calling async methods from a Tracing decorated method in version 1.5.1
  • Thanks to @JonathanVerberne for reporting this issue

Logging Update

  • Updated to version 1.6.1
  • Fixed issue #656: Serialization exceptions when running .NET 8 non-AOT Lambda functions
  • Thanks to @nCubed for reporting this issue

Changes

🌟New features and non-breaking changes

  • feat: New batch processing option: 'ThrowOnFullBatchFailure' (#646) by @lachriz-aws

📜 Documentation updates

  • feat: New batch processing option: 'ThrowOnFullBatchFailure' (#646) by @lachriz-aws

🔧 Bug Fixes

  • chore: Fix Lambda timeout with Tracing 1.5.1 using async methods (#660) by @hjgraca
  • chore: Remove TypeInfoResolver from non AOT mode. (#657) by @hjgraca
  • chore: update logging nuget package version v 1.6.0 (#652) by @hjgraca

This release was made possible by the following contributors:

@hjgraca and @lachriz-aws

1.14

24 Sep 11:33
434add6
Compare
Choose a tag to compare

Summary

We are excited to announce GA support for Ahead-of-Time (AOT) compilation for Logging version 1.6.0. You can now use Logging in your AOT-published .NET AWS Lambda functions without any AOT warnings.

With this release, all Powertools core utilities (Logging, Metrics, and Tracing) have AOT support.
You can follow progress on AOT support here.

Check our docs for AOT support details.

Tip

New to AOT?
Check out this tutorial in the AWS Lambda documentation.

Serialization

Important

Starting from version 1.6.0, it is required to update the Amazon.Lambda.Serialization.SystemTextJson NuGet package to version 2.4.3 in your csproj.

Note

Using LogEvent, Custom Log Formatter features, or serialize your own types when Logging events? You need to make changes in your Lambda Main method.
Replace SourceGeneratorLambdaJsonSerializer with PowertoolsSourceGeneratorSerializer.
When you update your code to use PowertoolsSourceGeneratorSerializer<MyCustomJsonSerializerContext>, we combine your JsonSerializerContext with Powertools' JsonSerializerContext. This allows Powertools to serialize your types and Lambda events.

image

Custom Log Formatter

Important

To use a custom log formatter with AOT, pass an instance of ILogFormatter to PowertoolsSourceGeneratorSerializer instead of using the static Logger.UseFormatter in the Function constructor as you do in non-AOT Lambdas.

image

Anonymous Types

While we support anonymous type serialization by converting to a Dictionary<string, object>, this is not a best practice and is not recommended when using native AOT.
We recommend using concrete classes and adding them to your JsonSerializerContext.

Changes

🚀 Features

📜 Documentation updates

🔧 Maintenance

  • chore: Update examples for release 1..13 (#645) by @hjgraca
  • chore: Refactor and simplify Common dependency. (#643) by @hjgraca
  • chore: Change the way we reference Common and JMESPath (internal references). (#641) by @hjgraca

This release was made possible by the following contributors:

@hjgraca

1.13

29 Aug 13:18
4029b08
Compare
Choose a tag to compare

Summary

In this release we fix a bug when using Tracing utility with BatchProcessing utility.
The issue occurred due a max depth serialization error when using Batch RecordHanderResult and Tracing decorator

Special thanks to @CoreySchnedl for reporting the issue

New in this release

We also improved the user experience in case any other serialization error occurs.
Now when exceptions occour inside X-Ray SDK EndSubsegment we catch those and create a new SubSegment in CloudWatch Traces, this prevents the app from crashing and displays in the UI that an error occurred.

image

📜 Documentation updates

🔧 Maintenance

  • chore: fix docs missing closing tag (#639) by @hjgraca
  • chore: Update versions for release 1.13 (#638) by @hjgraca
  • chore(docs): Updating tracing docs for typo (#622) by @hjgraca
  • chore(docs): load self hosted mermaid.js (#635) by @dreamorosi
  • chore: Fix Max depth serialization bug when using Batch RecordHanderResult and Tracing (#632) by @hjgraca
  • chore: Add Pushpay as a public reference (#633) by @hjgraca
  • chore: add caylent as a public reference (#625) by @hjgraca
  • chore: Update examples Tracing to version 1.5.0 related to release 1.12 (#623) by @hjgraca
  • chore: Change the way we reference Common and JMESPath (internal references). (#641) by @hjgraca
  • Bug: Issue with JMESPath dependency in Idempotency on some scenarios (#626) by @hjgraca
  • chore: Refactor and simplify Common dependency. (#643) by @hjgraca

This release was made possible by the following contributors:

@dreamorosi, @hjgraca and @leandrodamascena

1.12

25 Jul 13:40
aef100c
Compare
Choose a tag to compare

Summary

We are excited to announce GA support for Ahead-of-time (AOT) compilation for Tracing version 1.5.0. This means, you can now use Tracing in your AOT published .NET AWS Lambda functions without any AOT warnings.

You can follow progress on AOT support here.

Tip

New to AOT?
Checkout this tutorial in the AWS Lambda documentation.

Caveats

Docs

By default, Tracing uses AWS X-Ray SDK. That means, you must include TrimmerRootAssemblies as part of your .csproj file:

image

Changes

🚀 Features

📜 Documentation updates

🔧 Maintenance

This release was made possible by the following contributors:

@hjgraca

1.11.1

12 Jul 09:47
a1ae03a
Compare
Choose a tag to compare

Summary

This release we fix a regression caused by release 1.7.0.
This bug caused the Metrics to not capture the Lambda context when in an AOT published Lambda.

Version 1.7.0 was removed from NuGet

Changes

{
    "_aws": {
        "Timestamp": 1720714102216,
        "CloudWatchMetrics": [
            {
                "Namespace": "ns",
                "Metrics": [
                    {
                        "Name": "ColdStart",
                        "Unit": "Count"
                    }
                ],
                "Dimensions": [
                    [
                        "FunctionName"
                    ],
                    [
                        "Service"
                    ]
                ]
            }
        ]
    },
    "FunctionName": null, <--- should not be null
    "Service": "svc",
    "ColdStart": 1
}

🔧 Maintenance

  • chore: Fix metrics lambda context and storage resolution (#613) by @hjgraca

This release was made possible by the following contributors:

@hjgraca