### 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; } } } ``` -------------------------------- ### 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); ``` -------------------------------- ### 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); } } ``` -------------------------------- ### Capture Cold Start Metric with Configure Pattern Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md Use the configure pattern to set up cold start metric capture. This method provides a clear way to define metric configurations, including the capture of cold start invocations. ```csharp using AWS.Lambda.Powertools.Metrics; public class Function { public void CaptureColdStartConfigure([FromBody]APIGatewayProxyRequest request, ILambdaContext context) { Metrics.Configure(config => { config.WithNamespace("ExampleApplication"); config.WithService("ExampleService"); config.CaptureColdStart = true; }); // Handler logic } } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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/ ``` -------------------------------- ### 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 ``` -------------------------------- ### Capture Cold Start Metric with Builder Pattern Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md Configure cold start metric capture using the builder pattern. This approach allows for programmatic configuration of metric flushing and cold start detection. ```csharp using AWS.Lambda.Powertools.Metrics; public class Function { public void CaptureColdStartBuilder([FromBody]APIGatewayProxyRequest request, ILambdaContext context) { Metrics.WithAttribute(new MetricsAttribute { Namespace = "ExampleApplication", Service = "ExampleService", CaptureColdStart = true }); // Handler logic } } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 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 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.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 ``` -------------------------------- ### 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 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 ``` -------------------------------- ### 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 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Capture Cold Start Metric with Attribute Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md Optionally capture cold start metrics by setting CaptureColdStart parameter to true in the Metrics attribute. This creates a separate EMF blob for the ColdStart metric with FunctionName and Service dimensions. ```csharp using AWS.Lambda.Powertools.Metrics; public class Function { [Metrics(Namespace = "ExampleApplication", Service = "ExampleService", CaptureColdStart = true)] public void CaptureColdStart([FromBody]APIGatewayProxyRequest request, ILambdaContext context) { // Handler logic } } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### Lambda Function with Metrics Utility Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/metrics.md Example of a Lambda function demonstrating the usage of the Metrics utility. ```csharp using System; using System.Collections.Generic; using System.Net.Http; using System.Threading.Tasks; using Amazon.Lambda.Core; using Amazon.Lambda.APIGatewayEvents; using AWS.Lambda.Powertools.Metrics; using AWS.Lambda.Powertools.Logging; namespace Powertools.Examples.Metrics { public class LambdaFunction { [Metric(Namespace = "CustomNamespace", Service = "Booking")] public async Task FunctionHandler(APIGatewayProxyRequest request, ILambdaContext context) { Logger.Log("Processing request..."); // Add custom metrics Metrics.AddMetric("ProcessedRequests", 1, MetricUnit.Count); Metrics.AddMetric("ProcessingLatency", Guid.NewGuid().GetHashCode() % 100, MetricUnit.Milliseconds); // Add custom dimensions Metrics.AddDimension("BookingId", "12345"); // Add default dimensions Metrics.AddDimension("Environment", "Test"); return new APIGatewayProxyResponse { StatusCode = 200, Body = "Hello from Lambda!", Headers = new Dictionary { { "Content-Type", "application/json" } } }; } } } ``` -------------------------------- ### 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 ``` -------------------------------- ### 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; } ``` -------------------------------- ### 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 } } } ``` -------------------------------- ### 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 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 ``` -------------------------------- ### 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" } } ``` -------------------------------- ### 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 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" }; } } ``` -------------------------------- ### 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" }; } } ``` -------------------------------- ### 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"); ``` -------------------------------- ### 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/ ``` -------------------------------- ### 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 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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 ``` -------------------------------- ### 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" } } ``` -------------------------------- ### 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" } ] } ``` -------------------------------- ### 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); ``` -------------------------------- ### 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 ``` -------------------------------- ### 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"; } } } ``` -------------------------------- ### 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 } } ``` -------------------------------- ### 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 ``` -------------------------------- ### Build Lambda Application with SAM CLI Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Parameters/README.md Build your application using the 'sam build' command. This command builds a Docker image and installs dependencies. ```bash Parameters$ sam build ``` -------------------------------- ### 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 ``` -------------------------------- ### Create ASP.NET Core Minimal API Lambda Project Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/aspnet.md Creates a new directory for your project and initializes a new ASP.NET Core Minimal API project using the AWS Lambda template. ```bash mkdir powertools-aspnet-logger-demo cd powertools-aspnet-logger-demo dotnet new serverless.AspNetCoreMinimalAPI --name PowertoolsAspNetLoggerDemo cd PowertoolsAspNetLoggerDemo/src/PowertoolsAspNetLoggerDemo ``` -------------------------------- ### 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 ``` -------------------------------- ### Dependency Injection for Bedrock Agent Functions Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/event_handler/bedrock_agent_function.md Demonstrates how to set up dependency injection for integrating with services when handling Bedrock Agent functions. ```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) { _toolService = container.GetRequiredService(); } [LambdaFunction] public async Task FunctionHandler(BedrockEvent bedrockEvent, ILambdaContext context) { var response = await _toolService.InvokeAsync(bedrockEvent, context); return response; } } } ``` -------------------------------- ### 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 ``` -------------------------------- ### Create Native AOT Lambda Project Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/aot.md Creates a new directory for your project and initializes a Lambda project specifically configured for Native AOT compilation. Navigate into the created project directory afterwards. ```bash mkdir powertools-aot-logger-demo cd powertools-aot-logger-demo dotnet new lambda.NativeAOT -n PowertoolsAotLoggerDemo cd PowertoolsAotLoggerDemo ``` -------------------------------- ### Example Event for Built-in Correlation ID Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/core/logging.md An example event structure showing the 'RequestContext.RequestId' field, which can be used for built-in correlation ID extraction. ```json { "RequestContext": { "RequestId": "correlation_id_value" } } ``` -------------------------------- ### Build and Deploy Lambda Function Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/Kafka/Json/src/Readme.md Build the .NET project and deploy the application using AWS SAM CLI. ```bash git clone https://github.com/aws-powertools/powertools-lambda-dotnet.git cd powertools-lambda-dotnet/examples/Kafka/Json/src dotnet build sam build sam deploy --guided ``` -------------------------------- ### Run E2E Tests Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/tests/e2e/Readme.md Navigate to the E2E test project directory and execute the tests using the .NET test runner. This example targets the 'core' utilities tests. ```sh # example for Core utilities cd libraries/tests/e2e/functions/core dotnet test ``` -------------------------------- ### Example Structured Logs Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/docs/getting-started/logger/simple.md These are examples of JSON-formatted logs generated by AWS Powertools for .NET Logger, showing consistent structure and automatic inclusion of Lambda context. ```bash { "level": "Information", "message": "Processing request Amazon.Lambda.APIGatewayEvents.APIGatewayProxyRequest", "timestamp": "2025-04-23T15:16:42.7473327Z", "service": "greeting-service", "cold_start": true, "function_name": "powertools-logger-demo", "function_memory_size": 512, "function_arn": "", "function_request_id": "93f07a79-6146-4ed2-80d3-c0a06a5739e0", "function_version": "$LATEST", "xray_trace_id": "1-68090459-2c2aa3377cdaa9476348236a", "name": "AWS.Lambda.Powertools.Logging.Logger", "request": { "resource": null, "path": null, "http_method": null, "headers": null, "multi_value_headers": null, "query_string_parameters": { "name": "Powertools" }, "multi_value_query_string_parameters": null, "path_parameters": null, "stage_variables": null, "request_context": null, "body": null, "is_base64_encoded": false } } { "level": "Information", "message": "Response successfully created", "timestamp": "2025-04-23T15:16:42.9082709Z", "service": "greeting-service", "cold_start": true, "function_name": "powertools-logger-demo", "function_memory_size": 512, "function_arn": "", "function_request_id": "93f07a79-6146-4ed2-80d3-c0a06a5739e0", "function_version": "$LATEST", "xray_trace_id": "1-68090459-2c2aa3377cdaa9476348236a", "name": "AWS.Lambda.Powertools.Logging.Logger", "query_string": { "name": "Powertools" } } ``` -------------------------------- ### Install Bedrock Agent Function Resolver for ASP.NET Core Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/libraries/src/AWS.Lambda.Powertools.EventHandler.Resolvers.BedrockAgentFunction.AspNetCore/Readme.md Install the necessary NuGet package to use the Bedrock Agent Function Resolver with ASP.NET Core. ```bash dotnet add package AWS.Lambda.Powertools.EventHandler.Resolvers.BedrockAgentFunction.AspNetCore ``` -------------------------------- ### Build and Deploy Serverless Application Source: https://github.com/aws-powertools/powertools-lambda-dotnet/blob/develop/examples/ServerlessApi/Readme.md Use these commands to build the Docker image for your Lambda function and deploy the application to AWS using AWS SAM CLI. Ensure the serverless.template file is in your current directory. ```bash sam build -t ./serverless.template sam deploy --guided ```