### Getting Started with Lambda Metadata Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/metadata.md Demonstrates basic usage of the Lambda Metadata utility to retrieve the Availability Zone ID. Ensure the package is installed. ```csharp using AWS.Lambda.Powertools.Metadata.Exceptions; using AWS.Lambda.Powertools.Metadata; public class Function { public void FunctionHandler(ILambdaContext context) { try { var availabilityZoneId = LambdaMetadata.AvailabilityZoneId; // Use availabilityZoneId } catch (MetadataNotFoundException) { // Handle cases where metadata is not available } } } ``` -------------------------------- ### Select Powertools Hello World Template Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/index.md From the AWS Quick Start Templates, select option 3 to initialize a project with the 'Hello World Example with Powertools for AWS Lambda'. ```bash Choose an AWS Quick Start application template 1 - Hello World Example 2 - Data processing 3 - Hello World Example with Powertools for AWS Lambda 4 - Multi-step workflow 5 - Scheduled task 6 - Standalone function 7 - Serverless API Template: 3 ``` -------------------------------- ### Complete Example with Dependency Injection Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/event_handler/bedrock_agent_function.md A comprehensive example demonstrating the integration of dependency injection with Bedrock Agent functions in .NET. This snippet shows a fully functional setup including tool registration and handler implementation. ```csharp using AWS.Lambda.Core; using AWS.Lambda.Powertools.Bedrock.Tools; using AWS.Lambda.Powertools.DependencyInjection; namespace BedrockAgentFunction { public class BedrockAgentFunction : ILambdaEntryPoint { private readonly IToolService _toolService; public BedrockAgentFunction() : this(new LambdaDiContainer()) { } public BedrockAgentFunction(ILambdaDiContainer container) { // Register tools from MyTools class container.RegisterToolsFrom(); _toolService = container.GetRequiredService(); } [LambdaFunction] public async Task FunctionHandler(BedrockEvent bedrockEvent, ILambdaContext context) { var response = await _toolService.InvokeAsync(bedrockEvent, context); return response; } } public class MyTools { [Tool(Description = "Get the current weather for a location.")] public string GetWeather(string location) { return $"The weather in {location} is sunny."; } [Tool(Description = "Calculate the sum of two numbers.")] public int AddNumbers(int a, int b) { return a + b; } } } ``` -------------------------------- ### Build and Deploy Application with AWS SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/BatchProcessing/README.md Use these commands to build and deploy the sample application. The `--guided` flag prompts for configuration details. Ensure you have AWS SAM CLI, Docker, and .NET 8.0 installed. ```bash sam build sam deploy --guided ``` -------------------------------- ### Initialize .NET 8 Project with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/index.md Use this command to start a new .NET 8 project pre-configured with AWS Powertools for Lambda. Ensure you have SAM CLI, .NET 8, and Docker installed. ```bash sam init -r dotnet8 ``` -------------------------------- ### Complete Example with Dependency Injection Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.EventHandler.Resolvers.BedrockAgentFunction/Readme.md This snippet shows a complete Lambda function setup using BedrockAgentFunctionResolver and dependency injection. It includes service interfaces, implementations, and the registration of tool functions that utilize these injected services. ```csharp using Amazon.BedrockAgent.Model; using Amazon.Lambda.Core; using AWS.Lambda.Powertools.EventHandler; using Microsoft.Extensions.DependencyInjection; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.SystemTextJson.DefaultLambdaJsonSerializer))] namespace MyBedrockAgent { // Service interfaces and implementations public interface IWeatherService { string GetForecast(string city); } public class WeatherService : IWeatherService { public string GetForecast(string city) => $"Weather forecast for {city}: Sunny, 75°F"; } public interface IProductService { string CheckInventory(string productId); } public class ProductService : IProductService { public string CheckInventory(string productId) => $"Product {productId} has 25 units in stock"; } // Main Lambda function public class Function { private readonly BedrockAgentFunctionResolver _resolver; public Function() { // Set up dependency injection var services = new ServiceCollection(); services.AddSingleton(); services.AddSingleton(); services.AddBedrockResolver(); // Extension method to register the resolver var serviceProvider = services.BuildServiceProvider(); _resolver = serviceProvider.GetRequiredService(); // Register tool functions that use injected services _resolver .Tool("GetWeatherForecast", "Gets weather forecast for a city", (string city, IWeatherService weatherService, ILambdaContext ctx) => { ctx.Logger.LogLine($"Weather request for {city}"); return weatherService.GetForecast(city); }) .Tool("CheckInventory", "Checks inventory for a product", (string productId, IProductService productService) => productService.CheckInventory(productId)) .Tool("GetServerTime", "Returns the current server time", () => DateTime.Now.ToString("F")); } public ActionGroupInvocationOutput FunctionHandler( ActionGroupInvocationInput input, ILambdaContext context) { return _resolver.Resolve(input, context); } } } ``` -------------------------------- ### Install Kafka Protobuf Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/kafka.md Install the Powertools for AWS Lambda package for working with Protocol Buffers. ```bash dotnet add package AWS.Lambda.Powertools.Kafka.Protobuf ``` -------------------------------- ### Executable Assembly Example Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/event_handler/bedrock_agent_function.md Example demonstrating how to set up the BedrockAgentFunctionResolver for an executable assembly. ```csharp using System; using System.Threading.Tasks; using AWS.Lambda.Powertools.Bedrock.Agent; namespace BedrockAgentSample { public class Function { private readonly BedrockAgentFunctionResolver _resolver = new BedrockAgentFunctionResolver(); public Function() { _resolver.RegisterTool(new GetWeatherTool()); } public async Task FunctionHandler(string request, ILambdaContext context) { return await _resolver.InvokeAsync(request, context); } } public class GetWeatherTool { [ToolFunction("GetWeather", Description = "Get the current weather for a city.")] public WeatherReport GetWeather([Parameter(Name = "city", Description = "The city to get the weather for.")] string city) { // In a real application, you would call an external API here return new WeatherReport { City = city, Temperature = "25°C", Condition = "Sunny" }; } } public class WeatherReport { public string City { get; set; } public string Temperature { get; set; } public string Condition { get; set; } } } ``` -------------------------------- ### Install Tracing NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/tracing.md Install the AWS.Lambda.Powertools.Tracing NuGet package using the .NET CLI. ```bash dotnet nuget add AWS.Lambda.Powertools.Tracing ``` -------------------------------- ### Example IServiceProvider Implementation Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/batch-processing.md Provides an example implementation of `IServiceProvider` to demonstrate how dependency injection can be set up for batch processing utilities. ```csharp public class MyServiceProvider : IServiceProvider { private readonly IServiceCollection _services; private readonly ServiceProvider _innerProvider; public MyServiceProvider(IServiceCollection services) { _services = services; _innerProvider = services.BuildServiceProvider(); } public object GetService(Type serviceType) { if (serviceType == typeof(SqsBatchProcessor)) { return new SqsBatchProcessor(new BatchProcessorConfig { ProcessingOptions = new ProcessingOptions { ThrowOnFullBatchFailure = false } }); } return _innerProvider.GetService(serviceType); } } ``` -------------------------------- ### AOT Support: Before PowertoolsSourceGeneratorSerializer Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md Example demonstrating the setup before migrating to PowertoolsSourceGeneratorSerializer for AOT support in logging. ```csharp var lambdaLogger = new SourceGeneratorLambdaJsonSerializer(); Logger.Setup(lambdaLogger); ``` -------------------------------- ### Install Avro Tools Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/tests/AWS.Lambda.Powertools.Kafka.Tests/Readme.md Installs the Apache Avro Tools globally. This is a prerequisite for generating Avro classes. ```bash dotnet tool install --global Apache.Avro.Tools ``` -------------------------------- ### Verify .NET SDK Installation Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/simple.md Run this command to check your installed .NET SDK version. Ensure it is 8.0 or later. ```bash dotnet --version ``` -------------------------------- ### Start Local API with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Parameters/README.md Emulate your application's API locally by running 'sam local start-api'. This command starts the API on port 3000. ```bash Parameters$ sam local start-api ``` ```bash Parameters$ curl http://localhost:3000/hello ``` -------------------------------- ### Start Local API with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Tracing/README.md Emulate your application's API locally by running `sam local start-api`. This command starts a local server, typically on port 3000, allowing you to test API endpoints. ```bash Tracing$ sam local start-api Tracing$ curl http://localhost:3000/ ``` -------------------------------- ### Install AWS Lambda Powertools EventHandler Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/event_handler/appsync_events.md Install the AWS Lambda Powertools EventHandler package using the .NET CLI. ```bash dotnet add package AWS.Lambda.Powertools.EventHandler ``` -------------------------------- ### Install Bedrock Agent Function Resolver Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/event_handler/bedrock_agent_function.md Install the AWS.Lambda.Powertools.EventHandler.Resolvers.BedrockAgentFunction package using the .NET CLI. ```bash dotnet add package AWS.Lambda.Powertools.EventHandler.Resolvers.BedrockAgentFunction ``` -------------------------------- ### Configure default dimensions with cold start Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md Use the Builder or Configure patterns in the constructor to set default dimensions including cold start metrics. ```csharp var metrics = new MetricsBuilder() .Configuration(config => { config.DefaultDimensions = new Dictionary { { "Environment", "Production" } }; config.CaptureColdStart = true; }) .Build(); ``` ```csharp var metrics = new Metrics(); metrics.Configure(config => { config.DefaultDimensions = new Dictionary { { "Environment", "Production" } }; config.CaptureColdStart = true; }); ``` -------------------------------- ### Start Lambda Runtime Client Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Event Handler/BedrockAgentFunction/src/Readme.md Add this code to the end of your top-level statements file to start the Lambda runtime client. It requires the Amazon.Lambda.RuntimeSupport NuGet package. ```csharp await LambdaBootstrapBuilder.Create(handler, new DefaultLambdaJsonSerializer()) .Build() .RunAsync(); ``` -------------------------------- ### Install Idempotency Package with .NET CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.Idempotency/README.md Install the Idempotency package using the .NET Core command-line interface. ```bash dotnet add package Amazon.Lambda.PowerTools.Idempotency ``` -------------------------------- ### Install Logging NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md Use the dotnet CLI to add the AWS.Lambda.Powertools.Logging NuGet package to your project. ```bash dotnet add package AWS.Lambda.Powertools.Logging ``` -------------------------------- ### Install Apache Avro Tools Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/kafka.md Installs the Apache Avro Tools globally for generating C# classes from Avro schemas. ```bash dotnet tool install --global Apache.Avro.Tools ``` -------------------------------- ### Install Kafka Avro Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/kafka.md Install the Powertools for AWS Lambda package for processing Avro messages. ```bash dotnet add package AWS.Lambda.Powertools.Kafka.Avro ``` -------------------------------- ### Install AWS.Lambda.Powertools.Metadata NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/metadata.md Add the AWS.Lambda.Powertools.Metadata package to your .NET project using the dotnet CLI. ```bash dotnet add package AWS.Lambda.Powertools.Metadata ``` -------------------------------- ### Install Kafka Json Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/kafka.md Install the Powertools for AWS Lambda package for working with Json messages. ```bash dotnet add package AWS.Lambda.Powertools.Kafka.Json ``` -------------------------------- ### Install AWS Lambda Tools for .NET CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/simple.md Install the AWS Lambda .NET CLI tools globally. This enables the use of `dotnet lambda` commands. ```bash dotnet tool install -g Amazon.Lambda.Tools dotnet new install Amazon.Lambda.Templates ``` -------------------------------- ### Full Idempotency Configuration Example with AOT Support Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/idempotency.md This example demonstrates a full Idempotency configuration including AOT support by specifying the JSON serialization context. ```csharp var builder = WebApplication.CreateBuilder(args); builder.Services.AddTransient(); builder.Services.AddIdempotency(options => { options.WithJsonSerializationContext(LambdaFunctionJsonSerializerContext.Default); }); var app = builder.Build(); app.MapPost("/", app.CreateLambdaFunction(functions => functions.Handle)); return app.Run(); ``` -------------------------------- ### Install Amazon.Lambda.Tools Global Tool Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Event Handler/BedrockAgentFunction/src/Readme.md Install the Amazon.Lambda.Tools Global Tool if you haven't already. This tool is used for deploying .NET applications to AWS Lambda. ```bash dotnet tool install -g Amazon.Lambda.Tools ``` -------------------------------- ### Log Output Example: Pascal Case Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md Demonstrates the JSON log output when PascalCase is applied to the log keys. ```json { "Level": "Information", "Message": "Collecting payment", "Timestamp": "2021-12-13T20:32:22.5774262Z", "Service": "payment", "ColdStart": true, "FunctionName": "test", "FunctionMemorySize": 128, "FunctionArn": "arn:aws:lambda:eu-west-1:12345678910:function:test", "FunctionRequestId": "52fdfc07-2182-154f-163f-5f0f9a621d72" } ``` -------------------------------- ### Install Metrics NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md Command to add the required metrics package to your ASP.NET Core project. ```bash dotnet add package AWS.Lambda.Powertools.Metrics.AspNetCore ``` -------------------------------- ### Build Application with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Logging/README.md Build your application using the 'sam build' command. This command creates a Docker image and installs dependencies. ```bash Logging$ sam build ``` -------------------------------- ### Install .NET Lambda Tools Global Tool Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/AOT/AOT_Metrics/src/AOT_Metrics/Readme.md Installs or updates the Amazon.Lambda.Tools Global Tool, required for deploying .NET Lambda functions. ```bash dotnet tool install -g Amazon.Lambda.Tools ``` ```bash dotnet tool update -g Amazon.Lambda.Tools ``` -------------------------------- ### Verify AWS Lambda Tools Installation Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/simple.md Check if the AWS Lambda CLI tools are installed correctly by viewing their help information. ```bash dotnet lambda --help ``` -------------------------------- ### Install AWS Lambda Powertools Kafka Protobuf NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.Kafka.Protobuf NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.Kafka.Protobuf ``` -------------------------------- ### Install AWS Lambda Powertools Parameters NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.Parameters NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.Parameters ``` -------------------------------- ### AppSync Event Handler Example Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.EventHandler/README.md This example demonstrates how to configure handlers for publish, aggregate publish, and subscribe events using AppSyncEventsResolver. It includes logging and error handling for specific event types. ```csharp using AWS.Lambda.Powertools.EventHandler; using Amazon.Lambda.Core; using Amazon.Lambda.RuntimeSupport; using Amazon.Lambda.Serialization.SystemTextJson; using AWS.Lambda.Powertools.EventHandler.AppSyncEvents; using AWS.Lambda.Powertools.Logging; var app = new AppSyncEventsResolver(); app.OnPublishAsync("/default/channel", async (payload) => { Logger.LogInformation("Published to /default/channel with {@payload}", payload); if (payload["eventType"].ToString() == "data_2") { throw new Exception("Error in /default/channel"); } return "Hello from /default/channel"; }); app.OnPublishAggregateAsync("/default/channel2", async (payload) => { var evt = new List(); foreach (var item in payload.Events) { var pd = new AppSyncEvent { Id = item.Id, Payload = new Dictionary { { "demo", "demo" } } }; if (item.Payload["eventType"].ToString() == "data_2") { pd.Payload["message"] = "Hello from /default/channel2 with data_2"; pd.Payload["data"] = new Dictionary { { "key", "value" } }; } evt.Add(pd); } Logger.LogInformation("Published to /default/channel2 with {@evt}", evt); return new AppSyncEventsResponse { Events = evt }; }); app.OnSubscribeAsync("/default/*", async (payload) => { Logger.LogInformation("Subscribed to /default/* with {@payload}", payload); return true; }); async Task Handler(AppSyncEventsRequest appSyncEvent, ILambdaContext context) { return await app.ResolveAsync(appSyncEvent, context); } await LambdaBootstrapBuilder.Create((Func>)Handler, new DefaultLambdaJsonSerializer()) .Build() .RunAsync(); ``` -------------------------------- ### Install AWS Lambda Powertools Tracing NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.Tracing NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.Tracing ``` -------------------------------- ### Example CloudWatch Logs excerpt Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md A sample JSON structure representing the output format for CloudWatch Metrics. ```json { "SuccessfulBooking": 1.0, "_aws": { "Timestamp": 1592234975665, "CloudWatchMetrics": [ { "Namespace": "ExampleApplication", "Dimensions": [ [ "service" ] ], "Metrics": [ { "Name": "SuccessfulBooking", "Unit": "Count" } ] } ] }, "Service": "Booking", "BookingId": "683EEB2D-B2F3-4075-96EE-788E6E2EED45" } ``` -------------------------------- ### Create Project Directory and Navigate Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/simple.md Set up a new directory for your project and change into it. ```bash mkdir powertools-logger-demo cd powertools-logger-demo ``` -------------------------------- ### Install AWS Lambda Powertools Metrics.AspNetCore NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.Metrics.AspNetCore NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.Metrics.AspNetCore ``` -------------------------------- ### Example Lambda Function Response Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/aot.md This is an example of the structured JSON response you can expect from a Lambda function using Powertools Logger, including cold start information. ```json { "Level": "Information", "Message": "test", "Timestamp": "2025-05-06T09:52:19.8222787Z", "Service": "TestService", "ColdStart": true, "XrayTraceId": "1-6819dbd3-0de6dc4b6cc712b020ee8ae7", "Name": "AWS.Lambda.Powertools.Logging.Logger" } { "Level": "Information", "Message": "Processing context: Amazon.Lambda.RuntimeSupport.LambdaContext", "Timestamp": "2025-05-06T09:52:19.8232664Z", "Service": "TestService", "ColdStart": true, "XrayTraceId": "1-6819dbd3-0de6dc4b6cc712b020ee8ae7", "Name": "AWS.Lambda.Powertools.Logging.Logger", "Context": { "AwsRequestId": "20f8da57-002b-426d-84c2-c295e4797e23", "ClientContext": { "Environment": null, "Client": null, "Custom": null }, "FunctionName": "powertools-aot-logger-demo", "FunctionVersion": "$LATEST", "Identity": { "IdentityId": null, "IdentityPoolId": null }, "InvokedFunctionArn": "your arn", "Logger": {}, "LogGroupName": "/aws/lambda/powertools-aot-logger-demo", "LogStreamName": "2025/05/06/[$LATEST]71249d02013b42b9b044b42dd4c7c37a", "MemoryLimitInMB": 512, "RemainingTime": "00:00:29.9972216" } } ``` -------------------------------- ### Install AWS Lambda Powertools Logging NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.Logging NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.Logging ``` -------------------------------- ### Class Library Deployment with Kafka Serializer Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/kafka.md Example of configuring a Kafka serializer for a class library deployment type in a Lambda function. ```csharp using AWS.Lambda.Powertools.Kafka; [assembly: LambdaSerializer(typeof(PowertoolsKafkaJsonSerializer))] namespace LambdaFunction { public class Function { public void FunctionHandler(KafkaEvent kafkaEvent, ILambdaContext context) { // Your Kafka message processing logic here } } } ``` -------------------------------- ### Define Protobuf Message Structure Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.Kafka.Protobuf/Readme.md Define your data structure in a .proto file. This example shows a simple Customer message. ```protobuf syntax = "proto3"; message Customer { string id = 1; string name = 2; int32 age = 3; string email = 4; } ``` -------------------------------- ### Select SAM Template Source Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/index.md When initializing a project with `sam init`, choose option 1 to use AWS Quick Start Templates. ```bash Which template source would you like to use? 1 - AWS Quick Start Templates 2 - Custom Template Location ``` -------------------------------- ### Install AWS Lambda Powertools Metrics NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.Metrics NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.Metrics ``` -------------------------------- ### Install AWS Lambda Powertools Event Handler NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.EventHandler/README.md Use this command to add the necessary NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.EventHandler --version 1.0.0 ``` -------------------------------- ### Example CloudWatch Logs for Multiple Dimensions Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md JSON output showing the structure of CloudWatch metrics with multiple dimensions. ```json { "SuccessfulBooking": 1, "_aws": { "Timestamp": 1592234975665, "CloudWatchMetrics": [ { "Namespace": "ExampleApplication", "Dimensions": [ [ "Service", "Environment", "Region" ] ], "Metrics": [ { "Name": "SuccessfulBooking", "Unit": "Count" } ] } ] }, "Service": "Booking", "Environment": "Prod", "Region": "eu-west-1" } ``` -------------------------------- ### Example CloudWatch Logs for Single Dimension Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md JSON output showing the structure of CloudWatch metrics with a single dimension. ```json { "SuccessfulBooking": 1, "_aws": { "Timestamp": 1592234975665, "CloudWatchMetrics": [ { "Namespace": "ExampleApplication", "Dimensions": [ [ "Service", "Environment" ] ], "Metrics": [ { "Name": "SuccessfulBooking", "Unit": "Count" } ] } ] }, "Service": "Booking", "Environment": "Prod" } ``` -------------------------------- ### Install AWS Lambda Powertools EventHandler NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/README.md Use this command to add the AWS.Lambda.Powertools.EventHandler NuGet package to your .NET project. ```bash dotnet add package AWS.Lambda.Powertools.EventHandler ``` -------------------------------- ### AOT Support: After PowertoolsSourceGeneratorSerializer Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md Example showing the updated setup using PowertoolsSourceGeneratorSerializer for improved AOT compatibility and serialization handling. ```csharp var lambdaLogger = new PowertoolsSourceGeneratorSerializer(); Logger.Setup(lambdaLogger); ``` -------------------------------- ### Example CloudWatch Logs for Flushed Metrics Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md JSON output showing the structure of flushed metrics in CloudWatch logs. ```json { "BookingConfirmation": 1.0, "_aws": { "Timestamp": 1592234975665, "CloudWatchMetrics": [ { "Namespace": "ExampleApplication", "Dimensions": [ [ "service" ] ], "Metrics": [ { "Name": "BookingConfirmation", "Unit": "Count" } ] } ] }, "service": "ExampleService" } ``` -------------------------------- ### Example Log Output Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/ServerlessApi/Readme.md This is an example of a log entry generated by AWS Lambda Powertools. It includes contextual information such as cold start status, correlation ID, function details, timestamp, log level, service name, and the custom log message. ```json {"cold_start":true,"correlation_id":"4749a5a8-93ea-464e-8778-3bffc5f9a35d","function_name":"AspNetCoreFunction","function_version":"$LATEST","function_memory_size":256,"function_arn":"arn:aws:lambda:us-east-1:012345678912:function:AspNetCoreFunction","function_request_id":"150991e0-20ec-4776-acd8-0f9290f1e968","timestamp":"2023-06-05T10:18:02.2434792Z","level":"Information","service":"aws-lambda-powertools-web-api-sample","name":"AWS.Lambda.Powertools.Logging.Logger","message":"Log entry information only about getting values? Or maybe something more "} ``` -------------------------------- ### Package and Deploy Lambda Function Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Event Handler/BedrockAgentFunction/src/Readme.md Navigate to the source directory, package the application into a zip file, and then deploy it using the CDK. ```bash cd "BedrockAgentFunction/src" dotnet lambda package --output-package ../release/BedrockAgentFunction.zip cd ../infra npm run cdk deploy -- --require-approval never ``` -------------------------------- ### AOT Support: With Powertools Logging Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/tracing.md Configure Tracing utility with AOT support, integrating with Powertools Logging using the PowertoolsSourceGeneratorSerializer. This example includes both tracing and logging setup. ```csharp using AWS.Lambda.Powertools.Logging.SourceGenerator; using AWS.Lambda.Powertools.Tracing; using AWS.Lambda.Powertools.Tracing.SourceGenerator; public class Function { [Logging(LogEvent = false, CorrelationIdPath = "request.headers.x-correlation-id")] [Tracing] public async Task FunctionHandler(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context) { // Use Tracing utility with AOT support and Powertools Logging var serializer = new PowertoolsSourceGeneratorSerializer(PowertoolsTrace.WithTracing()); // ... rest of your handler logic return new APIGatewayHttpApiV2ProxyResponse { StatusCode = 200, Body = "Request processed successfully" }; } } ``` -------------------------------- ### UseMetrics() Middleware Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md An extension method for IApplicationBuilder that adds MetricsMiddleware to capture cold start metrics and flush metrics on function exit. ```APIDOC ## UseMetrics() ### Description Adds a metrics middleware to the IApplicationBuilder to capture cold start metrics and flush metrics upon function exit. ### Method Extension Method (IApplicationBuilder) ### Usage app.UseMetrics(); ``` -------------------------------- ### AOT Support: Without Powertools Logging Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/tracing.md Configure Tracing utility with AOT support using the default SourceGeneratorLambdaJsonSerializer. This example shows the setup without integrating Powertools Logging. ```csharp using AWS.Lambda.Powertools.Tracing; using AWS.Lambda.Powertools.Tracing.SourceGenerator; public class Function { [Tracing] public async Task FunctionHandler(APIGatewayHttpApiV2ProxyRequest request, ILambdaContext context) { // Use Tracing utility with AOT support var serializer = new SourceGeneratorLambdaJsonSerializer(PowertoolsTrace.WithTracing()); // ... rest of your handler logic return new APIGatewayHttpApiV2ProxyResponse { StatusCode = 200, Body = "Request processed successfully" }; } } ``` -------------------------------- ### WithMetrics() Filter Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md An extension method for RouteHandlerBuilder that adds a metrics filter to capture cold start metrics and flush metrics for specific HTTP endpoints. ```APIDOC ## WithMetrics() ### Description Adds a metrics filter to the RouteHandlerBuilder to capture cold start metrics and flush metrics for the associated endpoint. ### Method Extension Method (RouteHandlerBuilder) ### Usage app.MapGet("/", () => "Hello World").WithMetrics(); ``` -------------------------------- ### Use Custom Parameter Store Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/parameters.md Demonstrates how to use a custom parameter provider, such as one backed by S3. This involves instantiating the custom provider and registering it with the ParametersManager. ```csharp var parameters = ParametersManager.Instance; parameters.Provider = new S3Provider("my-config-bucket", "settings/"); var connectionString = parameters.Get("db-connection-string"); ``` -------------------------------- ### Install Idempotency Package with NuGet Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.Idempotency/README.md Install the Idempotency package using the NuGet Package Manager. ```csharp Install-Package Amazon.Lambda.PowerTools.Idempotency ``` -------------------------------- ### Start API Locally with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Logging/README.md Emulate your application's API locally on port 3000 using 'sam local start-api'. This command reads the application template to define routes. ```bash Logging$ sam local start-api Logging$ curl http://localhost:3000/ ``` -------------------------------- ### Start Local API with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Metrics/README.md Use `sam local start-api` to emulate your serverless application's API locally. It runs on port 3000 by default. You can then use tools like `curl` to test endpoints. ```bash Metrics$ sam local start-api Metrics$ curl http://localhost:3000/ ``` -------------------------------- ### Protobuf Schema Evolution Example Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.Kafka.Protobuf/Readme.md Illustrates schema evolution in Protobuf, showing a version 1 schema and its updated version 2 with added optional fields. This demonstrates how Protobuf handles changes while maintaining backward compatibility. ```protobuf // Version 1 message Customer { string id = 1; string name = 2; } // Version 2 - Added optional field message Customer { string id = 1; string name = 2; int32 age = 3; // New optional field string email = 4; // Another new field } ``` -------------------------------- ### Install Batch Processing NuGet Package Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/batch-processing.md Install the AWS.Lambda.Powertools.BatchProcessing package using the NuGet Package Manager. ```powershell Install-Package AWS.Lambda.Powertools.BatchProcessing ``` -------------------------------- ### Analyze Cold Start Performance with CloudWatch Logs Insights Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/aot.md Use CloudWatch Logs Insights to query and analyze cold start performance metrics, including timestamp, cold start status, billed duration, and memory usage. ```sql fields @timestamp, coldStart, billedDurationMs, maxMemoryUsedMB | filter functionName = "powertools-aot-logger-demo" | sort @timestamp desc | limit 100 ``` -------------------------------- ### Start Local API with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/ServerlessApi/Readme.md Emulate your application's API locally on port 3000. The SAM CLI uses the application template to define routes and function mappings. ```bash sam local start-api ``` ```bash curl http://localhost:3000/api/values ``` -------------------------------- ### Example Event for Custom Correlation ID Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md An example event structure demonstrating where a custom correlation ID can be found. ```json { "headers": { "my_request_id_header": "correlation_id_value" } } ``` -------------------------------- ### Build Serverless Application with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Tracing/README.md Build your serverless application using the `sam build` command. This command prepares your application for deployment by building Docker images and installing dependencies. ```bash Tracing$ sam build ``` -------------------------------- ### AppSync Payload Request Example Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/event_handler/appsync_events.md This is an example of the JSON payload structure received by a Lambda function when invoked by AppSync. ```json { "identity":"None", "result":"None", "request":{ "headers": { "x-forwarded-for": "1.1.1.1, 2.2.2.2", "cloudfront-viewer-country": "US", "cloudfront-is-tablet-viewer": "false", "via": "2.0 xxxxxxxxxxxxxxxx.cloudfront.net (CloudFront)", "cloudfront-forwarded-proto": "https", "origin": "https://us-west-1.console.aws.amazon.com", "content-length": "217", "accept-language": "en-US,en;q=0.9", "host": "xxxxxxxxxxxxxxxx.appsync-api.us-west-1.amazonaws.com", "x-forwarded-proto": "https", "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36", "accept": "*/*", "cloudfront-is-mobile-viewer": "false", "cloudfront-is-smarttv-viewer": "false", "accept-encoding": "gzip, deflate, br", "referer": "https://us-west-1.console.aws.amazon.com/appsync/home?region=us-west-1", "content-type": "application/json", "sec-fetch-mode": "cors", "x-amz-cf-id": "3aykhqlUwQeANU-HGY7E_guV5EkNeMMtwyOgiA==", "x-amzn-trace-id": "Root=1-5f512f51-fac632066c5e848ae714", "authorization": "eyJraWQiOiJScWFCSlJqYVJlM0hrSnBTUFpIcVRXazNOW...", "sec-fetch-dest": "empty", "x-amz-user-agent": "AWS-Console-AppSync/", "cloudfront-is-desktop-viewer": "true", "sec-fetch-site": "cross-site", "x-forwarded-port": "443" }, "domainName":"None" }, "info":{ "channel":{ "path":"/default/channel", "segments":[ "default", "channel" ] }, "channelNamespace":{ "name":"default" }, "operation":"PUBLISH" }, "error":"None", "prev":"None", "stash":{ }, "outErrors":[ ], "events":[ { "payload":{ "data":"data_1" }, "id":"1" }, { "payload":{ "data":"data_2" }, "id":"2" } ] } ``` -------------------------------- ### Example CloudWatch Logs Output Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md This is an example of how log entries appear in CloudWatch Logs when using a custom log formatter. ```json { "Message": "Test Message", "Service": "lambda-example", "CorrelationIds": { "AwsRequestId": "52fdfc07-2182-154f-163f-5f0f9a621d72", "XRayTraceId": "1-61b7add4-66532bb81441e1b060389429", "CorrelationId": "correlation_id_value" }, "LambdaFunction": { "Name": "test", "Arn": "arn:aws:lambda:eu-west-1:12345678910:function:test", "MemorySize": 128, "Version": "$LATEST", "ColdStart": true }, "Level": "Information", "Timestamp": "2021-12-13T20:32:22.5774262Z", "Logger": { "Name": "AWS.Lambda.Powertools.Logging.Logger", "SampleRate": 0.7 } } ``` -------------------------------- ### Initialize Metrics with Default Dimensions in C# Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/ServerlessApi/Readme.md Demonstrates how to initialize the Metrics utility and set default dimensions, such as Environment, Runtime, and Version, which will be appended to every emitted metric. This setup is typically done in the Lambda function's entry point. ```csharp // We are defining some default dimensions. private Dictionary _defaultDimensions = new Dictionary{ {"Environment", Environment.GetEnvironmentVariable("ENVIRONMENT") ?? "Unknown"}, {"Runtime",Environment.Version.ToString()} }; [LambdaSerializer(typeof(DefaultLambdaJsonSerializer))] [Logging(CorrelationIdPath = CorrelationIdPaths.ApiGatewayRest, LogEvent = true)] // we are enabling logging, it needs to be added on method which have Lambda event [Tracing] // Adding a tracing attribute here we will see additional function call which might be important in terms of debugging [Metrics] // Metrics need to be initialized. The best place is the entry point opposite on adding attributes on each controller. public override Task FunctionHandlerAsync(APIGatewayProxyRequest request, ILambdaContext lambdaContext) { if (!_defaultDimensions.ContainsKey("Version")) _defaultDimensions.Add("Version", lambdaContext.FunctionVersion ?? "Unknown"); // Setting the default dimensions. They will be added to every emitted metric. Metrics.SetDefaultDimensions(_defaultDimensions); ``` -------------------------------- ### Update Amazon.Lambda.Tools Global Tool Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Event Handler/BedrockAgentFunction/src/Readme.md Check for and install the latest version of the Amazon.Lambda.Tools Global Tool if it's already installed. ```bash dotnet tool update -g Amazon.Lambda.Tools ``` -------------------------------- ### Set up Logger using Decorator Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md Use the `Logging` attribute on your Lambda function for a straightforward logger setup. This approach automatically handles logger initialization. ```csharp using AWS.Lambda.Powertools.Logging.EN; namespace Logging.Samples { public class LoggingWithDecorator { [Logging(Service="MyService", LogLevel=LogLevel.Information)] public string Handler(ILambdaContext context) { Logger.Log("Hello world"); return "Hello from Lambda"; } } } ``` -------------------------------- ### Install Idempotency Package with NuGet Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/utilities/idempotency.md Install the AWS Lambda Powertools Idempotency package using NuGet for your .NET project. ```powershell Install-Package AWS.Lambda.Powertools.Idempotency ```