powertools-lambda-dotnet icon indicating copy to clipboard operation
powertools-lambda-dotnet copied to clipboard

Feature request: Add multiple dimensets to the same Metrics instance

Open hjgraca opened this issue 9 months ago • 0 comments

Use case

Add Support for multiple dimension sets for the same Metrics instance This feature would allow users to gain more granular insights and comprehensive views of their applications by creating aggregating metrics across various dimensions.

Reference: https://github.com/aws-powertools/powertools-lambda-python/issues/6198

Solution/User Experience

Add a new AddDimensions() method to the Metrics class that accepts a List<DimensionSet>


    /// <summary>
    ///     Adds multiple dimensions to memory.
    /// </summary>
    /// <param name="dimensions">Variable number of key-value pairs for dimensions.</param>
    public static void AddDimensions(params (string key, string value)[] dimensions)
    {
        if (dimensions == null || dimensions.Length == 0)
            return;
            
        foreach (var (key, value) in dimensions)
        {
            Instance.AddDimension(key, value);
        }
    }

Example:

Metrics.AddDimensions(("environment", "prod"), ("region", "us-west-2"));
Metrics.AddDimensions(("environment", "prod"));
Metrics.AddDimensions(("region", "us-west-2"));

Metrics.AddMetric("ExecutionTime", DateTime.Now, Unit.MILLISECONDS);

This will output

{
  "_aws": {
    "Timestamp": 1742467748165,
    "CloudWatchMetrics": [
      {
        "Namespace": "HelloWorldFunction",
        "Metrics": [
          {
            "Name": "ExecutionTime",
            "Unit": "Milliseconds"
          }
        ],
        "Dimensions": [
          [
            "Service"
          ],
          [
            "environment",
            "region"
          ],
          [
            "environment"
          ],
          [
            "region"
          ]
        ]
      }
    ]
  },
  "function_request_id": "c0e5afc1-c033-4aa6-9b13-26bfc324874b",
  "ExecutionTime": 0.0,
  "environment": "prod",
  "functionVersion": "$LATEST",
  "Service": "Powertools",
  "logStreamId": "$LATEST",
  "region": "us-west-2",
  "executionEnvironment": "AWS_Lambda_java17"
}

Notes:

  • 'AddDimension': will add a single dimension to the position to when it was called and will not update other dimensions. This is to keep the current behaviour as is.
  • 'Overriding values': override the latest set value for the same dimension key
    • Duplicate dimension sets are removed before being added to the end of the collection.
    • This ensures only latest dimension value is used as a target member on the root EMF node.
    • This operation is O(n^2), but acceptable given sets are capped at 30 dimensions

Alternative solutions


Acknowledgment

hjgraca avatar Apr 08 '25 14:04 hjgraca