diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index cfc6045b..a5a12869 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -20,27 +20,33 @@ permissions: jobs: build: runs-on: ubuntu-latest - steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 - - name: Setup .NET 6.0 & 8.0 + + - name: Setup .NET SDK uses: actions/setup-dotnet@3951f0dfe7a07e2313ec93c75700083e2005cbab # 4.3.0 with: dotnet-version: | - 6.0.405 - 8.0.101 + 6.0.x + 8.0.x + + - name: Install dependencies + run: dotnet restore + - name: Build - run: dotnet build --configuration Release - - name: Test Examples - run: dotnet test ../examples/ + run: dotnet build --configuration Release --no-restore /tl + - name: Test & Code Coverage - run: dotnet test --filter "Category!=E2E" --collect:"XPlat Code Coverage" --results-directory ./codecov --verbosity normal + run: dotnet test --no-restore --filter "Category!=E2E" --collect:"XPlat Code Coverage" --results-directory ./codecov --verbosity normal + + - name: Test Examples + run: dotnet test ../examples/ --verbosity normal + - name: Codecov uses: codecov/codecov-action@13ce06bfc6bbe3ecf90edbbf1bc32fe5978ca1d3 # 5.3.1 with: token: ${{ secrets.CODECOV_TOKEN }} - flags: unittests fail_ci_if_error: false name: codecov-lambda-powertools-dotnet verbose: true - directory: ./libraries/codecov + directory: ./libraries/codecov \ No newline at end of file diff --git a/docs/core/metrics-v2.md b/docs/core/metrics-v2.md new file mode 100644 index 00000000..ec6c536e --- /dev/null +++ b/docs/core/metrics-v2.md @@ -0,0 +1,890 @@ +--- +title: Metrics V2 +description: Core utility +--- + +Metrics creates custom metrics asynchronously by logging metrics to standard output following [Amazon CloudWatch Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html). + +These metrics can be visualized through [Amazon CloudWatch Console](https://aws.amazon.com/cloudwatch/). + +## Key features + +* Aggregate up to 100 metrics using a single [CloudWatch EMF](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html){target="_blank"} object (large JSON blob) +* Validating your metrics against common metric definitions mistakes (for example, metric unit, values, max dimensions, max metrics) +* Metrics are created asynchronously by the CloudWatch service. You do not need any custom stacks, and there is no impact to Lambda function latency +* Context manager to create a one off metric with a different dimension +* Ahead-of-Time compilation to native code support [AOT](https://docs.aws.amazon.com/lambda/latest/dg/dotnet-native-aot.html) from version 1.7.0 +* Support for AspNetCore middleware and filters to capture metrics for HTTP requests + +## Breaking changes from V1 + +* **`Dimensions`** outputs as an array of arrays instead of an array of objects. Example: `Dimensions: [["service", "Environment"]]` instead of `Dimensions: ["service", "Environment"]` +* **`FunctionName`** is not added as default dimension and only to cold start metric. +* **`Default Dimensions`** can now be included in Cold Start metrics, this is a potential breaking change if you were relying on the absence of default dimensions in Cold Start metrics when searching. + +
+ +
+ Screenshot of the Amazon CloudWatch Console showing an example of business metrics in the Metrics Explorer +
Metrics showcase - Metrics Explorer
+
+ +## Installation + +Powertools for AWS Lambda (.NET) are available as NuGet packages. You can install the packages from [NuGet Gallery](https://www.nuget.org/packages?q=AWS+Lambda+Powertools*){target="_blank"} or from Visual Studio editor by searching `AWS.Lambda.Powertools*` to see various utilities available. + +* [AWS.Lambda.Powertools.Metrics](https://www.nuget.org/packages?q=AWS.Lambda.Powertools.Metrics): + + `dotnet nuget add AWS.Lambda.Powertools.Metrics` + +## Terminologies + +If you're new to Amazon CloudWatch, there are two terminologies you must be aware of before using this utility: + +* **Namespace**. It's the highest level container that will group multiple metrics from multiple services for a given application, for example `ServerlessEcommerce`. +* **Dimensions**. Metrics metadata in key-value format. They help you slice and dice metrics visualization, for example `ColdStart` metric by Payment `service`. +* **Metric**. It's the name of the metric, for example: SuccessfulBooking or UpdatedBooking. +* **Unit**. It's a value representing the unit of measure for the corresponding metric, for example: Count or Seconds. +* **Resolution**. It's a value representing the storage resolution for the corresponding metric. Metrics can be either Standard or High resolution. Read more [here](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition). + +Visit the AWS documentation for a complete explanation for [Amazon CloudWatch concepts](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html). + +
+ +
Metric terminology, visually explained
+
+ +## Getting started + +**`Metrics`** is implemented as a Singleton to keep track of your aggregate metrics in memory and make them accessible anywhere in your code. To guarantee that metrics are flushed properly the **`MetricsAttribute`** must be added on the lambda handler. + +Metrics has two global settings that will be used across all metrics emitted. Use your application or main service as the metric namespace to easily group all metrics: + +Setting | Description | Environment variable | Constructor parameter +------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- | ------------------------------------------------- +**Service** | Optionally, sets **service** metric dimension across all metrics e.g. `payment` | `POWERTOOLS_SERVICE_NAME` | `Service` +**Metric namespace** | Logical container where all metrics will be placed e.g. `MyCompanyEcommerce` | `POWERTOOLS_METRICS_NAMESPACE` | `Namespace` + +!!! info "Autocomplete Metric Units" + All parameters in **`Metrics Attribute`** are optional. Following rules apply: + + - **Namespace:** **`Empty`** string by default. You can either specify it in code or environment variable. If not present before flushing metrics, a **`SchemaValidationException`** will be thrown. + - **Service:** **`service_undefined`** by default. You can either specify it in code or environment variable. + - **CaptureColdStart:** **`false`** by default. + - **RaiseOnEmptyMetrics:** **`false`** by default. + +### Full list of environment variables + +| Environment variable | Description | Default | +| ------------------------------------------------- | --------------------------------------------------------------------------------- | ------------------------------------------------- | +| **POWERTOOLS_SERVICE_NAME** | Sets service name used for tracing namespace, metrics dimension and structured logging | `"service_undefined"` | +| **POWERTOOLS_METRICS_NAMESPACE** | Sets namespace used for metrics | `None` | + +### Metrics object + +#### Attribute + +The **`MetricsAttribute`** is a class-level attribute that can be used to set the namespace and service for all metrics emitted by the lambda handler. + +```csharp hl_lines="3" +using AWS.Lambda.Powertools.Metrics; + +[Metrics(Namespace = "ExampleApplication", Service = "Booking")] +public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) +{ + ... +} +``` + +#### Methods + +The **`Metrics`** class provides methods to add metrics, dimensions, and metadata to the metrics object. + +```csharp hl_lines="5-7" +using AWS.Lambda.Powertools.Metrics; + +public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) +{ + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + Metrics.AddDimension("Environment", "Prod"); + Metrics.AddMetadata("BookingId", "683EEB2D-B2F3-4075-96EE-788E6E2EED45"); + ... +} +``` + +#### Initialization + +The **`Metrics`** object is initialized as a Singleton and can be accessed anywhere in your code. + +But can also be initialize with `Configure` or `Builder` patterns in your Lambda constructor, this the best option for testing. + +Configure: + +```csharp +using AWS.Lambda.Powertools.Metrics; + +public Function() +{ + Metrics.Configure(options => + { + options.Namespace = "dotnet-powertools-test"; + options.Service = "testService"; + options.CaptureColdStart = true; + options.DefaultDimensions = new Dictionary + { + { "Environment", "Prod" }, + { "Another", "One" } + }; + }); +} + +[Metrics] +public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) +{ + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + ... +} +``` + +Builder: + +```csharp +using AWS.Lambda.Powertools.Metrics; + +private readonly IMetrics _metrics; + +public Function() +{ + _metrics = new MetricsBuilder() + .WithCaptureColdStart(true) + .WithService("testService") + .WithNamespace("dotnet-powertools-test") + .WithDefaultDimensions(new Dictionary + { + { "Environment", "Prod1" }, + { "Another", "One" } + }).Build(); +} + +[Metrics] +public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) +{ + _metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + ... +} +``` + + +### Creating metrics + +You can create metrics using **`AddMetric`**, and you can create dimensions for all your aggregate metrics using **`AddDimension`** method. + +=== "Metrics" + + ```csharp hl_lines="5 8" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + } + } + ``` +=== "Metrics with custom dimensions" + + ```csharp hl_lines="8-9" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddDimension("Environment","Prod"); + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + } + } + ``` + +!!! tip "Autocomplete Metric Units" + `MetricUnit` enum facilitates finding a supported metric unit by CloudWatch. + +!!! note "Metrics overflow" + CloudWatch EMF supports a max of 100 metrics per batch. Metrics utility will flush all metrics when adding the 100th metric. Subsequent metrics, e.g. 101th, will be aggregated into a new EMF object, for your convenience. + +!!! warning "Metric value must be a positive number" + Metric values must be a positive number otherwise an `ArgumentException` will be thrown. + +!!! warning "Do not create metrics or dimensions outside the handler" + Metrics or dimensions added in the global scope will only be added during cold start. Disregard if that's the intended behavior. + +### Adding high-resolution metrics + +You can create [high-resolution metrics](https://aws.amazon.com/about-aws/whats-new/2023/02/amazon-cloudwatch-high-resolution-metric-extraction-structured-logs/) passing `MetricResolution` as parameter to `AddMetric`. + +!!! tip "When is it useful?" + High-resolution metrics are data with a granularity of one second and are very useful in several situations such as telemetry, time series, real-time incident management, and others. + +=== "Metrics with high resolution" + + ```csharp hl_lines="9 12 15" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + // Publish a metric with standard resolution i.e. StorageResolution = 60 + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count, MetricResolution.Standard); + + // Publish a metric with high resolution i.e. StorageResolution = 1 + Metrics.AddMetric("FailedBooking", 1, MetricUnit.Count, MetricResolution.High); + + // The last parameter (storage resolution) is optional + Metrics.AddMetric("SuccessfulUpgrade", 1, MetricUnit.Count); + } + } + ``` + +!!! tip "Autocomplete Metric Resolutions" + Use the `MetricResolution` enum to easily find a supported metric resolution by CloudWatch. + +### Adding default dimensions + +You can use **`SetDefaultDimensions`** method to persist dimensions across Lambda invocations. + +=== "SetDefaultDimensions method" + + ```csharp hl_lines="4 5 6 7 12" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + private Dictionary _defaultDimensions = new Dictionary{ + {"Environment", "Prod"}, + {"Another", "One"} + }; + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.SetDefaultDimensions(_defaultDimensions); + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + } + } + ``` + +### Adding default dimensions with cold start metric + +You can use the Builder or Configure patterns in your Lambda class constructor to set default dimensions. + +=== "Builder pattern" + + ```csharp hl_lines="12-16" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + private readonly IMetrics _metrics; + + public Function() + { + _metrics = new MetricsBuilder() + .WithCaptureColdStart(true) + .WithService("testService") + .WithNamespace("dotnet-powertools-test") + .WithDefaultDimensions(new Dictionary + { + { "Environment", "Prod1" }, + { "Another", "One" } + }).Build(); + } + + [Metrics] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + _metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + ... + } + ``` +=== "Configure pattern" + + ```csharp hl_lines="12-16" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + public Function() + { + Metrics.Configure(options => + { + options.Namespace = "dotnet-powertools-test"; + options.Service = "testService"; + options.CaptureColdStart = true; + options.DefaultDimensions = new Dictionary + { + { "Environment", "Prod" }, + { "Another", "One" } + }; + }); + } + + [Metrics] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + ... + } + ``` +### Adding dimensions + +You can add dimensions to your metrics using **`AddDimension`** method. + +=== "Function.cs" + + ```csharp hl_lines="8" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddDimension("Environment","Prod"); + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + } + } + ``` +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="11 24" + { + "SuccessfulBooking": 1.0, + "_aws": { + "Timestamp": 1592234975665, + "CloudWatchMetrics": [ + { + "Namespace": "ExampleApplication", + "Dimensions": [ + [ + "service", + "Environment" + ] + ], + "Metrics": [ + { + "Name": "SuccessfulBooking", + "Unit": "Count" + } + ] + } + ] + }, + "service": "ExampleService", + "Environment": "Prod" + } + ``` + +### Flushing metrics + +With **`MetricsAttribute`** all your metrics are validated, serialized and flushed to standard output when lambda handler completes execution or when you had the 100th metric to memory. + +You can also flush metrics manually by calling **`Flush`** method. + +During metrics validation, if no metrics are provided then a warning will be logged, but no exception will be raised. + +=== "Function.cs" + + ```csharp hl_lines="9" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = "ExampleApplication", Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + Metrics.Flush(); + } + } + ``` +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="2 7 10 15 22" + { + "BookingConfirmation": 1.0, + "_aws": { + "Timestamp": 1592234975665, + "CloudWatchMetrics": [ + { + "Namespace": "ExampleApplication", + "Dimensions": [ + [ + "service" + ] + ], + "Metrics": [ + { + "Name": "BookingConfirmation", + "Unit": "Count" + } + ] + } + ] + }, + "service": "ExampleService" + } + ``` + +!!! tip "Metric validation" + If metrics are provided, and any of the following criteria are not met, **`SchemaValidationException`** will be raised: + + * Maximum of 30 dimensions + * Namespace is set + * Metric units must be [supported by CloudWatch](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html) + +!!! info "We do not emit 0 as a value for ColdStart metric for cost reasons. [Let us know](https://github.com/aws-powertools/powertools-lambda-dotnet/issues/new?assignees=&labels=feature-request%2Ctriage&template=feature_request.yml&title=Feature+request%3A+TITLE) if you'd prefer a flag to override it" + +### Raising SchemaValidationException on empty metrics + +If you want to ensure that at least one metric is emitted, you can pass **`RaiseOnEmptyMetrics`** to the Metrics attribute: + +=== "Function.cs" + + ```python hl_lines="5" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(RaiseOnEmptyMetrics = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + ``` + +### Capturing cold start metric + +You can optionally capture cold start metrics by setting **`CaptureColdStart`** parameter to `true`. + +=== "Function.cs" + + ```csharp hl_lines="5" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(CaptureColdStart = true)] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + ... + ``` +=== "Builder pattern" + + ```csharp hl_lines="9" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + private readonly IMetrics _metrics; + + public Function() + { + _metrics = new MetricsBuilder() + .WithCaptureColdStart(true) + .WithService("testService") + .WithNamespace("dotnet-powertools-test") + } + + [Metrics] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + _metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + ... + } + ``` +=== "Configure pattern" + + ```csharp hl_lines="11" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + public Function() + { + Metrics.Configure(options => + { + options.Namespace = "dotnet-powertools-test"; + options.Service = "testService"; + options.CaptureColdStart = true; + }); + } + + [Metrics] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + ... + } + ``` + +If it's a cold start invocation, this feature will: + +* Create a separate EMF blob solely containing a metric named `ColdStart` +* Add `FunctionName` and `Service` dimensions + +This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions. + +## Advanced + +### Adding metadata + +You can add high-cardinality data as part of your Metrics log with `AddMetadata` method. This is useful when you want to search highly contextual information along with your metrics in your logs. + +!!! info + **This will not be available during metrics visualization** - Use **dimensions** for this purpose + +!!! info + Adding metadata with a key that is the same as an existing metric will be ignored + +=== "Function.cs" + + ```csharp hl_lines="9" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = ExampleApplication, Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + Metrics.AddMetadata("BookingId", "683EEB2D-B2F3-4075-96EE-788E6E2EED45"); + ... + ``` + +=== "Example CloudWatch Logs excerpt" + + ```json hl_lines="23" + { + "SuccessfulBooking": 1.0, + "_aws": { + "Timestamp": 1592234975665, + "CloudWatchMetrics": [ + { + "Namespace": "ExampleApplication", + "Dimensions": [ + [ + "service" + ] + ], + "Metrics": [ + { + "Name": "SuccessfulBooking", + "Unit": "Count" + } + ] + } + ] + }, + "Service": "Booking", + "BookingId": "683EEB2D-B2F3-4075-96EE-788E6E2EED45" + } + ``` + +### Single metric with a different dimension + +CloudWatch EMF uses the same dimensions across all your metrics. Use **`PushSingleMetric`** if you have a metric that should have different dimensions. + +!!! info + Generally, this would be an edge case since you [pay for unique metric](https://aws.amazon.com/cloudwatch/pricing). Keep the following formula in mind: + + **unique metric = (metric_name + dimension_name + dimension_value)** + +=== "Function.cs" + + ```csharp hl_lines="8-17" + using AWS.Lambda.Powertools.Metrics; + + public class Function { + + [Metrics(Namespace = ExampleApplication, Service = "Booking")] + public async Task FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context) + { + Metrics.PushSingleMetric( + metricName: "ColdStart", + value: 1, + unit: MetricUnit.Count, + nameSpace: "ExampleApplication", + service: "Booking", + dimensions: new Dictionary + { + {"FunctionContext", "$LATEST"} + }); + ... + ``` + +## AspNetCore + +### Installation + +To use the Metrics middleware in an ASP.NET Core application, you need to install the `AWS.Lambda.Powertools.Metrics.AspNetCore` NuGet package. + +```bash +dotnet add package AWS.Lambda.Powertools.Metrics.AspNetCore +``` + +### UseMetrics() Middleware + +The `UseMetrics` middleware is an extension method for the `IApplicationBuilder` interface. + +It adds a metrics middleware to the specified application builder, which captures cold start metrics (if enabled) and flushes metrics on function exit. + +#### Example + +```csharp hl_lines="21" + +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +var builder = WebApplication.CreateBuilder(args); + +// Configure metrics +builder.Services.AddSingleton(_ => new MetricsBuilder() + .WithNamespace("MyApi") // Namespace for the metrics + .WithService("WeatherService") // Service name for the metrics + .WithCaptureColdStart(true) // Capture cold start metrics + .WithDefaultDimensions(new Dictionary // Default dimensions for the metrics + { + {"Environment", "Prod"}, + {"Another", "One"} + }) + .Build()); // Build the metrics + +builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); + +var app = builder.Build(); + +app.UseMetrics(); // Add the metrics middleware + +app.MapGet("/powertools", (IMetrics metrics) => + { + // add custom metrics + metrics.AddMetric("MyCustomMetric", 1, MetricUnit.Count); + // flush metrics - this is required to ensure metrics are sent to CloudWatch + metrics.Flush(); + }); + +app.Run(); + +``` + +Here is the highlighted `UseMetrics` method: + +```csharp +/// +/// Adds a metrics middleware to the specified application builder. +/// This will capture cold start (if CaptureColdStart is enabled) metrics and flush metrics on function exit. +/// +/// The application builder to add the metrics middleware to. +/// The application builder with the metrics middleware added. +public static IApplicationBuilder UseMetrics(this IApplicationBuilder app) +{ + app.UseMiddleware(); + return app; +} +``` + +Explanation: + +- The method is defined as an extension method for the `IApplicationBuilder` interface. +- It adds a `MetricsMiddleware` to the application builder using the `UseMiddleware` method. +- The `MetricsMiddleware` captures and records metrics for HTTP requests, including cold start metrics if the `CaptureColdStart` option is enabled. + +### WithMetrics() filter + +The `WithMetrics` method is an extension method for the `RouteHandlerBuilder` class. + +It adds a metrics filter to the specified route handler builder, which captures cold start metrics (if enabled) and flushes metrics on function exit. + +#### Example + +```csharp hl_lines="31" + +using AWS.Lambda.Powertools.Metrics; +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +var builder = WebApplication.CreateBuilder(args); + +// Configure metrics +builder.Services.AddSingleton(_ => new MetricsBuilder() + .WithNamespace("MyApi") // Namespace for the metrics + .WithService("WeatherService") // Service name for the metrics + .WithCaptureColdStart(true) // Capture cold start metrics + .WithDefaultDimensions(new Dictionary // Default dimensions for the metrics + { + {"Environment", "Prod"}, + {"Another", "One"} + }) + .Build()); // Build the metrics + +// Add AWS Lambda support. When the application is run in Lambda, Kestrel is swapped out as the web server with Amazon.Lambda.AspNetCoreServer. This +// package will act as the web server translating requests and responses between the Lambda event source and ASP.NET Core. +builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); + +var app = builder.Build(); + +app.MapGet("/powertools", (IMetrics metrics) => + { + // add custom metrics + metrics.AddMetric("MyCustomMetric", 1, MetricUnit.Count); + // flush metrics - this is required to ensure metrics are sent to CloudWatch + metrics.Flush(); + }) + .WithMetrics(); + +app.Run(); + +``` + +Here is the highlighted `WithMetrics` method: + +```csharp +/// +/// Adds a metrics filter to the specified route handler builder. +/// This will capture cold start (if CaptureColdStart is enabled) metrics and flush metrics on function exit. +/// +/// The route handler builder to add the metrics filter to. +/// The route handler builder with the metrics filter added. +public static RouteHandlerBuilder WithMetrics(this RouteHandlerBuilder builder) +{ + builder.AddEndpointFilter(); + return builder; +} +``` + +Explanation: + +- The method is defined as an extension method for the `RouteHandlerBuilder` class. +- It adds a `MetricsFilter` to the route handler builder using the `AddEndpointFilter` method. +- The `MetricsFilter` captures and records metrics for HTTP endpoints, including cold start metrics if the `CaptureColdStart` option is enabled. +- The method returns the modified `RouteHandlerBuilder` instance with the metrics filter added. + + +## Testing your code + +### Unit testing + +To test your code that uses the Metrics utility, you can use the `TestLambdaContext` class from the `Amazon.Lambda.TestUtilities` package. + +You can also use the `IMetrics` interface to mock the Metrics utility in your tests. + +Here is an example of how you can test a Lambda function that uses the Metrics utility: + +#### Lambda Function + +```csharp +using System.Collections.Generic; +using Amazon.Lambda.Core; + +public class MetricsnBuilderHandler +{ + private readonly IMetrics _metrics; + + // Allow injection of IMetrics for testing + public MetricsnBuilderHandler(IMetrics metrics = null) + { + _metrics = metrics ?? new MetricsBuilder() + .WithCaptureColdStart(true) + .WithService("testService") + .WithNamespace("dotnet-powertools-test") + .WithDefaultDimensions(new Dictionary + { + { "Environment", "Prod1" }, + { "Another", "One" } + }).Build(); + } + + [Metrics] + public void Handler(ILambdaContext context) + { + _metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + } +} + +``` +#### Unit Tests + + +```csharp +[Fact] + public void Handler_With_Builder_Should_Configure_In_Constructor() + { + // Arrange + var handler = new MetricsnBuilderHandler(); + + // Act + handler.Handler(new TestLambdaContext + { + FunctionName = "My_Function_Name" + }); + + // Get the output and parse it + var metricsOutput = _consoleOut.ToString(); + + // Assert cold start + Assert.Contains( + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\",\"FunctionName\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod1\",\"Another\":\"One\",\"FunctionName\":\"My_Function_Name\",\"ColdStart\":1}", + metricsOutput); + // Assert successful Memory metrics + Assert.Contains( + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"SuccessfulBooking\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\",\"FunctionName\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod1\",\"Another\":\"One\",\"FunctionName\":\"My_Function_Name\",\"SuccessfulBooking\":1}", + metricsOutput); + } + + [Fact] + public void Handler_With_Builder_Should_Configure_In_Constructor_Mock() + { + var metricsMock = Substitute.For(); + + metricsMock.Options.Returns(new MetricsOptions + { + CaptureColdStart = true, + Namespace = "dotnet-powertools-test", + Service = "testService", + DefaultDimensions = new Dictionary + { + { "Environment", "Prod" }, + { "Another", "One" } + } + }); + + Metrics.UseMetricsForTests(metricsMock); + + var sut = new MetricsnBuilderHandler(metricsMock); + + // Act + sut.Handler(new TestLambdaContext + { + FunctionName = "My_Function_Name" + }); + + metricsMock.Received(1).PushSingleMetric("ColdStart", 1, MetricUnit.Count, "dotnet-powertools-test", + service: "testService", Arg.Any>()); + metricsMock.Received(1).AddMetric("SuccessfulBooking", 1, MetricUnit.Count); + } +``` + +### Environment variables + +???+ tip + Ignore this section, if: + + * You are explicitly setting namespace/default dimension via `namespace` and `service` parameters + * You're not instantiating `Metrics` in the global namespace + + For example, `Metrics(namespace="ExampleApplication", service="booking")` + +Make sure to set `POWERTOOLS_METRICS_NAMESPACE` and `POWERTOOLS_SERVICE_NAME` before running your tests to prevent failing on `SchemaValidation` exception. You can set it before you run tests by adding the environment variable. + +```csharp title="Injecting Metric Namespace before running tests" +Environment.SetEnvironmentVariable("POWERTOOLS_METRICS_NAMESPACE","AWSLambdaPowertools"); +``` diff --git a/docs/core/metrics.md b/docs/core/metrics.md index 65fb5f50..0a766414 100644 --- a/docs/core/metrics.md +++ b/docs/core/metrics.md @@ -109,7 +109,7 @@ You can create metrics using **`AddMetric`**, and you can create dimensions for === "Metrics" - ```csharp hl_lines="8" + ```csharp hl_lines="5 8" using AWS.Lambda.Powertools.Metrics; public class Function { diff --git a/libraries/AWS.Lambda.Powertools.sln b/libraries/AWS.Lambda.Powertools.sln index 72aea967..bcc1a2c9 100644 --- a/libraries/AWS.Lambda.Powertools.sln +++ b/libraries/AWS.Lambda.Powertools.sln @@ -97,6 +97,10 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AOT-FunctionHandlerTest", " EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AOT-FunctionMethodAttributeTest", "tests\e2e\functions\idempotency\AOT-Function\src\AOT-FunctionMethodAttributeTest\AOT-FunctionMethodAttributeTest.csproj", "{CC8CFF43-DC72-464C-A42D-55E023DE8500}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Metrics.AspNetCore", "src\AWS.Lambda.Powertools.Metrics.AspNetCore\AWS.Lambda.Powertools.Metrics.AspNetCore.csproj", "{A2AD98B1-2BED-4864-B573-77BE7B52FED2}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "AWS.Lambda.Powertools.Metrics.AspNetCore.Tests", "tests\AWS.Lambda.Powertools.Metrics.AspNetCore.Tests\AWS.Lambda.Powertools.Metrics.AspNetCore.Tests.csproj", "{F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -518,6 +522,30 @@ Global {CC8CFF43-DC72-464C-A42D-55E023DE8500}.Release|x64.Build.0 = Release|Any CPU {CC8CFF43-DC72-464C-A42D-55E023DE8500}.Release|x86.ActiveCfg = Release|Any CPU {CC8CFF43-DC72-464C-A42D-55E023DE8500}.Release|x86.Build.0 = Release|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Debug|x64.ActiveCfg = Debug|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Debug|x64.Build.0 = Debug|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Debug|x86.ActiveCfg = Debug|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Debug|x86.Build.0 = Debug|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Release|Any CPU.Build.0 = Release|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Release|x64.ActiveCfg = Release|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Release|x64.Build.0 = Release|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Release|x86.ActiveCfg = Release|Any CPU + {A2AD98B1-2BED-4864-B573-77BE7B52FED2}.Release|x86.Build.0 = Release|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Debug|Any CPU.Build.0 = Debug|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Debug|x64.ActiveCfg = Debug|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Debug|x64.Build.0 = Debug|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Debug|x86.ActiveCfg = Debug|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Debug|x86.Build.0 = Debug|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Release|Any CPU.ActiveCfg = Release|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Release|Any CPU.Build.0 = Release|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Release|x64.ActiveCfg = Release|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Release|x64.Build.0 = Release|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Release|x86.ActiveCfg = Release|Any CPU + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(NestedProjects) = preSolution @@ -563,5 +591,7 @@ Global {ACA789EA-BD38-490B-A7F8-6A3A86985025} = {FB2C7DA3-6FCE-429D-86F9-5775D0231EC6} {E71C48D2-AD56-4177-BBD7-6BB859A40C92} = {FB2C7DA3-6FCE-429D-86F9-5775D0231EC6} {CC8CFF43-DC72-464C-A42D-55E023DE8500} = {FB2C7DA3-6FCE-429D-86F9-5775D0231EC6} + {A2AD98B1-2BED-4864-B573-77BE7B52FED2} = {73C9B1E5-3893-47E8-B373-17E5F5D7E6F5} + {F8F80477-1EAD-4C5C-A329-CBC0A60C7CAB} = {1CFF5568-8486-475F-81F6-06105C437528} EndGlobalSection EndGlobal diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/ConsoleWrapper.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/ConsoleWrapper.cs new file mode 100644 index 00000000..87321140 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/ConsoleWrapper.cs @@ -0,0 +1,31 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System; + +namespace AWS.Lambda.Powertools.Common; + +/// +public class ConsoleWrapper : IConsoleWrapper +{ + /// + public void WriteLine(string message) => Console.WriteLine(message); + /// + public void Debug(string message) => System.Diagnostics.Debug.WriteLine(message); + /// + public void Error(string message) => Console.Error.WriteLine(message); + /// + public string ReadLine() => Console.ReadLine(); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Common/Core/IConsoleWrapper.cs b/libraries/src/AWS.Lambda.Powertools.Common/Core/IConsoleWrapper.cs new file mode 100644 index 00000000..de75020e --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Common/Core/IConsoleWrapper.cs @@ -0,0 +1,46 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +namespace AWS.Lambda.Powertools.Common; + +/// +/// Wrapper for console operations to facilitate testing by abstracting system console interactions. +/// +public interface IConsoleWrapper +{ + /// + /// Writes the specified message followed by a line terminator to the standard output stream. + /// + /// The message to write. + void WriteLine(string message); + + /// + /// Writes a debug message to the trace listeners in the Debug.Listeners collection. + /// + /// The debug message to write. + void Debug(string message); + + /// + /// Writes the specified error message followed by a line terminator to the standard error stream. + /// + /// The error message to write. + void Error(string message); + + /// + /// Reads the next line of characters from the standard input stream. + /// + /// The next line of characters from the input stream, or null if no more lines are available. + string ReadLine(); +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/AWS.Lambda.Powertools.Metrics.AspNetCore.csproj b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/AWS.Lambda.Powertools.Metrics.AspNetCore.csproj new file mode 100644 index 00000000..976fe8b0 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/AWS.Lambda.Powertools.Metrics.AspNetCore.csproj @@ -0,0 +1,25 @@ + + + + + AWS.Lambda.Powertools.Metrics.AspNetCore + Powertools for AWS Lambda (.NET) - Metrics AspNetCore package. + AWS.Lambda.Powertools.Metrics.AspNetCore + AWS.Lambda.Powertools.Metrics.AspNetCore + net8.0 + false + enable + enable + + + + + + + + + + + + + diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/ColdStartTracker.cs b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/ColdStartTracker.cs new file mode 100644 index 00000000..aafaad26 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/ColdStartTracker.cs @@ -0,0 +1,76 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using Amazon.Lambda.Core; +using Microsoft.AspNetCore.Http; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + + +/// +/// Tracks and manages cold start metrics for Lambda functions in ASP.NET Core applications. +/// +/// +/// This class is responsible for detecting and recording the first invocation (cold start) of a Lambda function. +/// It ensures thread-safe tracking of cold starts and proper metric capture using the provided IMetrics implementation. +/// +internal class ColdStartTracker : IDisposable +{ + private readonly IMetrics _metrics; + private static bool _coldStart = true; + private static readonly object _lock = new(); + + /// + /// Initializes a new instance of the class. + /// + /// The metrics implementation to use for capturing cold start metrics. + public ColdStartTracker(IMetrics metrics) + { + _metrics = metrics; + } + + /// + /// Tracks the cold start of the Lambda function. + /// + /// The current HTTP context. + internal void TrackColdStart(HttpContext context) + { + if (!_coldStart) return; + + lock (_lock) + { + if (!_coldStart) return; + _metrics.CaptureColdStartMetric(context.Items["LambdaContext"] as ILambdaContext); + _coldStart = false; + } + } + + /// + /// Resets the cold start tracking state. + /// + internal static void ResetColdStart() + { + lock (_lock) + { + _coldStart = true; + } + } + + /// + public void Dispose() + { + ResetColdStart(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsEndpointExtensions.cs b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsEndpointExtensions.cs new file mode 100644 index 00000000..a2101229 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsEndpointExtensions.cs @@ -0,0 +1,37 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +/// +/// Provides extension methods for adding metrics to route handlers. +/// +public static class MetricsEndpointExtensions +{ + /// + /// Adds a metrics filter to the specified route handler builder. + /// This will capture cold start (if CaptureColdStart is enabled) metrics and flush metrics on function exit. + /// + /// The route handler builder to add the metrics filter to. + /// The route handler builder with the metrics filter added. + public static RouteHandlerBuilder WithMetrics(this RouteHandlerBuilder builder) + { + builder.AddEndpointFilter(); + return builder; + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsFilter.cs b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsFilter.cs new file mode 100644 index 00000000..f89fd94b --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsFilter.cs @@ -0,0 +1,68 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using Microsoft.AspNetCore.Http; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +/// +/// Represents a filter that captures and records metrics for HTTP endpoints. +/// +/// +/// This filter is responsible for tracking cold starts and capturing metrics during HTTP request processing. +/// It integrates with the ASP.NET Core endpoint routing system to inject metrics collection at the endpoint level. +/// +/// +/// +public class MetricsFilter : IEndpointFilter, IDisposable +{ + private readonly ColdStartTracker _coldStartTracker; + + /// + /// Initializes a new instance of the class. + /// + public MetricsFilter(IMetrics metrics) + { + _coldStartTracker = new ColdStartTracker(metrics); + } + + /// + /// Invokes the filter asynchronously. + /// + /// The context for the endpoint filter invocation. + /// The delegate to invoke the next filter or endpoint. + /// A task that represents the asynchronous operation, containing the result of the endpoint invocation. + public async ValueTask InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next) + { + try + { + _coldStartTracker.TrackColdStart(context.HttpContext); + } + catch + { + // ignored + } + + return await next(context); + } + + /// + /// Disposes of the resources used by the filter. + /// + public void Dispose() + { + _coldStartTracker.Dispose(); + } +} \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsMiddlewareExtensions.cs b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsMiddlewareExtensions.cs new file mode 100644 index 00000000..7515c1b5 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/Http/MetricsMiddlewareExtensions.cs @@ -0,0 +1,50 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +/// +/// Provides extension methods for adding metrics middleware to the application pipeline. +/// +public static class MetricsMiddlewareExtensions +{ + /// + /// Adds middleware to capture and record metrics for HTTP requests, including cold start tracking. + /// + /// The application builder instance used to configure the request pipeline. + /// The application builder with the metrics middleware added. + /// + /// This middleware tracks cold starts and captures request metrics. To use this middleware, ensure you have registered + /// the required services using builder.Services.AddSingleton<IMetrics>() in your service configuration. + /// + /// + /// + /// app.UseMetrics(); + /// + /// + public static IApplicationBuilder UseMetrics(this IApplicationBuilder app) + { + return app.Use(async (context, next) => + { + var metrics = context.RequestServices.GetRequiredService(); + using var metricsHelper = new ColdStartTracker(metrics); + metricsHelper.TrackColdStart(context); + await next(); + }); + } +} diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/InternalsVisibleTo.cs b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/InternalsVisibleTo.cs new file mode 100644 index 00000000..5b9c15a1 --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/InternalsVisibleTo.cs @@ -0,0 +1,18 @@ +/* + * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). + * You may not use this file except in compliance with the License. + * A copy of the License is located at + * + * http://aws.amazon.com/apache2.0 + * + * or in the "license" file accompanying this file. This file is distributed + * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either + * express or implied. See the License for the specific language governing + * permissions and limitations under the License. + */ + +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.AspNetCore.Tests")] \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/README.md b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/README.md new file mode 100644 index 00000000..a1ca8fee --- /dev/null +++ b/libraries/src/AWS.Lambda.Powertools.Metrics.AspNetCore/README.md @@ -0,0 +1,149 @@ +# AWS Lambda Powertools Metrics for ASP.NET Core + +This library provides utilities for capturing and publishing custom metrics from your AWS Lambda functions using ASP.NET Core. + +## Getting Started + +This library provides utilities for capturing and publishing custom metrics from your AWS Lambda functions using ASP.NET Core. + +### Installation + +You can install the package via the NuGet package manager just search for `AWS.Lambda.Powertools.Metrics.AspNetCore`. + +You can also install via powershell using the following command. + +```shell +dotnet add package AWS.Lambda.Powertools.Metrics.AspNetCore +``` + +```csharp + +using AWS.Lambda.Powertools.Metrics; +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +var builder = WebApplication.CreateBuilder(args); + +// Configure metrics +builder.Services.AddSingleton(_ => new MetricsBuilder() + .WithNamespace("MyApi") // Namespace for the metrics + .WithService("WeatherService") // Service name for the metrics + .WithCaptureColdStart(true) // Capture cold start metrics + .WithDefaultDimensions(new Dictionary // Default dimensions for the metrics + { + {"Environment", "Prod"}, + {"Another", "One"} + }) + .Build()); // Build the metrics + +// Add AWS Lambda support. When the application is run in Lambda, Kestrel is swapped out as the web server with Amazon.Lambda.AspNetCoreServer. This +// package will act as the web server translating requests and responses between the Lambda event source and ASP.NET Core. +builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); + +var app = builder.Build(); + +app.MapGet("/powertools", (IMetrics metrics) => + { + // add custom metrics + metrics.AddMetric("MyCustomMetric", 1, MetricUnit.Count); + // flush metrics - this is required to ensure metrics are sent to CloudWatch + metrics.Flush(); + }) + .WithMetrics(); + +app.Run(); + +``` + +### WithMetrics() filter + +The `WithMetrics` method is an extension method for the `RouteHandlerBuilder` class. + +It adds a metrics filter to the specified route handler builder, which captures cold start metrics (if enabled) and flushes metrics on function exit. + +Here is the highlighted `WithMetrics` method: + +```csharp +/// +/// Adds a metrics filter to the specified route handler builder. +/// This will capture cold start (if CaptureColdStart is enabled) metrics and flush metrics on function exit. +/// +/// The route handler builder to add the metrics filter to. +/// The route handler builder with the metrics filter added. +public static RouteHandlerBuilder WithMetrics(this RouteHandlerBuilder builder) +{ + builder.AddEndpointFilter(); + return builder; +} +``` + +Explanation: +- The method is defined as an extension method for the `RouteHandlerBuilder` class. +- It adds a `MetricsFilter` to the route handler builder using the `AddEndpointFilter` method. +- The `MetricsFilter` captures and records metrics for HTTP endpoints, including cold start metrics if the `CaptureColdStart` option is enabled. +- The method returns the modified `RouteHandlerBuilder` instance with the metrics filter added. + + +### UseMetrics() Middleware + +The `UseMetrics` middleware is an extension method for the `IApplicationBuilder` interface. + +It adds a metrics middleware to the specified application builder, which captures cold start metrics (if enabled) and flushes metrics on function exit. + +#### Example + +```csharp + +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; + +var builder = WebApplication.CreateBuilder(args); + +// Configure metrics +builder.Services.AddSingleton(_ => new MetricsBuilder() + .WithNamespace("MyApi") // Namespace for the metrics + .WithService("WeatherService") // Service name for the metrics + .WithCaptureColdStart(true) // Capture cold start metrics + .WithDefaultDimensions(new Dictionary // Default dimensions for the metrics + { + {"Environment", "Prod"}, + {"Another", "One"} + }) + .Build()); // Build the metrics + +builder.Services.AddAWSLambdaHosting(LambdaEventSource.RestApi); + +var app = builder.Build(); + +app.UseMetrics(); // Add the metrics middleware + +app.MapGet("/powertools", (IMetrics metrics) => + { + // add custom metrics + metrics.AddMetric("MyCustomMetric", 1, MetricUnit.Count); + // flush metrics - this is required to ensure metrics are sent to CloudWatch + metrics.Flush(); + }); + +app.Run(); + +``` + +Here is the highlighted `UseMetrics` method: + +```csharp +/// +/// Adds a metrics middleware to the specified application builder. +/// This will capture cold start (if CaptureColdStart is enabled) metrics and flush metrics on function exit. +/// +/// The application builder to add the metrics middleware to. +/// The application builder with the metrics middleware added. +public static IApplicationBuilder UseMetrics(this IApplicationBuilder app) +{ + app.UseMiddleware(); + return app; +} +``` + +Explanation: +- The method is defined as an extension method for the `IApplicationBuilder` interface. +- It adds a `MetricsMiddleware` to the application builder using the `UseMiddleware` method. +- The `MetricsMiddleware` captures and records metrics for HTTP requests, including cold start metrics if the `CaptureColdStart` option is enabled. \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs index 69ef2ee3..02164e8a 100644 --- a/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/IMetrics.cs @@ -14,6 +14,7 @@ */ using System.Collections.Generic; +using Amazon.Lambda.Core; namespace AWS.Lambda.Powertools.Metrics; @@ -85,10 +86,10 @@ void AddMetric(string key, double value, MetricUnit unit = MetricUnit.None, /// The metric unit. /// The namespace. /// The service name. - /// The default dimensions. + /// The default dimensions. /// The metric resolution. void PushSingleMetric(string name, double value, MetricUnit unit, string nameSpace = null, string service = null, - Dictionary defaultDimensions = null, MetricResolution resolution = MetricResolution.Default); + Dictionary dimensions = null, MetricResolution resolution = MetricResolution.Default); /// /// Clears the default dimensions. @@ -106,4 +107,10 @@ void PushSingleMetric(string name, double value, MetricUnit unit, string nameSpa /// /// The metrics options. public MetricsOptions Options { get; } + + /// + /// Captures the cold start metric. + /// + /// + void CaptureColdStartMetric(ILambdaContext context); } \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspect.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspect.cs index 1006d25c..aad3617c 100644 --- a/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspect.cs +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Internal/MetricsAspect.cs @@ -88,28 +88,10 @@ public void Before( Triggers = triggers }; - if (_metricsInstance.Options.CaptureColdStart != null && _metricsInstance.Options.CaptureColdStart.Value && _isColdStart) + if (_isColdStart) { - var defaultDimensions = _metricsInstance.Options?.DefaultDimensions; + _metricsInstance.CaptureColdStartMetric(GetContext(eventArgs)); _isColdStart = false; - - var context = GetContext(eventArgs); - - if (context is not null) - { - defaultDimensions ??= new Dictionary(); - defaultDimensions.Add("FunctionName", context.FunctionName); - _metricsInstance.SetDefaultDimensions(defaultDimensions); - } - - _metricsInstance.PushSingleMetric( - "ColdStart", - 1.0, - MetricUnit.Count, - _metricsInstance.Options?.Namespace ?? "", - _metricsInstance.Options?.Service ?? "", - defaultDimensions - ); } } @@ -140,6 +122,7 @@ internal static void ResetForTest() /// private static ILambdaContext GetContext(AspectEventArgs args) { + if (args == null || args.Method == null) return null; var index = Array.FindIndex(args.Method.GetParameters(), p => p.ParameterType == typeof(ILambdaContext)); if (index >= 0) { diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs index 0e44da1c..a1b53257 100644 --- a/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/InternalsVisibleTo.cs @@ -15,4 +15,6 @@ using System.Runtime.CompilerServices; -[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.Tests")] \ No newline at end of file +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.Tests")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.AspNetCore")] +[assembly: InternalsVisibleTo("AWS.Lambda.Powertools.Metrics.AspNetCore.Tests")] \ No newline at end of file diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs index 86823bf0..510fde9f 100644 --- a/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs @@ -15,9 +15,8 @@ using System; using System.Collections.Generic; -using System.Diagnostics; using System.Linq; -using System.Threading; +using Amazon.Lambda.Core; using AWS.Lambda.Powertools.Common; namespace AWS.Lambda.Powertools.Metrics; @@ -34,12 +33,12 @@ public class Metrics : IMetrics, IDisposable /// public static IMetrics Instance { - get => Current.Value ?? new Metrics(PowertoolsConfigurations.Instance); - private set => Current.Value = value; + get => _instance ?? new Metrics(PowertoolsConfigurations.Instance, consoleWrapper: new ConsoleWrapper()); + private set => _instance = value; } /// - public MetricsOptions Options => + public MetricsOptions Options => _options ?? new() { CaptureColdStart = _captureColdStartEnabled, @@ -52,7 +51,7 @@ public static IMetrics Instance /// /// The instance /// - private static readonly AsyncLocal Current = new(); + private static IMetrics _instance; /// /// The context @@ -74,11 +73,20 @@ public static IMetrics Instance /// private bool _captureColdStartEnabled; - // - // Shared synchronization object - // + /// + /// Shared synchronization object + /// private readonly object _lockObj = new(); + /// + /// The options + /// + private readonly MetricsOptions _options; + + /// + /// The console wrapper for console output + /// + private readonly IConsoleWrapper _consoleWrapper; /// /// Initializes a new instance of the class. @@ -117,13 +125,17 @@ public static IMetrics Configure(Action configure) /// Metrics Service Name /// Instructs metrics validation to throw exception if no metrics are provided /// Instructs metrics capturing the ColdStart is enabled + /// For console output + /// MetricsOptions internal Metrics(IPowertoolsConfigurations powertoolsConfigurations, string nameSpace = null, string service = null, - bool raiseOnEmptyMetrics = false, bool captureColdStartEnabled = false) + bool raiseOnEmptyMetrics = false, bool captureColdStartEnabled = false, IConsoleWrapper consoleWrapper = null, MetricsOptions options = null) { _powertoolsConfigurations = powertoolsConfigurations; + _consoleWrapper = consoleWrapper; _context = new MetricsContext(); _raiseOnEmptyMetrics = raiseOnEmptyMetrics; _captureColdStartEnabled = captureColdStartEnabled; + _options = options; Instance = this; _powertoolsConfigurations.SetExecutionEnvironment(this); @@ -165,7 +177,7 @@ void IMetrics.AddMetric(string key, double value, MetricUnit unit, MetricResolut } else { - Debug.WriteLine( + _consoleWrapper.Debug( $"##WARNING##: Metrics should be initialized in Handler method before calling {nameof(AddMetric)} method."); } } @@ -237,7 +249,7 @@ void IMetrics.Flush(bool metricsOverflow) { var emfPayload = _context.Serialize(); - Console.WriteLine(emfPayload); + _consoleWrapper.WriteLine(emfPayload); _context.ClearMetrics(); @@ -246,7 +258,7 @@ void IMetrics.Flush(bool metricsOverflow) else { if (!_captureColdStartEnabled) - Console.WriteLine( + _consoleWrapper.WriteLine( "##User-WARNING## No application metrics to publish. The cold-start metric may be published if enabled. If application metrics should never be empty, consider using 'RaiseOnEmptyMetrics = true'"); } } @@ -295,7 +307,7 @@ private Dictionary GetDefaultDimensions() /// void IMetrics.PushSingleMetric(string name, double value, MetricUnit unit, string nameSpace, - string service, Dictionary defaultDimensions, MetricResolution resolution) + string service, Dictionary dimensions, MetricResolution resolution) { if (string.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name), @@ -305,10 +317,10 @@ void IMetrics.PushSingleMetric(string name, double value, MetricUnit unit, strin context.SetNamespace(nameSpace ?? GetNamespace()); context.SetService(service ?? _context.GetService()); - if (defaultDimensions != null) + if (dimensions != null) { - var defaultDimensionsList = DictionaryToList(defaultDimensions); - context.SetDefaultDimensions(defaultDimensionsList); + var dimensionsList = DictionaryToList(dimensions); + context.AddDimensions(dimensionsList); } context.AddMetric(name, value, unit, resolution); @@ -403,7 +415,7 @@ public static void AddMetadata(string key, object value) /// Default Dimension List public static void SetDefaultDimensions(Dictionary defaultDimensions) { - Instance?.SetDefaultDimensions(defaultDimensions); + Instance.SetDefaultDimensions(defaultDimensions); } /// @@ -411,15 +423,7 @@ public static void SetDefaultDimensions(Dictionary defaultDimens /// public static void ClearDefaultDimensions() { - if (Instance != null) - { - Instance.ClearDefaultDimensions(); - } - else - { - Debug.WriteLine( - $"##WARNING##: Metrics should be initialized in Handler method before calling {nameof(ClearDefaultDimensions)} method."); - } + Instance.ClearDefaultDimensions(); } /// @@ -431,7 +435,7 @@ private void Flush(MetricsContext context) { var emfPayload = context.Serialize(); - Console.WriteLine(emfPayload); + _consoleWrapper.WriteLine(emfPayload); } /// @@ -443,22 +447,14 @@ private void Flush(MetricsContext context) /// Metric Unit /// Metric Namespace /// Service Name - /// Default dimensions list + /// Default dimensions list /// Metrics resolution public static void PushSingleMetric(string name, double value, MetricUnit unit, string nameSpace = null, - string service = null, Dictionary defaultDimensions = null, + string service = null, Dictionary dimensions = null, MetricResolution resolution = MetricResolution.Default) { - if (Instance != null) - { - Instance.PushSingleMetric(name, value, unit, nameSpace, service, defaultDimensions, - resolution); - } - else - { - Debug.WriteLine( - $"##WARNING##: Metrics should be initialized in Handler method before calling {nameof(PushSingleMetric)} method."); - } + Instance.PushSingleMetric(name, value, unit, nameSpace, service, dimensions, + resolution); } /// @@ -468,12 +464,12 @@ public static void PushSingleMetric(string name, double value, MetricUnit unit, /// Default dimensions list private List DictionaryToList(Dictionary defaultDimensions) { - var defaultDimensionsList = new List(); + var dimensionsList = new List(); if (defaultDimensions != null) foreach (var item in defaultDimensions) - defaultDimensionsList.Add(new DimensionSet(item.Key, item.Value)); + dimensionsList.Add(new DimensionSet(item.Key, item.Value)); - return defaultDimensionsList; + return dimensionsList; } private Dictionary ListToDictionary(List dimensions) @@ -487,10 +483,37 @@ private Dictionary ListToDictionary(List dimension } catch (Exception e) { - Debug.WriteLine("Error converting list to dictionary: " + e.Message); + _consoleWrapper.Debug("Error converting list to dictionary: " + e.Message); return dictionary; } } + + /// + /// Captures the cold start metric. + /// + /// The ILambdaContext. + void IMetrics.CaptureColdStartMetric(ILambdaContext context) + { + if (Options.CaptureColdStart == null || !Options.CaptureColdStart.Value) return; + + // bring default dimensions if exist + var dimensions = Options?.DefaultDimensions; + + if (context is not null) + { + dimensions ??= new Dictionary(); + dimensions.Add("FunctionName", context.FunctionName); + } + + PushSingleMetric( + "ColdStart", + 1.0, + MetricUnit.Count, + Options?.Namespace ?? "", + Options?.Service ?? "", + dimensions + ); + } /// /// Helper method for testing purposes. Clears static instance between test execution diff --git a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs index 8e886a90..759cdb9e 100644 --- a/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs +++ b/libraries/src/AWS.Lambda.Powertools.Metrics/Model/MetricsContext.cs @@ -135,6 +135,18 @@ public void AddDimension(string key, string value) _rootNode.AWS.AddDimensionSet(new DimensionSet(key, value)); } + /// + /// Adds new dimensions to memory + /// + /// List of dimensions + public void AddDimensions(List dimensions) + { + foreach (var dimension in dimensions) + { + _rootNode.AWS.AddDimensionSet(dimension); + } + } + /// /// Sets default dimensions list /// diff --git a/libraries/src/Directory.Packages.props b/libraries/src/Directory.Packages.props index 56d0fba9..c5af6311 100644 --- a/libraries/src/Directory.Packages.props +++ b/libraries/src/Directory.Packages.props @@ -11,6 +11,8 @@ + + diff --git a/libraries/tests/AWS.Lambda.Powertools.Common.Tests/ConsoleWrapperTests.cs b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/ConsoleWrapperTests.cs new file mode 100644 index 00000000..6395f79a --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Common.Tests/ConsoleWrapperTests.cs @@ -0,0 +1,53 @@ +using System; +using System.IO; +using Xunit; + +namespace AWS.Lambda.Powertools.Common.Tests; + +public class ConsoleWrapperTests +{ + [Fact] + public void WriteLine_Should_Write_To_Console() + { + // Arrange + var consoleWrapper = new ConsoleWrapper(); + var writer = new StringWriter(); + Console.SetOut(writer); + + // Act + consoleWrapper.WriteLine("test message"); + + // Assert + Assert.Equal($"test message{Environment.NewLine}", writer.ToString()); + } + + [Fact] + public void Error_Should_Write_To_Error_Console() + { + // Arrange + var consoleWrapper = new ConsoleWrapper(); + var writer = new StringWriter(); + Console.SetError(writer); + + // Act + consoleWrapper.Error("error message"); + + // Assert + Assert.Equal($"error message{Environment.NewLine}", writer.ToString()); + } + + [Fact] + public void ReadLine_Should_Read_From_Console() + { + // Arrange + var consoleWrapper = new ConsoleWrapper(); + var reader = new StringReader("input text"); + Console.SetIn(reader); + + // Act + var result = consoleWrapper.ReadLine(); + + // Assert + Assert.Equal("input text", result); + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests.csproj b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests.csproj new file mode 100644 index 00000000..15ac1312 --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests.csproj @@ -0,0 +1,35 @@ + + + + + AWS.Lambda.Powertools.Metrics.AspNetCore.Tests + AWS.Lambda.Powertools.Metrics.AspNetCore.Tests + net8.0 + enable + enable + + false + true + + + + + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsEndpointExtensionsTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsEndpointExtensionsTests.cs new file mode 100644 index 00000000..c5ee7c2c --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsEndpointExtensionsTests.cs @@ -0,0 +1,164 @@ +using Amazon.Lambda.TestUtilities; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Xunit; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Tests; + +[Collection("Metrics")] +public class MetricsEndpointExtensionsTests : IDisposable +{ + [Fact] + public async Task When_WithMetrics_Should_Add_ColdStart() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "TestNamespace", + Service = "TestService" + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + var metrics = new Metrics(conf, consoleWrapper: consoleWrapper, options: options); + var builder = WebApplication.CreateBuilder(); + builder.Services.AddSingleton(metrics); + builder.WebHost.UseTestServer(); + + var app = builder.Build(); + + app.MapGet("/test", () => Results.Ok(new { success = true })).WithMetrics(); + + await app.StartAsync(); + var client = app.GetTestClient(); + + // Act + var response = await client.GetAsync("/test"); + + // Assert + Assert.Equal(200, (int)response.StatusCode); + + // Assert metrics calls + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("CloudWatchMetrics\":[{\"Namespace\":\"TestNamespace\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[]]}]},\"ColdStart\":1}")) + ); + + + await app.StopAsync(); + } + + [Fact] + public async Task When_WithMetrics_Should_Add_ColdStart_Dimensions() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "TestNamespace", + Service = "TestService" + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + var metrics = new Metrics(conf, consoleWrapper: consoleWrapper, options: options); + + var builder = WebApplication.CreateBuilder(); + builder.Services.AddSingleton(metrics); + builder.WebHost.UseTestServer(); + + + var app = builder.Build(); + app.Use(async (context, next) => + { + var lambdaContext = new TestLambdaContext + { + FunctionName = "TestFunction" + }; + context.Items["LambdaContext"] = lambdaContext; + await next(); + }); + + app.MapGet("/test", () => Results.Ok(new { success = true })).WithMetrics(); + + await app.StartAsync(); + var client = app.GetTestClient(); + + // Act + var response = await client.GetAsync("/test"); + + // Assert + Assert.Equal(200, (int)response.StatusCode); + + // Assert metrics calls + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("CloudWatchMetrics\":[{\"Namespace\":\"TestNamespace\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"FunctionName\"]]}]},\"FunctionName\":\"TestFunction\",\"ColdStart\":1}")) + ); + + await app.StopAsync(); + } + + [Fact] + public async Task When_WithMetrics_Should_Add_ColdStart_Default_Dimensions() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "TestNamespace", + Service = "TestService", + DefaultDimensions = new Dictionary + { + { "Environment", "Prod" } + } + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + var metrics = new Metrics(conf, consoleWrapper: consoleWrapper, options: options); + + var builder = WebApplication.CreateBuilder(); + builder.Services.AddSingleton(metrics); + builder.WebHost.UseTestServer(); + + + var app = builder.Build(); + app.Use(async (context, next) => + { + var lambdaContext = new TestLambdaContext + { + FunctionName = "TestFunction" + }; + context.Items["LambdaContext"] = lambdaContext; + await next(); + }); + + app.MapGet("/test", () => Results.Ok(new { success = true })).WithMetrics(); + + await app.StartAsync(); + var client = app.GetTestClient(); + + // Act + var response = await client.GetAsync("/test"); + + // Assert + Assert.Equal(200, (int)response.StatusCode); + + // Assert metrics calls + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("CloudWatchMetrics\":[{\"Namespace\":\"TestNamespace\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Environment\",\"FunctionName\"]]}]},\"Environment\":\"Prod\",\"FunctionName\":\"TestFunction\",\"ColdStart\":1}")) + ); + + await app.StopAsync(); + } + + public void Dispose() + { + ColdStartTracker.ResetColdStart(); + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsFilterTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsFilterTests.cs new file mode 100644 index 00000000..9951034a --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsFilterTests.cs @@ -0,0 +1,76 @@ +using Amazon.Lambda.Core; +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; +using Microsoft.AspNetCore.Http; +using NSubstitute; +using Xunit; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Tests; + +[Collection("Metrics")] +public class MetricsFilterTests : IDisposable +{ + private readonly IMetrics _metrics; + private readonly EndpointFilterInvocationContext _context; + + public MetricsFilterTests() + { + ColdStartTracker.ResetColdStart(); // Reset before each test + _metrics = Substitute.For(); + _context = Substitute.For(); + var lambdaContext = Substitute.For(); + + var httpContext = new DefaultHttpContext(); + httpContext.Items["LambdaContext"] = lambdaContext; + _context.HttpContext.Returns(httpContext); + } + + [Fact] + public async Task InvokeAsync_Second_Call_DoesNotRecord_ColdStart_Metric() + { + // Arrange + var options = new MetricsOptions { CaptureColdStart = false }; + _metrics.Options.Returns(options); + + var filter = new MetricsFilter(_metrics); + var next = new EndpointFilterDelegate(_ => ValueTask.FromResult("result")); + + // Act + _ = await filter.InvokeAsync(_context, next); + var result = await filter.InvokeAsync(_context, next); + + // Assert + _metrics.Received(1).CaptureColdStartMetric(Arg.Any() ); + Assert.Equal("result", result); + } + + [Fact] + public async Task InvokeAsync_ShouldCallNextAndContinue() + { + // Arrange + var metrics = Substitute.For(); + metrics.Options.Returns(new MetricsOptions { CaptureColdStart = true }); + + var httpContext = new DefaultHttpContext(); + var context = new DefaultEndpointFilterInvocationContext(httpContext); + var filter = new MetricsFilter(metrics); + + var called = false; + EndpointFilterDelegate next = _ => + { + called = true; + return ValueTask.FromResult("result"); + }; + + // Act + var result = await filter.InvokeAsync(context, next); + + // Assert + Assert.True(called); + Assert.Equal("result", result); + } + + public void Dispose() + { + ColdStartTracker.ResetColdStart(); + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsMiddlewareExtensionsTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsMiddlewareExtensionsTests.cs new file mode 100644 index 00000000..a9510eaa --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.AspNetCore.Tests/MetricsMiddlewareExtensionsTests.cs @@ -0,0 +1,105 @@ +using Amazon.Lambda.TestUtilities; +using AWS.Lambda.Powertools.Common; +using AWS.Lambda.Powertools.Metrics.AspNetCore.Http; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.TestHost; +using Microsoft.Extensions.DependencyInjection; +using NSubstitute; +using Xunit; + +namespace AWS.Lambda.Powertools.Metrics.AspNetCore.Tests; + +[Collection("Metrics")] +public class MetricsMiddlewareExtensionsTests : IDisposable +{ + [Fact] + public async Task When_UseMetrics_Should_Add_ColdStart() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "TestNamespace", + Service = "TestService" + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + var metrics = new Metrics(conf, consoleWrapper: consoleWrapper, options: options); + + var builder = WebApplication.CreateBuilder(); + builder.Services.AddSingleton(metrics); + builder.WebHost.UseTestServer(); + + var app = builder.Build(); + app.UseMetrics(); + app.MapGet("/test", () => Results.Ok()); + + await app.StartAsync(); + var client = app.GetTestClient(); + + // Act + var response = await client.GetAsync("/test"); + + // Assert + Assert.Equal(200, (int)response.StatusCode); + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("CloudWatchMetrics\":[{\"Namespace\":\"TestNamespace\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[]]}]},\"ColdStart\":1}")) + ); + + await app.StopAsync(); + } + + [Fact] + public async Task When_UseMetrics_Should_Add_ColdStart_With_LambdaContext() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "TestNamespace", + Service = "TestService" + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + var metrics = new Metrics(conf, consoleWrapper:consoleWrapper, options: options); + + var builder = WebApplication.CreateBuilder(); + builder.Services.AddSingleton(metrics); + builder.WebHost.UseTestServer(); + + var app = builder.Build(); + app.Use(async (context, next) => + { + var lambdaContext = new TestLambdaContext + { + FunctionName = "TestFunction" + }; + context.Items["LambdaContext"] = lambdaContext; + await next(); + }); + app.UseMetrics(); + app.MapGet("/test", () => Results.Ok()); + + await app.StartAsync(); + var client = app.GetTestClient(); + + // Act + var response = await client.GetAsync("/test"); + + // Assert + Assert.Equal(200, (int)response.StatusCode); + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("CloudWatchMetrics\":[{\"Namespace\":\"TestNamespace\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"FunctionName\"]]}]},\"FunctionName\":\"TestFunction\",\"ColdStart\":1}")) + ); + + await app.StopAsync(); + } + + public void Dispose() + { + ColdStartTracker.ResetColdStart(); + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/DefaultDimensionsHandler.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/DefaultDimensionsHandler.cs index 1028f58c..95e6a9f3 100644 --- a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/DefaultDimensionsHandler.cs +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/DefaultDimensionsHandler.cs @@ -9,6 +9,9 @@ public DefaultDimensionsHandler() { Metrics.Configure(options => { + options.Namespace = "dotnet-powertools-test"; + options.Service = "testService"; + options.CaptureColdStart = true; options.DefaultDimensions = new Dictionary { { "Environment", "Prod" }, @@ -17,14 +20,14 @@ public DefaultDimensionsHandler() }); } - [Metrics(Namespace = "dotnet-powertools-test", Service = "testService", CaptureColdStart = true)] + [Metrics] public void Handler() { // Default dimensions are already set Metrics.AddMetric("SuccessfulBooking", 1, MetricUnit.Count); } - [Metrics(Namespace = "dotnet-powertools-test", Service = "testService", CaptureColdStart = true)] + [Metrics] public void HandlerWithContext(ILambdaContext context) { // Default dimensions are already set and adds FunctionName dimension diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandler.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandler.cs index abc41d7f..910ca0a9 100644 --- a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandler.cs +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandler.cs @@ -14,13 +14,11 @@ */ using System; -using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Amazon.Lambda.Core; -using Amazon.Lambda.TestUtilities; namespace AWS.Lambda.Powertools.Metrics.Tests.Handlers; @@ -43,12 +41,12 @@ public void AddDimensions() public void AddMultipleDimensions() { Metrics.PushSingleMetric("SingleMetric1", 1, MetricUnit.Count, resolution: MetricResolution.High, - defaultDimensions: new Dictionary { + dimensions: new Dictionary { { "Default1", "SingleMetric1" } }); Metrics.PushSingleMetric("SingleMetric2", 1, MetricUnit.Count, resolution: MetricResolution.High, nameSpace: "ns2", - defaultDimensions: new Dictionary { + dimensions: new Dictionary { { "Default1", "SingleMetric2" }, { "Default2", "SingleMetric2" } }); @@ -60,7 +58,7 @@ public void AddMultipleDimensions() public void PushSingleMetricWithNamespace() { Metrics.PushSingleMetric("SingleMetric", 1, MetricUnit.Count, resolution: MetricResolution.High, - defaultDimensions: new Dictionary { + dimensions: new Dictionary { { "Default", "SingleMetric" } }); } @@ -69,7 +67,7 @@ public void PushSingleMetricWithNamespace() public void PushSingleMetricWithEnvNamespace() { Metrics.PushSingleMetric("SingleMetric", 1, MetricUnit.Count, resolution: MetricResolution.High, - defaultDimensions: new Dictionary { + dimensions: new Dictionary { { "Default", "SingleMetric" } }); } diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandlerTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandlerTests.cs index c34397f4..1f89a208 100644 --- a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandlerTests.cs +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/Handlers/FunctionHandlerTests.cs @@ -16,6 +16,7 @@ using System; using System.Collections.Generic; using System.Threading.Tasks; +using Amazon.Lambda.Core; using Amazon.Lambda.TestUtilities; using AWS.Lambda.Powertools.Common; using NSubstitute; @@ -142,11 +143,11 @@ public void DefaultDimensions_AreAppliedCorrectly() // Assert cold start Assert.Contains( - "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Environment\",\"Another\",\"Service\"]]}]},\"Environment\":\"Prod\",\"Another\":\"One\",\"Service\":\"testService\",\"ColdStart\":1}", + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod\",\"Another\":\"One\",\"ColdStart\":1}", metricsOutput); // Assert successful booking metrics Assert.Contains( - "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"SuccessfulBooking\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Environment\",\"Another\",\"Service\"]]}]},\"Environment\":\"Prod\",\"Another\":\"One\",\"Service\":\"testService\",\"SuccessfulBooking\":1}", + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"SuccessfulBooking\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod\",\"Another\":\"One\",\"SuccessfulBooking\":1}", metricsOutput); } @@ -167,11 +168,11 @@ public void DefaultDimensions_AreAppliedCorrectly_WithContext_FunctionName() // Assert cold start Assert.Contains( - "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Environment\",\"Another\",\"Service\",\"FunctionName\"]]}]},\"Environment\":\"Prod\",\"Another\":\"One\",\"Service\":\"testService\",\"FunctionName\":\"My_Function_Name\",\"ColdStart\":1}", + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\",\"FunctionName\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod\",\"Another\":\"One\",\"FunctionName\":\"My_Function_Name\",\"ColdStart\":1}", metricsOutput); // Assert successful Memory metrics Assert.Contains( - "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"Memory\",\"Unit\":\"Megabytes\"}],\"Dimensions\":[[\"Environment\",\"Another\",\"Service\",\"FunctionName\"]]}]},\"Environment\":\"Prod\",\"Another\":\"One\",\"Service\":\"testService\",\"FunctionName\":\"My_Function_Name\",\"Memory\":10}", + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"Memory\",\"Unit\":\"Megabytes\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod\",\"Another\":\"One\",\"Memory\":10}", metricsOutput); } @@ -202,8 +203,7 @@ public void Handler_WithMockedMetrics_ShouldCallAddMetric() sut.Handler(); // Assert - metricsMock.Received(1).PushSingleMetric("ColdStart", 1, MetricUnit.Count, "dotnet-powertools-test", - service: "testService", Arg.Any>()); + metricsMock.Received(1).CaptureColdStartMetric(Arg.Any()); metricsMock.Received(1).AddMetric("SuccessfulBooking", 1, MetricUnit.Count); } @@ -228,7 +228,7 @@ public void Handler_With_Builder_Should_Configure_In_Constructor() metricsOutput); // Assert successful Memory metrics Assert.Contains( - "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"SuccessfulBooking\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\",\"FunctionName\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod1\",\"Another\":\"One\",\"FunctionName\":\"My_Function_Name\",\"SuccessfulBooking\":1}", + "\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"SuccessfulBooking\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Service\",\"Environment\",\"Another\"]]}]},\"Service\":\"testService\",\"Environment\":\"Prod1\",\"Another\":\"One\",\"SuccessfulBooking\":1}", metricsOutput); } @@ -259,8 +259,7 @@ public void Handler_With_Builder_Should_Configure_In_Constructor_Mock() FunctionName = "My_Function_Name" }); - metricsMock.Received(1).PushSingleMetric("ColdStart", 1, MetricUnit.Count, "dotnet-powertools-test", - service: "testService", Arg.Any>()); + metricsMock.Received(1).CaptureColdStartMetric(Arg.Any()); metricsMock.Received(1).AddMetric("SuccessfulBooking", 1, MetricUnit.Count); } @@ -282,89 +281,6 @@ public void Handler_With_Builder_Should_Raise_Empty_Metrics() var exception = Assert.Throws(() => handler.HandlerEmpty()); Assert.Equal("No metrics have been provided.", exception.Message); } - - [Fact] - public void When_ColdStart_Should_Use_DefaultDimensions_From_Options() - { - // Arrange - var metricsMock = Substitute.For(); - var expectedDimensions = new Dictionary - { - { "Environment", "Test" }, - { "Region", "us-east-1" } - }; - - metricsMock.Options.Returns(new MetricsOptions - { - Namespace = "dotnet-powertools-test", - Service = "testService", - CaptureColdStart = true, - DefaultDimensions = expectedDimensions - }); - - Metrics.UseMetricsForTests(metricsMock); - - var context = new TestLambdaContext - { - FunctionName = "TestFunction" - }; - - // Act - _handler.HandleWithLambdaContext(context); - - // Assert - metricsMock.Received(1).PushSingleMetric( - "ColdStart", - 1.0, - MetricUnit.Count, - "dotnet-powertools-test", - "testService", - Arg.Is>(d => - d.ContainsKey("Environment") && d["Environment"] == "Test" && - d.ContainsKey("Region") && d["Region"] == "us-east-1" && - d.ContainsKey("FunctionName") && d["FunctionName"] == "TestFunction" - ) - ); - } - - [Fact] - public void When_ColdStart_And_DefaultDimensions_Is_Null_Should_Only_Add_Service_And_FunctionName() - { - // Arrange - var metricsMock = Substitute.For(); - - metricsMock.Options.Returns(new MetricsOptions - { - Namespace = "dotnet-powertools-test", - Service = "testService", - CaptureColdStart = true, - DefaultDimensions = null - }); - - Metrics.UseMetricsForTests(metricsMock); - - var context = new TestLambdaContext - { - FunctionName = "TestFunction" - }; - - // Act - _handler.HandleWithLambdaContext(context); - - // Assert - metricsMock.Received(1).PushSingleMetric( - "ColdStart", - 1.0, - MetricUnit.Count, - "dotnet-powertools-test", - "testService", - Arg.Is>(d => - d.Count == 1 && - d.ContainsKey("FunctionName") && - d["FunctionName"] == "TestFunction" - ) - ); - } public void Dispose() { diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsAttributeTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsAttributeTests.cs new file mode 100644 index 00000000..04a1f86d --- /dev/null +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsAttributeTests.cs @@ -0,0 +1,72 @@ +using Xunit; + +namespace AWS.Lambda.Powertools.Metrics.Tests; + +[Collection("Sequential")] +public class MetricsAttributeTests +{ + [Fact] + public void MetricsAttribute_WhenCaptureColdStartSet_ShouldSetFlag() + { + // Arrange & Act + var attribute = new MetricsAttribute + { + CaptureColdStart = true + }; + + // Assert + Assert.True(attribute.CaptureColdStart); + Assert.True(attribute.IsCaptureColdStartSet); + } + + [Fact] + public void MetricsAttribute_WhenCaptureColdStartNotSet_ShouldNotSetFlag() + { + // Arrange & Act + var attribute = new MetricsAttribute(); + + // Assert + Assert.False(attribute.CaptureColdStart); + Assert.False(attribute.IsCaptureColdStartSet); + } + + [Fact] + public void MetricsAttribute_WhenRaiseOnEmptyMetricsSet_ShouldSetFlag() + { + // Arrange & Act + var attribute = new MetricsAttribute + { + RaiseOnEmptyMetrics = true + }; + + // Assert + Assert.True(attribute.RaiseOnEmptyMetrics); + Assert.True(attribute.IsRaiseOnEmptyMetricsSet); + } + + [Fact] + public void MetricsAttribute_WhenRaiseOnEmptyMetricsNotSet_ShouldNotSetFlag() + { + // Arrange & Act + var attribute = new MetricsAttribute(); + + // Assert + Assert.False(attribute.RaiseOnEmptyMetrics); + Assert.False(attribute.IsRaiseOnEmptyMetricsSet); + } + + [Fact] + public void MetricsAttribute_ShouldSetNamespaceAndService() + { + // Arrange & Act + var attribute = new MetricsAttribute + { + Namespace = "TestNamespace", + Service = "TestService" + }; + + // Assert + Assert.Equal("TestNamespace", attribute.Namespace); + Assert.Equal("TestService", attribute.Service); + } +} \ No newline at end of file diff --git a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsTests.cs b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsTests.cs index 13afdecd..36039756 100644 --- a/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsTests.cs +++ b/libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsTests.cs @@ -1,5 +1,7 @@ using System; using System.Collections.Generic; +using Amazon.Lambda.Core; +using Amazon.Lambda.TestUtilities; using AWS.Lambda.Powertools.Common; using NSubstitute; using Xunit; @@ -20,11 +22,11 @@ public void Metrics_Set_Execution_Environment_Context() var env = Substitute.For(); env.GetAssemblyName(Arg.Any()).Returns(assemblyName); env.GetAssemblyVersion(Arg.Any()).Returns(assemblyVersion); - + var conf = new PowertoolsConfigurations(new SystemWrapper(env)); - - var metrics = new Metrics(conf); - + + _ = new Metrics(conf); + // Assert env.Received(1).SetEnvironmentVariable( "AWS_EXECUTION_ENV", $"{Constants.FeatureContextIdentifier}/Metrics/{assemblyVersion}" @@ -32,51 +34,69 @@ public void Metrics_Set_Execution_Environment_Context() env.Received(1).GetEnvironmentVariable("AWS_EXECUTION_ENV"); } - + [Fact] - public void When_Constructor_With_Namespace_And_Service_Should_Set_Both() + public void Before_When_RaiseOnEmptyMetricsNotSet_Should_Configure_Null() { // Arrange - var metricsMock = Substitute.For(); - var powertoolsConfigMock = Substitute.For(); + MetricsAspect.ResetForTest(); + var method = typeof(MetricsTests).GetMethod(nameof(TestMethod)); + var trigger = new MetricsAttribute(); + + var metricsAspect = new MetricsAspect(); // Act - var metrics = new Metrics(powertoolsConfigMock, "TestNamespace", "TestService"); + metricsAspect.Before( + this, + "TestMethod", + new object[] { new TestLambdaContext() }, + typeof(MetricsTests), + method, + typeof(void), + new Attribute[] { trigger } + ); // Assert - Assert.Equal("TestNamespace", metrics.GetNamespace()); - Assert.Equal("TestService", metrics.Options.Service); + var metrics = Metrics.Instance; + Assert.False(trigger.IsRaiseOnEmptyMetricsSet); + Assert.False(metrics.Options.RaiseOnEmptyMetrics); + } + + // Helper method for the tests + internal void TestMethod(ILambdaContext context) + { } [Fact] public void When_Constructor_With_Null_Namespace_And_Service_Should_Not_Set() { // Arrange - var metricsMock = Substitute.For(); + Substitute.For(); var powertoolsConfigMock = Substitute.For(); powertoolsConfigMock.MetricsNamespace.Returns((string)null); powertoolsConfigMock.Service.Returns("service_undefined"); // Act - var metrics = new Metrics(powertoolsConfigMock, null, null); + var metrics = new Metrics(powertoolsConfigMock); // Assert Assert.Null(metrics.GetNamespace()); Assert.Null(metrics.Options.Service); } - + [Fact] public void When_AddMetric_With_EmptyKey_Should_ThrowArgumentNullException() { // Arrange - var metricsMock = Substitute.For(); + Substitute.For(); var powertoolsConfigMock = Substitute.For(); IMetrics metrics = new Metrics(powertoolsConfigMock); // Act & Assert var exception = Assert.Throws(() => metrics.AddMetric("", 1.0)); Assert.Equal("key", exception.ParamName); - Assert.Contains("'AddMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", exception.Message); + Assert.Contains("'AddMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", + exception.Message); } [Theory] @@ -93,23 +113,24 @@ public void When_AddMetric_With_InvalidKey_Should_ThrowArgumentNullException(str // Act & Assert var exception = Assert.Throws(() => metrics.AddMetric(key, 1.0)); Assert.Equal("key", exception.ParamName); - Assert.Contains("'AddMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", exception.Message); + Assert.Contains("'AddMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", + exception.Message); } - + [Fact] public void When_SetDefaultDimensions_With_InvalidKeyOrValue_Should_ThrowArgumentNullException() { // Arrange var powertoolsConfigMock = Substitute.For(); IMetrics metrics = new Metrics(powertoolsConfigMock); - + var invalidDimensions = new Dictionary { { "", "value" }, // empty key - { "key", "" }, // empty value + { "key", "" }, // empty value { " ", "value" }, // whitespace key { "key1", " " }, // whitespace value - { "key2", null } // null value + { "key2", null } // null value }; // Act & Assert @@ -118,10 +139,12 @@ public void When_SetDefaultDimensions_With_InvalidKeyOrValue_Should_ThrowArgumen var dimensions = new Dictionary { { dimension.Key, dimension.Value } }; var exception = Assert.Throws(() => metrics.SetDefaultDimensions(dimensions)); Assert.Equal("Key", exception.ParamName); - Assert.Contains("'SetDefaultDimensions' method requires a valid key pair. 'Null' or empty values are not allowed.", exception.Message); + Assert.Contains( + "'SetDefaultDimensions' method requires a valid key pair. 'Null' or empty values are not allowed.", + exception.Message); } } - + [Fact] public void When_PushSingleMetric_With_EmptyName_Should_ThrowArgumentNullException() { @@ -132,7 +155,9 @@ public void When_PushSingleMetric_With_EmptyName_Should_ThrowArgumentNullExcepti // Act & Assert var exception = Assert.Throws(() => metrics.PushSingleMetric("", 1.0, MetricUnit.Count)); Assert.Equal("name", exception.ParamName); - Assert.Contains("'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", exception.Message); + Assert.Contains( + "'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", + exception.Message); } [Theory] @@ -146,8 +171,76 @@ public void When_PushSingleMetric_With_InvalidName_Should_ThrowArgumentNullExcep IMetrics metrics = new Metrics(powertoolsConfigMock); // Act & Assert - var exception = Assert.Throws(() => metrics.PushSingleMetric(name, 1.0, MetricUnit.Count)); + var exception = + Assert.Throws(() => metrics.PushSingleMetric(name, 1.0, MetricUnit.Count)); Assert.Equal("name", exception.ParamName); - Assert.Contains("'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", exception.Message); + Assert.Contains( + "'PushSingleMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.", + exception.Message); + } + + + [Fact] + public void When_ColdStart_Should_Use_DefaultDimensions_From_Options() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "dotnet-powertools-test", + Service = "testService", + DefaultDimensions = new Dictionary + { + { "Environment", "Test" }, + { "Region", "us-east-1" } + } + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + IMetrics metrics = new Metrics(conf, consoleWrapper: consoleWrapper, options: options); + + var context = new TestLambdaContext + { + FunctionName = "TestFunction" + }; + + // Act + metrics.CaptureColdStartMetric(context); + + // Assert + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"Environment\",\"Region\",\"FunctionName\"]]}]},\"Environment\":\"Test\",\"Region\":\"us-east-1\",\"FunctionName\":\"TestFunction\",\"ColdStart\":1}")) + ); + } + + [Fact] + public void When_ColdStart_And_DefaultDimensions_Is_Null_Should_Only_Add_Service_And_FunctionName() + { + // Arrange + var options = new MetricsOptions + { + CaptureColdStart = true, + Namespace = "dotnet-powertools-test", + Service = "testService", + DefaultDimensions = null + }; + + var conf = Substitute.For(); + var consoleWrapper = Substitute.For(); + IMetrics metrics = new Metrics(conf, consoleWrapper: consoleWrapper, options: options); + + var context = new TestLambdaContext + { + FunctionName = "TestFunction" + }; + + // Act + metrics.CaptureColdStartMetric(context); + + // Assert + consoleWrapper.Received(1).WriteLine( + Arg.Is(s => s.Contains("\"CloudWatchMetrics\":[{\"Namespace\":\"dotnet-powertools-test\",\"Metrics\":[{\"Name\":\"ColdStart\",\"Unit\":\"Count\"}],\"Dimensions\":[[\"FunctionName\"]]}]},\"FunctionName\":\"TestFunction\",\"ColdStart\":1}")) + ); } } \ No newline at end of file diff --git a/libraries/tests/Directory.Packages.props b/libraries/tests/Directory.Packages.props index e8c9a16e..516a0e93 100644 --- a/libraries/tests/Directory.Packages.props +++ b/libraries/tests/Directory.Packages.props @@ -6,6 +6,7 @@ + diff --git a/libraries/tests/e2e/functions/core/metrics/Function/src/Function/TestHelper.cs b/libraries/tests/e2e/functions/core/metrics/Function/src/Function/TestHelper.cs index c3434d28..38cb7438 100644 --- a/libraries/tests/e2e/functions/core/metrics/Function/src/Function/TestHelper.cs +++ b/libraries/tests/e2e/functions/core/metrics/Function/src/Function/TestHelper.cs @@ -38,7 +38,7 @@ public static void TestMethod(APIGatewayProxyRequest apigwProxyEvent, ILambdaCon unit: MetricUnit.Count, nameSpace: "Test", service: "Test", - defaultDimensions: new Dictionary + dimensions: new Dictionary { {"FunctionName", context.FunctionName} }); diff --git a/mkdocs.yml b/mkdocs.yml index 4c6617c3..24f86cf6 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -15,7 +15,9 @@ nav: - Workshop 🆕: https://s12d.com/powertools-for-aws-lambda-workshop" target="_blank - Core utilities: - core/logging.md - - core/metrics.md + - Metrics: + - core/metrics.md + - core/metrics-v2.md - core/tracing.md - Utilities: - utilities/parameters.md diff --git a/version.json b/version.json index d52ea67c..8ddbf994 100644 --- a/version.json +++ b/version.json @@ -1,8 +1,9 @@ { "Core": { "Logging": "1.6.4", - "Metrics": "1.8.0", - "Tracing": "1.6.1" + "Metrics": "2.0.0", + "Tracing": "1.6.1", + "Metrics.AspNetCore": "0.1.0", }, "Utilities": { "Parameters": "1.3.0",