Skip to content

fix(metrics): addDimensions() documentation and tests #3964

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
40 changes: 40 additions & 0 deletions docs/features/metrics.md
Original file line number Diff line number Diff line change
Expand Up @@ -502,3 +502,43 @@ When `POWERTOOLS_DEV` is enabled, Metrics uses the global `console` to emit metr
```typescript hl_lines="4-5 12"
--8<-- "examples/snippets/metrics/testingMetrics.ts"
```

## Multiple dimension sets

You can create multiple dimension sets for your metrics using the `addDimensions` or `addDimensionSet` methods. This allows you to aggregate metrics across various dimensions, providing more granular insights into your application.

=== "Creating multiple dimension sets"

```typescript hl_lines="10-25"
--8<-- "examples/snippets/metrics/multiDimensionSets.ts"
```

=== "Example CloudWatch Logs excerpt"

```json
{
"successfulBooking": 1.0,
"_aws": {
"Timestamp": 1592234975665,
"CloudWatchMetrics": [{
"Namespace": "serverlessAirline",
"Dimensions": [
["service", "environment", "region"],
["service", "dimension1", "dimension2"],
["service", "feature", "version"]
],
"Metrics": [{
"Name": "successfulBooking",
"Unit": "Count"
}]
}]
},
"service": "orders",
"environment": "prod",
"region": "us-west-2",
"dimension1": "1",
"dimension2": "2",
"feature": "booking",
"version": "v1"
}
```
28 changes: 28 additions & 0 deletions examples/snippets/metrics/multiDimensionSets.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';

const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
defaultDimensions: { environment: 'prod' },
});

export const handler = async () => {
// Add a single dimension to the default dimension set
metrics.addDimension('region', 'us-west-2');

// Add a new dimension set
metrics.addDimensions({
dimension1: '1',
dimension2: '2',
});

// Add another dimension set (addDimensionSet is an alias for addDimensions)
metrics.addDimensionSet({
feature: 'booking',
version: 'v1',
});

// This will create three dimension sets in the EMF output
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.publishStoredMetrics();
};
94 changes: 89 additions & 5 deletions packages/metrics/src/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
} from './constants.js';
import type {
ConfigServiceInterface,
DimensionSet,
Dimensions,
EmfOutput,
ExtraOptions,
Expand Down Expand Up @@ -200,6 +201,12 @@ class Metrics extends Utility implements MetricsInterface {
*/
private storedMetrics: StoredMetrics = {};

/**
* Storage for dimension sets
* @default []
*/
private dimensionSets: DimensionSet[] = [];

/**
* Whether to disable metrics
*/
Expand Down Expand Up @@ -255,23 +262,90 @@ class Metrics extends Utility implements MetricsInterface {
}

/**
* Add multiple dimensions to the metrics.
* Add multiple dimensions to the metrics as a new dimension set.
*
* This method is useful when you want to add multiple dimensions to the metrics at once.
* This method creates a new dimension set that will be included in the EMF output.
* Invalid dimension values are skipped and a warning is logged.
*
* When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of
* dimension is useful when you want to add request-specific dimensions to your metrics. If you want to add dimensions that are
* included in all metrics, use the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* // Add a single dimension
* metrics.addDimension('environment', 'prod');
*
* // Add a new dimension set
* metrics.addDimensions({
* dimension1: "1",
* dimension2: "2"
* });
*
* // This will create two dimension sets in the EMF output:
* // [["service", "environment"]] and [["service", "dimension1", "dimension2"]]
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* ```
*
* @param dimensions - An object with key-value pairs of dimensions
*/
public addDimensions(dimensions: Dimensions): void {
const dimensionSet: string[] = [];

// Add default dimensions to the set
for (const name of Object.keys(this.defaultDimensions)) {
dimensionSet.push(name);
}

// Add new dimensions to both the dimension set and the dimensions object
for (const [name, value] of Object.entries(dimensions)) {
this.addDimension(name, value);
if (!value) {
this.#logger.warn(
`The dimension ${name} doesn't meet the requirements and won't be added. Ensure the dimension name and value are non empty strings`
);
continue;
}

if (MAX_DIMENSION_COUNT <= this.getCurrentDimensionsCount() + 1) {
throw new RangeError(
`The number of metric dimensions must be lower than ${MAX_DIMENSION_COUNT}`
);
}

// Add to dimensions object for value storage
this.dimensions[name] = value;

// Add to dimension set if not already included
if (!dimensionSet.includes(name)) {
dimensionSet.push(name);
}
}

// Only add the dimension set if it has dimensions beyond the defaults
if (dimensionSet.length > Object.keys(this.defaultDimensions).length) {
this.dimensionSets.push(dimensionSet);
}
}

/**
* Add a dimension set to metrics.
*
* This is an alias for {@link Metrics.addDimensions | `addDimensions()`} for consistency with other Powertools for AWS Lambda implementations.
*
* @param dimensions - An object with key-value pairs of dimensions
*/
public addDimensionSet(dimensions: Dimensions): void {
this.addDimensions(dimensions);
}

/**
* A metadata key-value pair to be included with metrics.
*
Expand Down Expand Up @@ -447,6 +521,7 @@ class Metrics extends Utility implements MetricsInterface {
*/
public clearDimensions(): void {
this.dimensions = {};
this.dimensionSets = [];
}

/**
Expand Down Expand Up @@ -692,20 +767,29 @@ class Metrics extends Utility implements MetricsInterface {
{}
);

const dimensionNames = [
// Create the default dimension set from default dimensions and current dimensions
const defaultDimensionNames = [
...new Set([
...Object.keys(this.defaultDimensions),
...Object.keys(this.dimensions),
]),
];

// Prepare all dimension sets for the EMF output
const allDimensionSets: DimensionSet[] = [defaultDimensionNames];

// Add any additional dimension sets created via addDimensions()
if (this.dimensionSets.length > 0) {
allDimensionSets.push(...this.dimensionSets);
}

return {
_aws: {
Timestamp: this.#timestamp ?? new Date().getTime(),
CloudWatchMetrics: [
{
Namespace: this.namespace || DEFAULT_NAMESPACE,
Dimensions: [dimensionNames],
Dimensions: allDimensionSets as [string[]],
Metrics: metricDefinitions,
},
],
Expand Down
6 changes: 6 additions & 0 deletions packages/metrics/src/types/Metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ import type { ConfigServiceInterface } from './ConfigServiceInterface.js';
*/
type Dimensions = Record<string, string>;

/**
* A dimension set is an array of dimension names
*/
type DimensionSet = string[];

/**
* Options to configure the Metrics class.
*
Expand Down Expand Up @@ -541,6 +546,7 @@ interface MetricsInterface {
export type {
MetricsOptions,
Dimensions,
DimensionSet,
EmfOutput,
ExtraOptions,
StoredMetrics,
Expand Down
1 change: 1 addition & 0 deletions packages/metrics/src/types/index.ts
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a bit unsure about the changes in this entire file. It seems that we re-declared all the types that were previously in the packages/metrics/src/types/Metrics.ts file for no apparent reason.

This seems to break the compilation (see failed CI) - can we revert?

Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export type {
MetricsOptions,
Dimensions,
DimensionSet,
EmfOutput,
ExtraOptions,
StoredMetrics,
Expand Down
Loading
Loading