Socket
Socket
Sign inDemoInstall

@aws-lambda-powertools/metrics

Package Overview
Dependencies
Maintainers
0
Versions
94
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@aws-lambda-powertools/metrics - npm Package Compare versions

Comparing version 2.8.0 to 2.9.0

8

lib/cjs/config/EnvironmentVariablesService.d.ts
import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';
import type { ConfigServiceInterface } from '../types/ConfigServiceInterface.js';
/**
* Class EnvironmentVariablesService
*
* This class is used to return environment variables that are available in the runtime of
* the current Lambda invocation.
*/
declare class EnvironmentVariablesService extends CommonEnvironmentVariablesService implements ConfigServiceInterface {
private namespaceVariable;
/**
* It returns the value of the POWERTOOLS_METRICS_NAMESPACE environment variable.
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/

@@ -8,0 +14,0 @@ getNamespace(): string;

@@ -5,6 +5,12 @@ "use strict";

const commons_1 = require("@aws-lambda-powertools/commons");
/**
* Class EnvironmentVariablesService
*
* This class is used to return environment variables that are available in the runtime of
* the current Lambda invocation.
*/
class EnvironmentVariablesService extends commons_1.EnvironmentVariablesService {
namespaceVariable = 'POWERTOOLS_METRICS_NAMESPACE';
/**
* It returns the value of the POWERTOOLS_METRICS_NAMESPACE environment variable.
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/

@@ -11,0 +17,0 @@ getNamespace() {

@@ -0,6 +1,27 @@

/**
* The dimension key for the cold start metric.
*/
declare const COLD_START_METRIC = "ColdStart";
/**
* The default namespace for metrics.
*/
declare const DEFAULT_NAMESPACE = "default_namespace";
/**
* The maximum number of metrics that can be emitted in a single EMF blob.
*/
declare const MAX_METRICS_SIZE = 100;
/**
* The maximum number of metric values that can be emitted in a single metric.
*/
declare const MAX_METRIC_VALUES_SIZE = 100;
/**
* The maximum number of dimensions that can be added to a metric (0-indexed).
*/
declare const MAX_DIMENSION_COUNT = 29;
/**
* The unit of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Unit | Amazon CloudWatch Units}
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html | Amazon CloudWatch MetricDatum}
*/
declare const MetricUnit: {

@@ -35,2 +56,7 @@ readonly Seconds: "Seconds";

};
/**
* The resolution of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | Amazon CloudWatch Resolution}
*/
declare const MetricResolution: {

@@ -37,0 +63,0 @@ readonly Standard: 60;

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MetricResolution = exports.MetricUnit = exports.MAX_DIMENSION_COUNT = exports.MAX_METRIC_VALUES_SIZE = exports.MAX_METRICS_SIZE = exports.DEFAULT_NAMESPACE = exports.COLD_START_METRIC = void 0;
/**
* The dimension key for the cold start metric.
*/
const COLD_START_METRIC = 'ColdStart';
exports.COLD_START_METRIC = COLD_START_METRIC;
/**
* The default namespace for metrics.
*/
const DEFAULT_NAMESPACE = 'default_namespace';
exports.DEFAULT_NAMESPACE = DEFAULT_NAMESPACE;
/**
* The maximum number of metrics that can be emitted in a single EMF blob.
*/
const MAX_METRICS_SIZE = 100;
exports.MAX_METRICS_SIZE = MAX_METRICS_SIZE;
/**
* The maximum number of metric values that can be emitted in a single metric.
*/
const MAX_METRIC_VALUES_SIZE = 100;
exports.MAX_METRIC_VALUES_SIZE = MAX_METRIC_VALUES_SIZE;
/**
* The maximum number of dimensions that can be added to a metric (0-indexed).
*/
const MAX_DIMENSION_COUNT = 29;
exports.MAX_DIMENSION_COUNT = MAX_DIMENSION_COUNT;
/**
* The unit of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Unit | Amazon CloudWatch Units}
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html | Amazon CloudWatch MetricDatum}
*/
const MetricUnit = {

@@ -44,2 +65,7 @@ Seconds: 'Seconds',

exports.MetricUnit = MetricUnit;
/**
* The resolution of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | Amazon CloudWatch Resolution}
*/
const MetricResolution = {

@@ -46,0 +72,0 @@ Standard: 60,

446

lib/cjs/Metrics.d.ts

@@ -5,60 +5,58 @@ import { Utility } from '@aws-lambda-powertools/commons';

/**
* ## Intro
* Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF).
* The Metrics utility creates custom metrics asynchronously by logging metrics to standard output following {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*
* These metrics can be visualized through Amazon CloudWatch Console.
*
* ## Key features
* * Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob)
* * Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc)
* * Metrics are created asynchronously by CloudWatch service, no custom stacks needed
* * Context manager to create a one off metric with a different dimension
* **Key features**
* * Aggregating up to 100 metrics using a single CloudWatch EMF 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.
* * Creating a one-off metric with different dimensions.
*
* ## Usage
* After initializing the Metrics class, you can add metrics using the {@link Metrics.addMetric | `addMetric()`} method.
* The metrics are stored in a buffer and are flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
* Each metric can have dimensions and metadata added to it.
*
* ### Functions usage with middleware
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* const lambdaHandler = async (_event: unknown, _context: unknown) => {
* ...
* export const handler = async (event: { requestId: string }) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* ```
*
* ### Object oriented way with decorator
* If you don't want to manually flush the metrics, you can use the {@link Metrics.logMetrics | `logMetrics()`} decorator or
* the Middy.js middleware to automatically flush the metrics after the handler function returns or throws an error.
*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the {@link Metrics.logMetrics} decorator to automatically:
* * capture a `ColdStart` metric
* * flush buffered metrics
* * throw on empty metrics
* In addition to this, the decorator and middleware can also be configured to capture a `ColdStart` metric and
* set default dimensions for all metrics.
*
* **Class method decorator**
*
* @example
*
* ```typescript
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* // Decorate your handler with the logMetrics decorator
* ⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
* public handler(_event: unknown, _context: unknown): Promise<void> {
* // ...
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* // ...
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -71,5 +69,7 @@ * }

*
* ### Standard function
* Note that decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard.
* The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the [`experimentalDecorators` flag](https://www.typescriptlang.org/tsconfig/#experimentalDecorators)
* set to `true` in the `tsconfig.json` file.
*
* If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics.
* **Middy.js middleware**
*

@@ -80,11 +80,21 @@ * @example

* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* metrics.publishStoredMetrics();
* };
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* The `logMetrics()` middleware is compatible with `@middy/core@3.x` and above.
*
*/

@@ -152,9 +162,12 @@ declare class Metrics extends Utility implements MetricsInterface {

/**
* Add a dimension to the metrics.
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics.
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name The name of the dimension
* @param value The value of the dimension
* 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.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/

@@ -165,16 +178,37 @@ addDimension(name: string, value: string): void;

*
* A dimension is a key-value pair that is used to group metrics.
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* @param dimensions A key-value pair of dimensions
* 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.
*
* @param dimensions - An object with key-value pairs of dimensions
*/
addDimensions(dimensions: {
[key: string]: string;
}): void;
addDimensions(dimensions: Dimensions): void;
/**
* A high-cardinality data part of your Metrics log.
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* @param key The key of the metadata
* @param value The value of the metadata
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/

@@ -185,8 +219,13 @@ addMetadata(key: string, value: string): void;

*
* By default, metrics are buffered and flushed at the end of the Lambda invocation
* or when calling {@link Metrics.publishStoredMetrics}.
* By default, metrics are buffered and flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link Metrics.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in {@link MetricUnit}.
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example

@@ -196,35 +235,76 @@ * ```typescript

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* Optionally, you can specify the metric resolution, which can be either `High` or `Standard`.
* By default, metrics are published with a resolution of `Standard`, click [here](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition)
* to learn more about metric resolutions.
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
/**
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* By using this method, the metric will be emitted immediately without you having to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example
* ```typescript
* import { Metrics, MetricUnit, MetricResolution } from '@aws-lambda-powertools/metrics';
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1, MetricResolution.High);
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };
* ```
*/
captureColdStartMetric(): void;
/**
* Clear all previously set default dimensions.
*
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution
* This will remove all default dimensions set by the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
clearDefaultDimensions(): void;
/**
* Create a singleMetric to capture cold start.
* Clear all the dimensions added to the Metrics instance via {@link Metrics.addDimension | `addDimension()`} or {@link Metrics.addDimensions | `addDimensions()`}.
*
* If it's a cold start invocation, this feature will:
* * Create a separate EMF blob that contains a single metric named ColdStart
* * Add function_name and service dimensions
* These dimensions are normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions,
* as well as avoiding potential data loss from metrics not being published for other reasons.
* This method does not clear the default dimensions set via {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*

@@ -235,20 +315,26 @@ * @example

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
captureColdStartMetric(): void;
/**
* Clear all default dimensions.
*/
clearDefaultDimensions(): void;
/**
* Clear all dimensions.
*/
clearDimensions(): void;
/**
* Clear all metadata.
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -258,19 +344,32 @@ clearMetadata(): void;

* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearMetrics(): void;
/**
* A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* @metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: unknown, __context: unknown): Promise<void> {
* // ...
* ⁣@metrics.logMetrics({ captureColdStartMetric: true })
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -283,18 +382,28 @@ * }

*
* @param options - The options to configure the logMetrics decorator
* You can configure the decorator with the following options:
* - `captureColdStartMetric` - Whether to capture a `ColdStart` metric
* - `defaultDimensions` - Default dimensions to add to all metrics
* - `throwOnEmptyMetrics` - Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/
logMetrics(options?: ExtraOptions): HandlerMethodDecorator;
/**
* Synchronous function to actually publish your metrics. (Not needed if using logMetrics decorator).
* It will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation.
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
*
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();

@@ -306,10 +415,12 @@ * };

/**
* Function to create a new metric object compliant with the EMF (Embedded Metric Format) schema which
* includes the metric name, unit, and optionally storage resolution.
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The function will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch
* logs and processed automatically for metrics creation.
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* @returns metrics as JSON object compliant EMF Schema Specification
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html for more details
* The object is then emitted to standard output, which in AWS Lambda is picked up by CloudWatch logs and processed asynchronously.
*/

@@ -320,48 +431,90 @@ serializeMetrics(): EmfOutput;

*
* @param dimensions The default dimensions to be added to all metrics.
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/
setDefaultDimensions(dimensions: Dimensions | undefined): void;
/**
* Sets the function name to be added to the metric.
* Set the function name to be added to each metric as a dimension.
*
* @param value The function name to be added to the metric.
*/
setFunctionName(value: string): void;
/**
* CloudWatch EMF uses the same dimensions across all your metrics. Use singleMetric if you have a metric that should have different dimensions.
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* You don't need to call publishStoredMetrics() after calling addMetric for a singleMetrics, they will be flushed directly.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* ```typescript
* const singleMetric = metrics.singleMetric();
* singleMetric.addDimension('InnerDimension', 'true');
* singleMetric.addMetric('single-metric', MetricUnit.Percent, 50);
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @returns the Metrics
* @param name - The function name
*/
singleMetric(): Metrics;
setFunctionName(name: string): void;
/**
* Throw an Error if the metrics buffer is empty.
* Set the flag to throw an error if no metrics are emitted.
*
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
setThrowOnEmptyMetrics(enabled: boolean): void;
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.throwOnEmptyMetrics();
* metrics.publishStoredMetrics(); // will throw since no metrics added.
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('coldStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*/
singleMetric(): Metrics;
/**
* @deprecated Use {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`} instead.
*/
throwOnEmptyMetrics(): void;
/**
* Gets the current number of dimensions stored.
*
* @returns the number of dimensions currently stored
* Gets the current number of dimensions count.
*/

@@ -386,12 +539,11 @@ private getCurrentDimensionsCount;

*
* @param name The name of the metric
* @param unit The unit of the metric
* @param name - The name of the metric
* @param unit - The unit of the metric
*/
private isNewMetric;
/**
* Initialize the console property as an instance of the internal version of Console() class (PR #748)
* Initialize the console property as an instance of the internal version of `Console()` class (PR #748)
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
*
* @private
* @returns {void}
*/

@@ -412,3 +564,3 @@ private setConsole;

*
* @param namespace The namespace to be used
* @param namespace - The namespace to be used
*/

@@ -421,3 +573,3 @@ private setNamespace;

*
* @param options The options to be used
* @param options - The options to be used
*/

@@ -428,3 +580,3 @@ private setOptions;

*
* @param service The service to be used
* @param service - The service to be used
*/

@@ -436,8 +588,8 @@ private setService;

* If the buffer is full, or the metric reaches the maximum number of values,
* the buffer is published to stdout.
* the metrics are flushed to stdout.
*
* @param name The name of the metric to store
* @param unit The unit of the metric to store
* @param value The value of the metric to store
* @param resolution The resolution of the metric to store
* @param name - The name of the metric to store
* @param unit - The unit of the metric to store
* @param value - The value of the metric to store
* @param resolution - The resolution of the metric to store
*/

@@ -444,0 +596,0 @@ private storeMetric;

@@ -9,60 +9,58 @@ "use strict";

/**
* ## Intro
* Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF).
* The Metrics utility creates custom metrics asynchronously by logging metrics to standard output following {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*
* These metrics can be visualized through Amazon CloudWatch Console.
*
* ## Key features
* * Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob)
* * Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc)
* * Metrics are created asynchronously by CloudWatch service, no custom stacks needed
* * Context manager to create a one off metric with a different dimension
* **Key features**
* * Aggregating up to 100 metrics using a single CloudWatch EMF 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.
* * Creating a one-off metric with different dimensions.
*
* ## Usage
* After initializing the Metrics class, you can add metrics using the {@link Metrics.addMetric | `addMetric()`} method.
* The metrics are stored in a buffer and are flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
* Each metric can have dimensions and metadata added to it.
*
* ### Functions usage with middleware
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* const lambdaHandler = async (_event: unknown, _context: unknown) => {
* ...
* export const handler = async (event: { requestId: string }) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* ```
*
* ### Object oriented way with decorator
* If you don't want to manually flush the metrics, you can use the {@link Metrics.logMetrics | `logMetrics()`} decorator or
* the Middy.js middleware to automatically flush the metrics after the handler function returns or throws an error.
*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the {@link Metrics.logMetrics} decorator to automatically:
* * capture a `ColdStart` metric
* * flush buffered metrics
* * throw on empty metrics
* In addition to this, the decorator and middleware can also be configured to capture a `ColdStart` metric and
* set default dimensions for all metrics.
*
* **Class method decorator**
*
* @example
*
* ```typescript
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* // Decorate your handler with the logMetrics decorator
* ⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
* public handler(_event: unknown, _context: unknown): Promise<void> {
* // ...
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* // ...
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -75,5 +73,7 @@ * }

*
* ### Standard function
* Note that decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard.
* The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the [`experimentalDecorators` flag](https://www.typescriptlang.org/tsconfig/#experimentalDecorators)
* set to `true` in the `tsconfig.json` file.
*
* If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics.
* **Middy.js middleware**
*

@@ -84,11 +84,21 @@ * @example

* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* metrics.publishStoredMetrics();
* };
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* The `logMetrics()` middleware is compatible with `@middy/core@3.x` and above.
*
*/

@@ -160,9 +170,12 @@ class Metrics extends commons_1.Utility {

/**
* Add a dimension to the metrics.
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics.
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name The name of the dimension
* @param value The value of the dimension
* 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.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/

@@ -178,5 +191,9 @@ addDimension(name, value) {

*
* A dimension is a key-value pair that is used to group metrics.
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* @param dimensions A key-value pair of dimensions
* 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.
*
* @param dimensions - An object with key-value pairs of dimensions
*/

@@ -194,8 +211,27 @@ addDimensions(dimensions) {

/**
* A high-cardinality data part of your Metrics log.
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* @param key The key of the metadata
* @param value The value of the metadata
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/

@@ -208,8 +244,13 @@ addMetadata(key, value) {

*
* By default, metrics are buffered and flushed at the end of the Lambda invocation
* or when calling {@link Metrics.publishStoredMetrics}.
* By default, metrics are buffered and flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link Metrics.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in {@link MetricUnit}.
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example

@@ -219,24 +260,17 @@ * ```typescript

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* Optionally, you can specify the metric resolution, which can be either `High` or `Standard`.
* By default, metrics are published with a resolution of `Standard`, click [here](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition)
* to learn more about metric resolutions.
*
* @example
* ```typescript
* import { Metrics, MetricUnit, MetricResolution } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1, MetricResolution.High);
* ```
*
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/

@@ -249,11 +283,12 @@ addMetric(name, unit, value, resolution = constants_js_1.MetricResolution.Standard) {

/**
* Create a singleMetric to capture cold start.
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* If it's a cold start invocation, this feature will:
* * Create a separate EMF blob that contains a single metric named ColdStart
* * Add function_name and service dimensions
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions,
* as well as avoiding potential data loss from metrics not being published for other reasons.
* By using this method, the metric will be emitted immediately without you having to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example

@@ -263,6 +298,9 @@ * ```typescript

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };

@@ -286,3 +324,22 @@ * ```

/**
* Clear all default dimensions.
* Clear all previously set default dimensions.
*
* This will remove all default dimensions set by the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/

@@ -293,3 +350,29 @@ clearDefaultDimensions() {

/**
* Clear all dimensions.
* Clear all the dimensions added to the Metrics instance via {@link Metrics.addDimension | `addDimension()`} or {@link Metrics.addDimensions | `addDimensions()`}.
*
* These dimensions are normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This method does not clear the default dimensions set via {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -300,3 +383,8 @@ clearDimensions() {

/**
* Clear all metadata.
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -308,2 +396,6 @@ clearMetadata() {

* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -314,16 +406,25 @@ clearMetrics() {

/**
* A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* @metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: unknown, __context: unknown): Promise<void> {
* // ...
* ⁣@metrics.logMetrics({ captureColdStartMetric: true })
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -336,3 +437,8 @@ * }

*
* @param options - The options to configure the logMetrics decorator
* You can configure the decorator with the following options:
* - `captureColdStartMetric` - Whether to capture a `ColdStart` metric
* - `defaultDimensions` - Default dimensions to add to all metrics
* - `throwOnEmptyMetrics` - Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/

@@ -342,3 +448,3 @@ logMetrics(options = {}) {

if (throwOnEmptyMetrics) {
this.throwOnEmptyMetrics();
this.setThrowOnEmptyMetrics(throwOnEmptyMetrics);
}

@@ -371,14 +477,19 @@ if (defaultDimensions !== undefined) {

/**
* Synchronous function to actually publish your metrics. (Not needed if using logMetrics decorator).
* It will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation.
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
*
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();

@@ -401,10 +512,12 @@ * };

/**
* Function to create a new metric object compliant with the EMF (Embedded Metric Format) schema which
* includes the metric name, unit, and optionally storage resolution.
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The function will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch
* logs and processed automatically for metrics creation.
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* @returns metrics as JSON object compliant EMF Schema Specification
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html for more details
* The object is then emitted to standard output, which in AWS Lambda is picked up by CloudWatch logs and processed asynchronously.
*/

@@ -457,3 +570,22 @@ serializeMetrics() {

*
* @param dimensions The default dimensions to be added to all metrics.
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/

@@ -471,23 +603,63 @@ setDefaultDimensions(dimensions) {

/**
* Sets the function name to be added to the metric.
* Set the function name to be added to each metric as a dimension.
*
* @param value The function name to be added to the metric.
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @param name - The function name
*/
setFunctionName(value) {
this.functionName = value;
setFunctionName(name) {
this.functionName = name;
}
/**
* CloudWatch EMF uses the same dimensions across all your metrics. Use singleMetric if you have a metric that should have different dimensions.
* Set the flag to throw an error if no metrics are emitted.
*
* You don't need to call publishStoredMetrics() after calling addMetric for a singleMetrics, they will be flushed directly.
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
setThrowOnEmptyMetrics(enabled) {
this.shouldThrowOnEmptyMetrics = enabled;
}
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
*
* ```typescript
* const singleMetric = metrics.singleMetric();
* singleMetric.addDimension('InnerDimension', 'true');
* singleMetric.addMetric('single-metric', MetricUnit.Percent, 50);
* ```
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* @returns the Metrics
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('coldStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*/

@@ -503,16 +675,3 @@ singleMetric() {

/**
* Throw an Error if the metrics buffer is empty.
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.throwOnEmptyMetrics();
* metrics.publishStoredMetrics(); // will throw since no metrics added.
* };
* ```
* @deprecated Use {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`} instead.
*/

@@ -523,5 +682,3 @@ throwOnEmptyMetrics() {

/**
* Gets the current number of dimensions stored.
*
* @returns the number of dimensions currently stored
* Gets the current number of dimensions count.
*/

@@ -553,4 +710,4 @@ getCurrentDimensionsCount() {

*
* @param name The name of the metric
* @param unit The unit of the metric
* @param name - The name of the metric
* @param unit - The unit of the metric
*/

@@ -568,7 +725,6 @@ isNewMetric(name, unit) {

/**
* Initialize the console property as an instance of the internal version of Console() class (PR #748)
* Initialize the console property as an instance of the internal version of `Console()` class (PR #748)
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
*
* @private
* @returns {void}
*/

@@ -605,3 +761,3 @@ setConsole() {

*
* @param namespace The namespace to be used
* @param namespace - The namespace to be used
*/

@@ -618,3 +774,3 @@ setNamespace(namespace) {

*
* @param options The options to be used
* @param options - The options to be used
*/

@@ -635,3 +791,3 @@ setOptions(options) {

*
* @param service The service to be used
* @param service - The service to be used
*/

@@ -651,8 +807,8 @@ setService(service) {

* If the buffer is full, or the metric reaches the maximum number of values,
* the buffer is published to stdout.
* the metrics are flushed to stdout.
*
* @param name The name of the metric to store
* @param unit The unit of the metric to store
* @param value The value of the metric to store
* @param resolution The resolution of the metric to store
* @param name - The name of the metric to store
* @param unit - The unit of the metric to store
* @param value - The value of the metric to store
* @param resolution - The resolution of the metric to store
*/

@@ -659,0 +815,0 @@ storeMetric(name, unit, value, resolution) {

@@ -5,27 +5,36 @@ import type { MiddlewareLikeObj } from '@aws-lambda-powertools/commons/types';

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
* A Middy.js middleware automating capture of Amazon CloudWatch metrics.
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
* This middleware is compatible with `@middy/core@3.x` and above.
*
* The middleware automatically flushes metrics after the handler function returns or throws an error,
* so you don't need to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} manually.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* const lambdaHandler = async (_event: any, _context: any) => {
* ...
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* You can configure the middleware with the following options:
* - `captureColdStartMetric`: Whether to capture a `ColdStart` metric
* - `defaultDimensions`: Default dimensions to add to all metrics
* - `throwOnEmptyMetrics`: Whether to throw an error if no metrics are emitted
*
* @param target - The Metrics instance to use for emitting metrics
* @param options - (_optional_) Options for the middleware
* @param options - Options to configure the middleware, see {@link ExtraOptions}
*/

@@ -32,0 +41,0 @@ declare const logMetrics: (target: Metrics | Metrics[], options?: ExtraOptions) => MiddlewareLikeObj;

@@ -6,27 +6,36 @@ "use strict";

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
* A Middy.js middleware automating capture of Amazon CloudWatch metrics.
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
* This middleware is compatible with `@middy/core@3.x` and above.
*
* The middleware automatically flushes metrics after the handler function returns or throws an error,
* so you don't need to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} manually.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* const lambdaHandler = async (_event: any, _context: any) => {
* ...
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* You can configure the middleware with the following options:
* - `captureColdStartMetric`: Whether to capture a `ColdStart` metric
* - `defaultDimensions`: Default dimensions to add to all metrics
* - `throwOnEmptyMetrics`: Whether to throw an error if no metrics are emitted
*
* @param target - The Metrics instance to use for emitting metrics
* @param options - (_optional_) Options for the middleware
* @param options - Options to configure the middleware, see {@link ExtraOptions}
*/

@@ -51,3 +60,3 @@ const logMetrics = (target, options = {}) => {

if (throwOnEmptyMetrics) {
metrics.throwOnEmptyMetrics();
metrics.setThrowOnEmptyMetrics(throwOnEmptyMetrics);
}

@@ -54,0 +63,0 @@ if (defaultDimensions !== undefined) {

@@ -11,5 +11,3 @@ import type { ConfigServiceInterface as ConfigServiceBaseInterface } from '@aws-lambda-powertools/commons/types';

/**
* It returns the value of the POWERTOOLS_METRICS_NAMESPACE environment variable.
*
* @returns {string}
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/

@@ -16,0 +14,0 @@ getNamespace(): string;

@@ -1,4 +0,3 @@

export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, } from './Metrics.js';
export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, MetricsInterface, } from './Metrics.js';
export type { ConfigServiceInterface } from './ConfigServiceInterface.js';
export type { MetricsInterface } from './MetricsInterface.js';
//# sourceMappingURL=index.d.ts.map

@@ -1,11 +0,60 @@

import type { MetricResolution as MetricResolutionList, MetricUnit as MetricUnitList } from '../constants.js';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { MetricResolution as MetricResolutions, MetricUnit as MetricUnits } from '../constants.js';
import type { ConfigServiceInterface } from './ConfigServiceInterface.js';
/**
* A set of key-value pairs that define the dimensions of a metric.
*/
type Dimensions = Record<string, string>;
/**
* Options to configure the Metrics class.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* singleMetric: true,
* });
* ```
*/
type MetricsOptions = {
/**
* A custom configuration service to use for retrieving configuration values.
*
* @default undefined
*/
customConfigService?: ConfigServiceInterface;
/**
* The namespace to use for all metrics.
*
* @default undefined
*/
namespace?: string;
/**
* The service name to use for all metrics.
*
* @default undefined
*/
serviceName?: string;
/**
* Whether to configure the Metrics class to emit a single metric as soon as it is added.
*
* @default false
* @see {@link MetricsInterface.singleMetric | `singleMetric()`}
*/
singleMetric?: boolean;
/**
* The default dimensions to add to all metrics.
*
* @default {}
* @see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}
*/
defaultDimensions?: Dimensions;
};
/**
* The output of the {@link MetricsInterface.serializeMetrics | `serializeMetrics()`} method,
* compliant with the {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*/
type EmfOutput = Readonly<{

@@ -23,27 +72,42 @@ [key: string]: string | number | object;

/**
* Options for the metrics decorator
*
* Usage:
*
* ```typescript
*
* const metricsOptions: MetricsOptions = {
* throwOnEmptyMetrics: true,
* defaultDimensions: {'environment': 'dev'},
* captureColdStartMetric: true,
* }
*
* @metrics.logMetric(metricsOptions)
* public handler(event: any, context: any, callback: any) {
* // ...
* }
* ```
* Options to customize the behavior of the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator or Middy.js middleware.
*/
type ExtraOptions = {
/**
* Whether to throw an error if no metrics are emitted.
*
* @default false
* @see {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}
*/
throwOnEmptyMetrics?: boolean;
/**
* Default dimensions to add to all metrics.
*
* @default {}
* @see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}
*/
defaultDimensions?: Dimensions;
/**
* Whether to capture a `ColdStart` metric.
*
* @default false
* @see {@link MetricsInterface.captureColdStartMetric | `captureColdStartMetric()`}
*/
captureColdStartMetric?: boolean;
};
type MetricResolution = (typeof MetricResolutionList)[keyof typeof MetricResolutionList];
type MetricUnit = (typeof MetricUnitList)[keyof typeof MetricUnitList];
/**
* A list of possible metric resolutions.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | Amazon CloudWatch Resolution}
*/
type MetricResolution = (typeof MetricResolutions)[keyof typeof MetricResolutions];
/**
* A list of possible metric units.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Unit | Amazon CloudWatch Units}
*/
type MetricUnit = (typeof MetricUnits)[keyof typeof MetricUnits];
/**
* Data structure to store a metric that has been added to the Metrics class.
*/
type StoredMetric = {

@@ -55,3 +119,9 @@ name: string;

};
/**
* A map of stored metrics, where the key is the metric name and the value is the stored metric.
*/
type StoredMetrics = Record<string, StoredMetric>;
/**
* A definition of a metric that can be added to the Metrics class.
*/
type MetricDefinition = {

@@ -62,3 +132,350 @@ Name: string;

};
export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, };
interface MetricsInterface {
/**
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* When calling the {@link MetricsInterface.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 MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/
addDimension(name: string, value: string): void;
/**
* Add multiple dimensions to the metrics.
*
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* When calling the {@link MetricsInterface.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 MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @param dimensions - An object with key-value pairs of dimensions
*/
addDimensions(dimensions: Dimensions): void;
/**
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/
addMetadata(key: string, value: string): void;
/**
* Add a metric to the metrics buffer.
*
* By default, metrics are buffered and flushed when calling {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema. In AWS Lambda, the logs are
* automatically picked up by CloudWatch logs and processed asynchronously.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
/**
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* By using this method, the metric will be emitted immediately without you having to call {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };
* ```
*/
captureColdStartMetric(): void;
/**
* Clear all previously set default dimensions.
*
* This will remove all default dimensions set by the {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/
clearDefaultDimensions(): void;
/**
* Clear all the dimensions added to the Metrics instance via {@link MetricsInterface.addDimension | `addDimension()`} or {@link MetricsInterface.addDimensions | `addDimensions()`}.
*
* These dimensions are normally cleared when calling {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This method does not clear the default dimensions set via {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearDimensions(): void;
/**
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearMetadata(): void;
/**
* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearMetrics(): void;
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link MetricsInterface.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link MetricsInterface.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* ⁣@metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: unknown, _context: unknown) {
* // ...
* }
* }
*
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
* You can configure the decorator with the following options:
* - `captureColdStartMetric`: Whether to capture a `ColdStart` metric
* - `defaultDimensions`: Default dimensions to add to all metrics
* - `throwOnEmptyMetrics`: Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/
logMetrics(options?: ExtraOptions): HandlerMethodDecorator;
/**
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*/
publishStoredMetrics(): void;
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* The serialized object is returned for later use.
*
* This is primarily an internal method used by the Metrics class, but it is exposed for advanced use cases.
*/
serializeMetrics(): EmfOutput;
/**
* Set default dimensions that will be added to all metrics.
*
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/
setDefaultDimensions(dimensions: Dimensions | undefined): void;
/**
* Set the function name to be added to each metric as a dimension.
*
* When using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @param name - The function name
*/
setFunctionName(name: string): void;
/**
* Set the flag to throw an error if no metrics are emitted.
*
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
setThrowOnEmptyMetrics(enabled: boolean): void;
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link MetricsInterface.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('coldStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*/
singleMetric(): MetricsInterface;
}
export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, MetricsInterface, };
//# sourceMappingURL=Metrics.d.ts.map
import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';
import type { ConfigServiceInterface } from '../types/ConfigServiceInterface.js';
/**
* Class EnvironmentVariablesService
*
* This class is used to return environment variables that are available in the runtime of
* the current Lambda invocation.
*/
declare class EnvironmentVariablesService extends CommonEnvironmentVariablesService implements ConfigServiceInterface {
private namespaceVariable;
/**
* It returns the value of the POWERTOOLS_METRICS_NAMESPACE environment variable.
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/

@@ -8,0 +14,0 @@ getNamespace(): string;

import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';
/**
* Class EnvironmentVariablesService
*
* This class is used to return environment variables that are available in the runtime of
* the current Lambda invocation.
*/
class EnvironmentVariablesService extends CommonEnvironmentVariablesService {
namespaceVariable = 'POWERTOOLS_METRICS_NAMESPACE';
/**
* It returns the value of the POWERTOOLS_METRICS_NAMESPACE environment variable.
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/

@@ -7,0 +13,0 @@ getNamespace() {

@@ -0,6 +1,27 @@

/**
* The dimension key for the cold start metric.
*/
declare const COLD_START_METRIC = "ColdStart";
/**
* The default namespace for metrics.
*/
declare const DEFAULT_NAMESPACE = "default_namespace";
/**
* The maximum number of metrics that can be emitted in a single EMF blob.
*/
declare const MAX_METRICS_SIZE = 100;
/**
* The maximum number of metric values that can be emitted in a single metric.
*/
declare const MAX_METRIC_VALUES_SIZE = 100;
/**
* The maximum number of dimensions that can be added to a metric (0-indexed).
*/
declare const MAX_DIMENSION_COUNT = 29;
/**
* The unit of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Unit | Amazon CloudWatch Units}
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html | Amazon CloudWatch MetricDatum}
*/
declare const MetricUnit: {

@@ -35,2 +56,7 @@ readonly Seconds: "Seconds";

};
/**
* The resolution of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | Amazon CloudWatch Resolution}
*/
declare const MetricResolution: {

@@ -37,0 +63,0 @@ readonly Standard: 60;

@@ -0,6 +1,27 @@

/**
* The dimension key for the cold start metric.
*/
const COLD_START_METRIC = 'ColdStart';
/**
* The default namespace for metrics.
*/
const DEFAULT_NAMESPACE = 'default_namespace';
/**
* The maximum number of metrics that can be emitted in a single EMF blob.
*/
const MAX_METRICS_SIZE = 100;
/**
* The maximum number of metric values that can be emitted in a single metric.
*/
const MAX_METRIC_VALUES_SIZE = 100;
/**
* The maximum number of dimensions that can be added to a metric (0-indexed).
*/
const MAX_DIMENSION_COUNT = 29;
/**
* The unit of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Unit | Amazon CloudWatch Units}
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_MetricDatum.html | Amazon CloudWatch MetricDatum}
*/
const MetricUnit = {

@@ -35,2 +56,7 @@ Seconds: 'Seconds',

};
/**
* The resolution of the metric.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | Amazon CloudWatch Resolution}
*/
const MetricResolution = {

@@ -37,0 +63,0 @@ Standard: 60,

@@ -5,60 +5,58 @@ import { Utility } from '@aws-lambda-powertools/commons';

/**
* ## Intro
* Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF).
* The Metrics utility creates custom metrics asynchronously by logging metrics to standard output following {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*
* These metrics can be visualized through Amazon CloudWatch Console.
*
* ## Key features
* * Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob)
* * Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc)
* * Metrics are created asynchronously by CloudWatch service, no custom stacks needed
* * Context manager to create a one off metric with a different dimension
* **Key features**
* * Aggregating up to 100 metrics using a single CloudWatch EMF 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.
* * Creating a one-off metric with different dimensions.
*
* ## Usage
* After initializing the Metrics class, you can add metrics using the {@link Metrics.addMetric | `addMetric()`} method.
* The metrics are stored in a buffer and are flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
* Each metric can have dimensions and metadata added to it.
*
* ### Functions usage with middleware
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* const lambdaHandler = async (_event: unknown, _context: unknown) => {
* ...
* export const handler = async (event: { requestId: string }) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* ```
*
* ### Object oriented way with decorator
* If you don't want to manually flush the metrics, you can use the {@link Metrics.logMetrics | `logMetrics()`} decorator or
* the Middy.js middleware to automatically flush the metrics after the handler function returns or throws an error.
*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the {@link Metrics.logMetrics} decorator to automatically:
* * capture a `ColdStart` metric
* * flush buffered metrics
* * throw on empty metrics
* In addition to this, the decorator and middleware can also be configured to capture a `ColdStart` metric and
* set default dimensions for all metrics.
*
* **Class method decorator**
*
* @example
*
* ```typescript
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* // Decorate your handler with the logMetrics decorator
* ⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
* public handler(_event: unknown, _context: unknown): Promise<void> {
* // ...
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* // ...
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -71,5 +69,7 @@ * }

*
* ### Standard function
* Note that decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard.
* The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the [`experimentalDecorators` flag](https://www.typescriptlang.org/tsconfig/#experimentalDecorators)
* set to `true` in the `tsconfig.json` file.
*
* If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics.
* **Middy.js middleware**
*

@@ -80,11 +80,21 @@ * @example

* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* metrics.publishStoredMetrics();
* };
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* The `logMetrics()` middleware is compatible with `@middy/core@3.x` and above.
*
*/

@@ -152,9 +162,12 @@ declare class Metrics extends Utility implements MetricsInterface {

/**
* Add a dimension to the metrics.
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics.
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name The name of the dimension
* @param value The value of the dimension
* 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.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/

@@ -165,16 +178,37 @@ addDimension(name: string, value: string): void;

*
* A dimension is a key-value pair that is used to group metrics.
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* @param dimensions A key-value pair of dimensions
* 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.
*
* @param dimensions - An object with key-value pairs of dimensions
*/
addDimensions(dimensions: {
[key: string]: string;
}): void;
addDimensions(dimensions: Dimensions): void;
/**
* A high-cardinality data part of your Metrics log.
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* @param key The key of the metadata
* @param value The value of the metadata
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/

@@ -185,8 +219,13 @@ addMetadata(key: string, value: string): void;

*
* By default, metrics are buffered and flushed at the end of the Lambda invocation
* or when calling {@link Metrics.publishStoredMetrics}.
* By default, metrics are buffered and flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link Metrics.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in {@link MetricUnit}.
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example

@@ -196,35 +235,76 @@ * ```typescript

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* Optionally, you can specify the metric resolution, which can be either `High` or `Standard`.
* By default, metrics are published with a resolution of `Standard`, click [here](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition)
* to learn more about metric resolutions.
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
/**
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* By using this method, the metric will be emitted immediately without you having to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example
* ```typescript
* import { Metrics, MetricUnit, MetricResolution } from '@aws-lambda-powertools/metrics';
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1, MetricResolution.High);
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };
* ```
*/
captureColdStartMetric(): void;
/**
* Clear all previously set default dimensions.
*
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution
* This will remove all default dimensions set by the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
clearDefaultDimensions(): void;
/**
* Create a singleMetric to capture cold start.
* Clear all the dimensions added to the Metrics instance via {@link Metrics.addDimension | `addDimension()`} or {@link Metrics.addDimensions | `addDimensions()`}.
*
* If it's a cold start invocation, this feature will:
* * Create a separate EMF blob that contains a single metric named ColdStart
* * Add function_name and service dimensions
* These dimensions are normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions,
* as well as avoiding potential data loss from metrics not being published for other reasons.
* This method does not clear the default dimensions set via {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*

@@ -235,20 +315,26 @@ * @example

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
captureColdStartMetric(): void;
/**
* Clear all default dimensions.
*/
clearDefaultDimensions(): void;
/**
* Clear all dimensions.
*/
clearDimensions(): void;
/**
* Clear all metadata.
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -258,19 +344,32 @@ clearMetadata(): void;

* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearMetrics(): void;
/**
* A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* @metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: unknown, __context: unknown): Promise<void> {
* // ...
* ⁣@metrics.logMetrics({ captureColdStartMetric: true })
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -283,18 +382,28 @@ * }

*
* @param options - The options to configure the logMetrics decorator
* You can configure the decorator with the following options:
* - `captureColdStartMetric` - Whether to capture a `ColdStart` metric
* - `defaultDimensions` - Default dimensions to add to all metrics
* - `throwOnEmptyMetrics` - Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/
logMetrics(options?: ExtraOptions): HandlerMethodDecorator;
/**
* Synchronous function to actually publish your metrics. (Not needed if using logMetrics decorator).
* It will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation.
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
*
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();

@@ -306,10 +415,12 @@ * };

/**
* Function to create a new metric object compliant with the EMF (Embedded Metric Format) schema which
* includes the metric name, unit, and optionally storage resolution.
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The function will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch
* logs and processed automatically for metrics creation.
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* @returns metrics as JSON object compliant EMF Schema Specification
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html for more details
* The object is then emitted to standard output, which in AWS Lambda is picked up by CloudWatch logs and processed asynchronously.
*/

@@ -320,48 +431,90 @@ serializeMetrics(): EmfOutput;

*
* @param dimensions The default dimensions to be added to all metrics.
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/
setDefaultDimensions(dimensions: Dimensions | undefined): void;
/**
* Sets the function name to be added to the metric.
* Set the function name to be added to each metric as a dimension.
*
* @param value The function name to be added to the metric.
*/
setFunctionName(value: string): void;
/**
* CloudWatch EMF uses the same dimensions across all your metrics. Use singleMetric if you have a metric that should have different dimensions.
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* You don't need to call publishStoredMetrics() after calling addMetric for a singleMetrics, they will be flushed directly.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* ```typescript
* const singleMetric = metrics.singleMetric();
* singleMetric.addDimension('InnerDimension', 'true');
* singleMetric.addMetric('single-metric', MetricUnit.Percent, 50);
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @returns the Metrics
* @param name - The function name
*/
singleMetric(): Metrics;
setFunctionName(name: string): void;
/**
* Throw an Error if the metrics buffer is empty.
* Set the flag to throw an error if no metrics are emitted.
*
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
setThrowOnEmptyMetrics(enabled: boolean): void;
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.throwOnEmptyMetrics();
* metrics.publishStoredMetrics(); // will throw since no metrics added.
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('coldStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*/
singleMetric(): Metrics;
/**
* @deprecated Use {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`} instead.
*/
throwOnEmptyMetrics(): void;
/**
* Gets the current number of dimensions stored.
*
* @returns the number of dimensions currently stored
* Gets the current number of dimensions count.
*/

@@ -386,12 +539,11 @@ private getCurrentDimensionsCount;

*
* @param name The name of the metric
* @param unit The unit of the metric
* @param name - The name of the metric
* @param unit - The unit of the metric
*/
private isNewMetric;
/**
* Initialize the console property as an instance of the internal version of Console() class (PR #748)
* Initialize the console property as an instance of the internal version of `Console()` class (PR #748)
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
*
* @private
* @returns {void}
*/

@@ -412,3 +564,3 @@ private setConsole;

*
* @param namespace The namespace to be used
* @param namespace - The namespace to be used
*/

@@ -421,3 +573,3 @@ private setNamespace;

*
* @param options The options to be used
* @param options - The options to be used
*/

@@ -428,3 +580,3 @@ private setOptions;

*
* @param service The service to be used
* @param service - The service to be used
*/

@@ -436,8 +588,8 @@ private setService;

* If the buffer is full, or the metric reaches the maximum number of values,
* the buffer is published to stdout.
* the metrics are flushed to stdout.
*
* @param name The name of the metric to store
* @param unit The unit of the metric to store
* @param value The value of the metric to store
* @param resolution The resolution of the metric to store
* @param name - The name of the metric to store
* @param unit - The unit of the metric to store
* @param value - The value of the metric to store
* @param resolution - The resolution of the metric to store
*/

@@ -444,0 +596,0 @@ private storeMetric;

@@ -6,60 +6,58 @@ import { Console } from 'node:console';

/**
* ## Intro
* Metrics creates custom metrics asynchronously by logging metrics to standard output following Amazon CloudWatch Embedded Metric Format (EMF).
* The Metrics utility creates custom metrics asynchronously by logging metrics to standard output following {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*
* These metrics can be visualized through Amazon CloudWatch Console.
*
* ## Key features
* * Aggregate up to 100 metrics using a single CloudWatch EMF object (large JSON blob)
* * Validate against common metric definitions mistakes (metric unit, values, max dimensions, max metrics, etc)
* * Metrics are created asynchronously by CloudWatch service, no custom stacks needed
* * Context manager to create a one off metric with a different dimension
* **Key features**
* * Aggregating up to 100 metrics using a single CloudWatch EMF 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.
* * Creating a one-off metric with different dimensions.
*
* ## Usage
* After initializing the Metrics class, you can add metrics using the {@link Metrics.addMetric | `addMetric()`} method.
* The metrics are stored in a buffer and are flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
* Each metric can have dimensions and metadata added to it.
*
* ### Functions usage with middleware
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* const lambdaHandler = async (_event: unknown, _context: unknown) => {
* ...
* export const handler = async (event: { requestId: string }) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* ```
*
* ### Object oriented way with decorator
* If you don't want to manually flush the metrics, you can use the {@link Metrics.logMetrics | `logMetrics()`} decorator or
* the Middy.js middleware to automatically flush the metrics after the handler function returns or throws an error.
*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the {@link Metrics.logMetrics} decorator to automatically:
* * capture a `ColdStart` metric
* * flush buffered metrics
* * throw on empty metrics
* In addition to this, the decorator and middleware can also be configured to capture a `ColdStart` metric and
* set default dimensions for all metrics.
*
* **Class method decorator**
*
* @example
*
* ```typescript
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* // Decorate your handler with the logMetrics decorator
* ⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
* public handler(_event: unknown, _context: unknown): Promise<void> {
* // ...
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* // ...
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -72,5 +70,7 @@ * }

*
* ### Standard function
* Note that decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard.
* The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the [`experimentalDecorators` flag](https://www.typescriptlang.org/tsconfig/#experimentalDecorators)
* set to `true` in the `tsconfig.json` file.
*
* If you are used to classic JavaScript functions, you can leverage the different methods provided to create and publish metrics.
* **Middy.js middleware**
*

@@ -81,11 +81,21 @@ * @example

* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* metrics.publishStoredMetrics();
* };
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* The `logMetrics()` middleware is compatible with `@middy/core@3.x` and above.
*
*/

@@ -157,9 +167,12 @@ class Metrics extends Utility {

/**
* Add a dimension to the metrics.
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics.
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name The name of the dimension
* @param value The value of the dimension
* 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.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/

@@ -175,5 +188,9 @@ addDimension(name, value) {

*
* A dimension is a key-value pair that is used to group metrics.
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* @param dimensions A key-value pair of dimensions
* 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.
*
* @param dimensions - An object with key-value pairs of dimensions
*/

@@ -191,8 +208,27 @@ addDimensions(dimensions) {

/**
* A high-cardinality data part of your Metrics log.
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* @param key The key of the metadata
* @param value The value of the metadata
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/

@@ -205,8 +241,13 @@ addMetadata(key, value) {

*
* By default, metrics are buffered and flushed at the end of the Lambda invocation
* or when calling {@link Metrics.publishStoredMetrics}.
* By default, metrics are buffered and flushed when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link Metrics.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in {@link MetricUnit}.
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example

@@ -216,24 +257,17 @@ * ```typescript

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* Optionally, you can specify the metric resolution, which can be either `High` or `Standard`.
* By default, metrics are published with a resolution of `Standard`, click [here](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition)
* to learn more about metric resolutions.
*
* @example
* ```typescript
* import { Metrics, MetricUnit, MetricResolution } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
*
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1, MetricResolution.High);
* ```
*
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/

@@ -246,11 +280,12 @@ addMetric(name, unit, value, resolution = MetricResolutions.Standard) {

/**
* Create a singleMetric to capture cold start.
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* If it's a cold start invocation, this feature will:
* * Create a separate EMF blob that contains a single metric named ColdStart
* * Add function_name and service dimensions
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* This has the advantage of keeping cold start metric separate from your application metrics, where you might have unrelated dimensions,
* as well as avoiding potential data loss from metrics not being published for other reasons.
* By using this method, the metric will be emitted immediately without you having to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example

@@ -260,6 +295,9 @@ * ```typescript

*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.captureColdStartMetric();
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };

@@ -283,3 +321,22 @@ * ```

/**
* Clear all default dimensions.
* Clear all previously set default dimensions.
*
* This will remove all default dimensions set by the {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/

@@ -290,3 +347,29 @@ clearDefaultDimensions() {

/**
* Clear all dimensions.
* Clear all the dimensions added to the Metrics instance via {@link Metrics.addDimension | `addDimension()`} or {@link Metrics.addDimensions | `addDimensions()`}.
*
* These dimensions are normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This method does not clear the default dimensions set via {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -297,3 +380,8 @@ clearDimensions() {

/**
* Clear all metadata.
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -305,2 +393,6 @@ clearMetadata() {

* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/

@@ -311,16 +403,25 @@ clearMetrics() {

/**
* A decorator automating coldstart capture, throw on empty metrics and publishing metrics on handler exit.
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link Metrics.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import type { Context } from 'aws-lambda';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* @metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: unknown, __context: unknown): Promise<void> {
* // ...
* ⁣@metrics.logMetrics({ captureColdStartMetric: true })
* public async handler(_event: { requestId: string }, _: Context) {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }

@@ -333,3 +434,8 @@ * }

*
* @param options - The options to configure the logMetrics decorator
* You can configure the decorator with the following options:
* - `captureColdStartMetric` - Whether to capture a `ColdStart` metric
* - `defaultDimensions` - Default dimensions to add to all metrics
* - `throwOnEmptyMetrics` - Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/

@@ -339,3 +445,3 @@ logMetrics(options = {}) {

if (throwOnEmptyMetrics) {
this.throwOnEmptyMetrics();
this.setThrowOnEmptyMetrics(throwOnEmptyMetrics);
}

@@ -368,14 +474,19 @@ if (defaultDimensions !== undefined) {

/**
* Synchronous function to actually publish your metrics. (Not needed if using logMetrics decorator).
* It will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch logs and processed automatically for metrics creation.
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
*
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' }); // Sets metric namespace, and service as a metric dimension
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.addMetric('test-metric', MetricUnit.Count, 10);
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();

@@ -398,10 +509,12 @@ * };

/**
* Function to create a new metric object compliant with the EMF (Embedded Metric Format) schema which
* includes the metric name, unit, and optionally storage resolution.
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The function will create a new EMF blob and log it to standard output to be then ingested by Cloudwatch
* logs and processed automatically for metrics creation.
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* @returns metrics as JSON object compliant EMF Schema Specification
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html for more details
* The object is then emitted to standard output, which in AWS Lambda is picked up by CloudWatch logs and processed asynchronously.
*/

@@ -454,3 +567,22 @@ serializeMetrics() {

*
* @param dimensions The default dimensions to be added to all metrics.
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/

@@ -468,23 +600,63 @@ setDefaultDimensions(dimensions) {

/**
* Sets the function name to be added to the metric.
* Set the function name to be added to each metric as a dimension.
*
* @param value The function name to be added to the metric.
* When using the {@link Metrics.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @param name - The function name
*/
setFunctionName(value) {
this.functionName = value;
setFunctionName(name) {
this.functionName = name;
}
/**
* CloudWatch EMF uses the same dimensions across all your metrics. Use singleMetric if you have a metric that should have different dimensions.
* Set the flag to throw an error if no metrics are emitted.
*
* You don't need to call publishStoredMetrics() after calling addMetric for a singleMetrics, they will be flushed directly.
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
setThrowOnEmptyMetrics(enabled) {
this.shouldThrowOnEmptyMetrics = enabled;
}
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link Metrics.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
*
* ```typescript
* const singleMetric = metrics.singleMetric();
* singleMetric.addDimension('InnerDimension', 'true');
* singleMetric.addMetric('single-metric', MetricUnit.Percent, 50);
* ```
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* @returns the Metrics
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('coldStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*/

@@ -500,16 +672,3 @@ singleMetric() {

/**
* Throw an Error if the metrics buffer is empty.
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName:'orders' });
*
* export const handler = async (_event: unknown, __context: unknown): Promise<void> => {
* metrics.throwOnEmptyMetrics();
* metrics.publishStoredMetrics(); // will throw since no metrics added.
* };
* ```
* @deprecated Use {@link Metrics.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`} instead.
*/

@@ -520,5 +679,3 @@ throwOnEmptyMetrics() {

/**
* Gets the current number of dimensions stored.
*
* @returns the number of dimensions currently stored
* Gets the current number of dimensions count.
*/

@@ -550,4 +707,4 @@ getCurrentDimensionsCount() {

*
* @param name The name of the metric
* @param unit The unit of the metric
* @param name - The name of the metric
* @param unit - The unit of the metric
*/

@@ -565,7 +722,6 @@ isNewMetric(name, unit) {

/**
* Initialize the console property as an instance of the internal version of Console() class (PR #748)
* Initialize the console property as an instance of the internal version of `Console()` class (PR #748)
* or as the global node console if the `POWERTOOLS_DEV' env variable is set and has truthy value.
*
* @private
* @returns {void}
*/

@@ -602,3 +758,3 @@ setConsole() {

*
* @param namespace The namespace to be used
* @param namespace - The namespace to be used
*/

@@ -615,3 +771,3 @@ setNamespace(namespace) {

*
* @param options The options to be used
* @param options - The options to be used
*/

@@ -632,3 +788,3 @@ setOptions(options) {

*
* @param service The service to be used
* @param service - The service to be used
*/

@@ -648,8 +804,8 @@ setService(service) {

* If the buffer is full, or the metric reaches the maximum number of values,
* the buffer is published to stdout.
* the metrics are flushed to stdout.
*
* @param name The name of the metric to store
* @param unit The unit of the metric to store
* @param value The value of the metric to store
* @param resolution The resolution of the metric to store
* @param name - The name of the metric to store
* @param unit - The unit of the metric to store
* @param value - The value of the metric to store
* @param resolution - The resolution of the metric to store
*/

@@ -656,0 +812,0 @@ storeMetric(name, unit, value, resolution) {

@@ -5,27 +5,36 @@ import type { MiddlewareLikeObj } from '@aws-lambda-powertools/commons/types';

/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
* A Middy.js middleware automating capture of Amazon CloudWatch metrics.
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
* This middleware is compatible with `@middy/core@3.x` and above.
*
* The middleware automatically flushes metrics after the handler function returns or throws an error,
* so you don't need to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} manually.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* const lambdaHandler = async (_event: any, _context: any) => {
* ...
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* You can configure the middleware with the following options:
* - `captureColdStartMetric`: Whether to capture a `ColdStart` metric
* - `defaultDimensions`: Default dimensions to add to all metrics
* - `throwOnEmptyMetrics`: Whether to throw an error if no metrics are emitted
*
* @param target - The Metrics instance to use for emitting metrics
* @param options - (_optional_) Options for the middleware
* @param options - Options to configure the middleware, see {@link ExtraOptions}
*/

@@ -32,0 +41,0 @@ declare const logMetrics: (target: Metrics | Metrics[], options?: ExtraOptions) => MiddlewareLikeObj;

import { METRICS_KEY } from '@aws-lambda-powertools/commons';
/**
* A middy middleware automating capture of metadata and annotations on segments or subsegments for a Lambda Handler.
* A Middy.js middleware automating capture of Amazon CloudWatch metrics.
*
* Using this middleware on your handler function will automatically flush metrics after the function returns or throws an error.
* Additionally, you can configure the middleware to easily:
* * ensure that at least one metric is emitted before you flush them
* * capture a `ColdStart` a metric
* * set default dimensions for all your metrics
* This middleware is compatible with `@middy/core@3.x` and above.
*
* The middleware automatically flushes metrics after the handler function returns or throws an error,
* so you don't need to call {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} manually.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
* import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
* import middy from '@middy/core';
*
* const metrics = new Metrics({ namespace: 'serverlessAirline', serviceName: 'orders' });
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* const lambdaHandler = async (_event: any, _context: any) => {
* ...
* };
*
* export const handler = middy(lambdaHandler).use(logMetrics(metrics));
* export const handler = middy(async () => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* }).use(logMetrics(metrics, {
* captureColdStartMetric: true,
* throwOnEmptyMetrics: true,
* }));
* ```
*
* You can configure the middleware with the following options:
* - `captureColdStartMetric`: Whether to capture a `ColdStart` metric
* - `defaultDimensions`: Default dimensions to add to all metrics
* - `throwOnEmptyMetrics`: Whether to throw an error if no metrics are emitted
*
* @param target - The Metrics instance to use for emitting metrics
* @param options - (_optional_) Options for the middleware
* @param options - Options to configure the middleware, see {@link ExtraOptions}
*/

@@ -47,3 +56,3 @@ const logMetrics = (target, options = {}) => {

if (throwOnEmptyMetrics) {
metrics.throwOnEmptyMetrics();
metrics.setThrowOnEmptyMetrics(throwOnEmptyMetrics);
}

@@ -50,0 +59,0 @@ if (defaultDimensions !== undefined) {

@@ -11,5 +11,3 @@ import type { ConfigServiceInterface as ConfigServiceBaseInterface } from '@aws-lambda-powertools/commons/types';

/**
* It returns the value of the POWERTOOLS_METRICS_NAMESPACE environment variable.
*
* @returns {string}
* Get the value of the `POWERTOOLS_METRICS_NAMESPACE` environment variable.
*/

@@ -16,0 +14,0 @@ getNamespace(): string;

@@ -1,4 +0,3 @@

export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, } from './Metrics.js';
export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, MetricsInterface, } from './Metrics.js';
export type { ConfigServiceInterface } from './ConfigServiceInterface.js';
export type { MetricsInterface } from './MetricsInterface.js';
//# sourceMappingURL=index.d.ts.map

@@ -1,11 +0,60 @@

import type { MetricResolution as MetricResolutionList, MetricUnit as MetricUnitList } from '../constants.js';
import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { MetricResolution as MetricResolutions, MetricUnit as MetricUnits } from '../constants.js';
import type { ConfigServiceInterface } from './ConfigServiceInterface.js';
/**
* A set of key-value pairs that define the dimensions of a metric.
*/
type Dimensions = Record<string, string>;
/**
* Options to configure the Metrics class.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* singleMetric: true,
* });
* ```
*/
type MetricsOptions = {
/**
* A custom configuration service to use for retrieving configuration values.
*
* @default undefined
*/
customConfigService?: ConfigServiceInterface;
/**
* The namespace to use for all metrics.
*
* @default undefined
*/
namespace?: string;
/**
* The service name to use for all metrics.
*
* @default undefined
*/
serviceName?: string;
/**
* Whether to configure the Metrics class to emit a single metric as soon as it is added.
*
* @default false
* @see {@link MetricsInterface.singleMetric | `singleMetric()`}
*/
singleMetric?: boolean;
/**
* The default dimensions to add to all metrics.
*
* @default {}
* @see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}
*/
defaultDimensions?: Dimensions;
};
/**
* The output of the {@link MetricsInterface.serializeMetrics | `serializeMetrics()`} method,
* compliant with the {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html | Amazon CloudWatch Embedded Metric Format (EMF)}.
*/
type EmfOutput = Readonly<{

@@ -23,27 +72,42 @@ [key: string]: string | number | object;

/**
* Options for the metrics decorator
*
* Usage:
*
* ```typescript
*
* const metricsOptions: MetricsOptions = {
* throwOnEmptyMetrics: true,
* defaultDimensions: {'environment': 'dev'},
* captureColdStartMetric: true,
* }
*
* @metrics.logMetric(metricsOptions)
* public handler(event: any, context: any, callback: any) {
* // ...
* }
* ```
* Options to customize the behavior of the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator or Middy.js middleware.
*/
type ExtraOptions = {
/**
* Whether to throw an error if no metrics are emitted.
*
* @default false
* @see {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}
*/
throwOnEmptyMetrics?: boolean;
/**
* Default dimensions to add to all metrics.
*
* @default {}
* @see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}
*/
defaultDimensions?: Dimensions;
/**
* Whether to capture a `ColdStart` metric.
*
* @default false
* @see {@link MetricsInterface.captureColdStartMetric | `captureColdStartMetric()`}
*/
captureColdStartMetric?: boolean;
};
type MetricResolution = (typeof MetricResolutionList)[keyof typeof MetricResolutionList];
type MetricUnit = (typeof MetricUnitList)[keyof typeof MetricUnitList];
/**
* A list of possible metric resolutions.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | Amazon CloudWatch Resolution}
*/
type MetricResolution = (typeof MetricResolutions)[keyof typeof MetricResolutions];
/**
* A list of possible metric units.
*
* @see {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Unit | Amazon CloudWatch Units}
*/
type MetricUnit = (typeof MetricUnits)[keyof typeof MetricUnits];
/**
* Data structure to store a metric that has been added to the Metrics class.
*/
type StoredMetric = {

@@ -55,3 +119,9 @@ name: string;

};
/**
* A map of stored metrics, where the key is the metric name and the value is the stored metric.
*/
type StoredMetrics = Record<string, StoredMetric>;
/**
* A definition of a metric that can be added to the Metrics class.
*/
type MetricDefinition = {

@@ -62,3 +132,350 @@ Name: string;

};
export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, };
interface MetricsInterface {
/**
* Add a dimension to metrics.
*
* A dimension is a key-value pair that is used to group metrics, and it is included in all metrics emitted after it is added.
*
* When calling the {@link MetricsInterface.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 MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @param name - The name of the dimension
* @param value - The value of the dimension
*/
addDimension(name: string, value: string): void;
/**
* Add multiple dimensions to the metrics.
*
* This method is useful when you want to add multiple dimensions to the metrics at once.
*
* When calling the {@link MetricsInterface.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 MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} method.
*
* @param dimensions - An object with key-value pairs of dimensions
*/
addDimensions(dimensions: Dimensions): void;
/**
* A metadata key-value pair to be included with metrics.
*
* You can use this method to add high-cardinality data as part of your metrics.
* This is useful when you want to search highly contextual information along with your metrics in your logs.
*
* Note that the metadata is not included in the Amazon CloudWatch UI, but it can be used to search and filter logs.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async (event) => {
* metrics.addMetadata('request_id', event.requestId);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param key - The key of the metadata
* @param value - The value of the metadata
*/
addMetadata(key: string, value: string): void;
/**
* Add a metric to the metrics buffer.
*
* By default, metrics are buffered and flushed when calling {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`} method,
* or at the end of the handler function when using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator or the Middy.js middleware.
*
* Metrics are emitted to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema. In AWS Lambda, the logs are
* automatically picked up by CloudWatch logs and processed asynchronously.
*
* You can add a metric by specifying the metric name, unit, and value. For convenience,
* we provide a set of constants for the most common units in the {@link MetricUnits | MetricUnit} dictionary object.
*
* Optionally, you can specify a {@link https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Resolution_definition | resolution}, which can be either `High` or `Standard`, using the {@link MetricResolutions | MetricResolution} dictionary object.
* By default, metrics are published with a resolution of `Standard`.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*
* @param name - The metric name
* @param unit - The metric unit, see {@link MetricUnits | MetricUnit}
* @param value - The metric value
* @param resolution - The metric resolution, see {@link MetricResolutions | MetricResolution}
*/
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
/**
* Immediately emit a `ColdStart` metric if this is a cold start invocation.
*
* A cold start is when AWS Lambda initializes a new instance of your function. To take advantage of this feature,
* you must instantiate the Metrics class outside of the handler function.
*
* By using this method, the metric will be emitted immediately without you having to call {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}.
*
* If you are using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, you can enable this
* feature by setting the `captureColdStartMetric` option to `true`.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.captureColdStartMetric();
* };
* ```
*/
captureColdStartMetric(): void;
/**
* Clear all previously set default dimensions.
*
* This will remove all default dimensions set by the {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} method
* or via the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* metrics.setDefaultDimensions({ region: 'us-west-2' });
*
* // both environment and region dimensions are removed
* metrics.clearDefaultDimensions();
* ```
*/
clearDefaultDimensions(): void;
/**
* Clear all the dimensions added to the Metrics instance via {@link MetricsInterface.addDimension | `addDimension()`} or {@link MetricsInterface.addDimensions | `addDimensions()`}.
*
* These dimensions are normally cleared when calling {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific dimensions that you no longer need at runtime.
*
* This method does not clear the default dimensions set via {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`} or via
* the `defaultDimensions` parameter in the constructor.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addDimension('region', 'us-west-2');
*
* // ...
*
* metrics.clearDimensions(); // olnly the region dimension is removed
* };
* ```
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearDimensions(): void;
/**
* Clear all the metadata added to the Metrics instance.
*
* Metadata is normally cleared when calling {@link MetricsInterface.publishStoredMetrics | `publishStoredMetrics()`}, but
* you can use this method to clear specific metadata that you no longer need at runtime.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearMetadata(): void;
/**
* Clear all the metrics stored in the buffer.
*
* This is useful when you want to clear the metrics stored in the buffer without publishing them.
*
* The method is primarily intended for internal use, but it is exposed for advanced use cases.
*/
clearMetrics(): void;
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.
*
* The decorator can be used with TypeScript classes and can be configured to optionally capture a `ColdStart` metric (see {@link MetricsInterface.captureColdStartMetric | `captureColdStartMetric()`}),
* throw an error if no metrics are emitted (see {@link MetricsInterface.setThrowOnEmptyMetrics | `setThrowOnEmptyMetrics()`}),
* and set default dimensions for all metrics (see {@link MetricsInterface.setDefaultDimensions | `setDefaultDimensions()`}).
*
* @example
*
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
* import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* class Lambda implements LambdaInterface {
* ⁣@metrics.logMetrics({ captureColdStartMetric: true })
* public handler(_event: unknown, _context: unknown) {
* // ...
* }
* }
*
* const handlerClass = new Lambda();
* export const handler = handlerClass.handler.bind(handlerClass);
* ```
*
* You can configure the decorator with the following options:
* - `captureColdStartMetric`: Whether to capture a `ColdStart` metric
* - `defaultDimensions`: Default dimensions to add to all metrics
* - `throwOnEmptyMetrics`: Whether to throw an error if no metrics are emitted
*
* @param options - Options to configure the behavior of the decorator, see {@link ExtraOptions}
*/
logMetrics(options?: ExtraOptions): HandlerMethodDecorator;
/**
* Flush the stored metrics to standard output.
*
* The method empties the metrics buffer and emits the metrics to standard output in the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* When using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the metrics are automatically flushed after the handler function returns or throws an error.
*
* @example
* ```typescript
* import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
* ```
*/
publishStoredMetrics(): void;
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.
*
* The EMF schema is a JSON object that contains the following properties:
* - `_aws`: An object containing the timestamp and the CloudWatch metrics.
* - `CloudWatchMetrics`: An array of CloudWatch metrics objects.
* - `Namespace`: The namespace of the metrics.
* - `Dimensions`: An array of dimensions for the metrics.
* - `Metrics`: An array of metric definitions.
*
* The serialized object is returned for later use.
*
* This is primarily an internal method used by the Metrics class, but it is exposed for advanced use cases.
*/
serializeMetrics(): EmfOutput;
/**
* Set default dimensions that will be added to all metrics.
*
* This method will merge the provided dimensions with the existing default dimensions.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* defaultDimensions: { environment: 'dev' },
* });
*
* // Default dimensions will contain both region and environment
* metrics.setDefaultDimensions({
* region: 'us-west-2',
* environment: 'prod',
* });
* ```
*
* @param dimensions - The dimensions to be added to the default dimensions object
*/
setDefaultDimensions(dimensions: Dimensions | undefined): void;
/**
* Set the function name to be added to each metric as a dimension.
*
* When using the {@link MetricsInterface.logMetrics | `logMetrics()`} decorator, or the Middy.js middleware, the function
* name is automatically inferred from the Lambda context.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* metrics.setFunctionName('my-function-name');
* ```
*
* @param name - The function name
*/
setFunctionName(name: string): void;
/**
* Set the flag to throw an error if no metrics are emitted.
*
* You can use this method to enable or disable this opt-in feature. This is useful if you want to ensure
* that at least one metric is emitted when flushing the metrics. This can be useful to catch bugs where
* metrics are not being emitted as expected.
*
* @param enabled - Whether to throw an error if no metrics are emitted
*/
setThrowOnEmptyMetrics(enabled: boolean): void;
/**
* Create a new Metrics instance configured to immediately flush a single metric.
*
* CloudWatch EMF uses the same dimensions and timestamp across all your metrics, this is useful when you have a metric that should have different dimensions
* or when you want to emit a single metric without buffering it.
*
* This method is used internally by the {@link MetricsInterface.captureColdStartMetric | `captureColdStartMetric()`} method to emit the `ColdStart` metric immediately
* after the handler function is called.
*
* @example
* ```typescript
* import { Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders'
* });
*
* export const handler = async () => {
* const singleMetric = metrics.singleMetric();
* // The single metric will be emitted immediately
* singleMetric.addMetric('coldStart', MetricUnit.Count, 1);
*
* // These other metrics will be buffered and emitted when calling `publishStoredMetrics()`
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* metrics.publishStoredMetrics();
* };
*/
singleMetric(): MetricsInterface;
}
export type { MetricsOptions, Dimensions, EmfOutput, ExtraOptions, StoredMetrics, StoredMetric, MetricDefinition, MetricResolution, MetricUnit, MetricsInterface, };
//# sourceMappingURL=Metrics.d.ts.map
{
"name": "@aws-lambda-powertools/metrics",
"version": "2.8.0",
"version": "2.9.0",
"description": "The metrics package for the Powertools for AWS Lambda (TypeScript) library",

@@ -27,3 +27,3 @@ "author": {

"dependencies": {
"@aws-lambda-powertools/commons": "^2.8.0"
"@aws-lambda-powertools/commons": "^2.9.0"
},

@@ -30,0 +30,0 @@ "peerDependencies": {

@@ -1,2 +0,2 @@

# Powertools for AWS Lambda (TypeScript) <!-- omit in toc -->
# Powertools for AWS Lambda (TypeScript)

@@ -7,8 +7,7 @@ Powertools for AWS Lambda (TypeScript) is a developer toolkit to implement Serverless [best practices and increase developer velocity](https://docs.powertools.aws.dev/lambda/typescript/latest/#features).

- [Intro](#intro)
- [Usage](#usage)
- [Basic usage](#basic-usage)
- [Flushing metrics](#flushing-metrics)
- [Capturing cold start as a metric](#capturing-cold-start-as-a-metric)
- [Adding metadata](#adding-metadata)
- [Class method decorator](#class-method-decorator)
- [Middy.js middleware](#middyjs-middleware)
- [Contribute](#contribute)

@@ -23,6 +22,6 @@ - [Roadmap](#roadmap)

## Intro
## Usage
The library provides a utility function to emit metrics to CloudWatch using [Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html).
To get started, install the library by running:

@@ -34,8 +33,8 @@

### Basic usage
After initializing the Metrics class, you can add metrics using the [https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics/#creating-metrics](`addMetric()`) method. The metrics are stored in a buffer and are flushed when calling [https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics/#flushing-metrics](`publishStoredMetrics()`).
The library provides a utility function to emit metrics to CloudWatch using [Embedded Metric Format (EMF)](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format.html).
Each metric can also have dimensions and metadata added to it.
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

@@ -45,9 +44,9 @@ const metrics = new Metrics({

serviceName: 'orders',
defaultDimensions: { environment: process.env.ENVIRONMENT },
});
export const handler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
export const handler = async (event: { requestId: string }) => {
metrics.addMetadata('request_id', event.requestId);
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.publishStoredMetrics();
};

@@ -58,10 +57,14 @@ ```

As you finish adding all your metrics, you need to serialize and "flush them" by calling publishStoredMetrics(). This will print the metrics to standard output.
As you finish adding all your metrics, you need to serialize and "flush them" by calling `publishStoredMetrics()`, which will emit the metrics to stdout in the Embedded Metric Format (EMF). The metrics are then picked up by the Lambda runtime and sent to CloudWatch.
You can flush metrics automatically using one of the following methods:
The `publishStoredMetrics()` method is synchronous and will block the event loop until the metrics are flushed. If you want Metrics to flush automatically at the end of your Lambda function, you can use the `@logMetrics()` decorator or the `logMetrics()` middleware.
- manually by calling `publishStoredMetrics()` at the end of your Lambda function
### Capturing cold start as a metric
With Metrics, you can capture cold start as a metric by calling the `captureColdStartMetric()` method. This method will add a metric with the name `ColdStart` and the value `1` to the metrics buffer.
This metric is flushed automatically as soon as the method is called, to ensure that the cold start is captured regardless of whether the metrics are flushed manually or automatically.
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

@@ -73,38 +76,17 @@ const metrics = new Metrics({

export const handler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.publishStoredMetrics();
export const handler = async (event: { requestId: string }) => {
metrics.captureColdStartMetric();
};
```
- middy compatible middleware `logMetrics()`
Note that we don't emit a `ColdStart` metric with value `0` when the function is warm, as this would result in a high volume of metrics being emitted to CloudWatch, so you'll need to rely on the absence of the `ColdStart` metric to determine if the function is warm.
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
import middy from '@middy/core';
### Class method decorator
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
If you are using TypeScript and are comfortable with writing classes, you can use the `@logMetrics()` decorator to automatically flush metrics at the end of your Lambda function as well as configure additional options such as throwing an error if no metrics are added, capturing cold start as a metric, and more.
const lambdaHandler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
};
export const handler = middy(lambdaHandler).use(logMetrics(metrics));
```
- using decorator `@logMetrics()`
```ts
import type { Context } from 'aws-lambda';
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';

@@ -117,4 +99,5 @@ const metrics = new Metrics({

class Lambda implements LambdaInterface {
@metrics.logMetrics()
public async handler(_event: unknown, _context: unknown): Promise<void> {
⁣@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
public async handler(event: { requestId: string }, _: Context) {
metrics.addMetadata('request_id', event.requestId);
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);

@@ -125,34 +108,15 @@ }

const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);
export const handler = handlerClass.handler.bind(handlerClass);
```
Using the Middy middleware or decorator will automatically validate, serialize, and flush all your metrics.
Decorators are a Stage 3 proposal for JavaScript and are not yet part of the ECMAScript standard. The current implmementation in this library is based on the legacy TypeScript decorator syntax enabled by the [`experimentalDecorators` flag](https://www.typescriptlang.org/tsconfig/#experimentalDecorators) set to `true` in the `tsconfig.json` file.
### Capturing cold start as a metric
### Middy.js middleware
You can optionally capture cold start metrics with the logMetrics middleware or decorator via the captureColdStartMetric param.
If instead you are using [Middy.js](http://middy.js.org) and prefer to use middleware, you can use the `@logMetrics()` middleware to do the same as the class method decorator.
```ts
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
The `@logMetrics()` middleware can be used with Middy.js to automatically flush metrics at the end of your Lambda function as well as configure additional options such as throwing an error if no metrics are added, capturing cold start as a metric, and set default dimensions.
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
export class MyFunction implements LambdaInterface {
@metrics.logMetrics({ captureColdStartMetric: true })
public async handler(_event: unknown, _context: unknown): Promise<void> {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
}
}
```
### Adding metadata
You can add high-cardinality data as part of your Metrics log with the `addMetadata` method. This is useful when you want to search highly contextual information along with your metrics in your logs.
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { Metrics, MetricUnit } from '@aws-lambda-powertools/metrics';
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';

@@ -166,13 +130,13 @@ import middy from '@middy/core';

const lambdaHandler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
export const handler = middy(async (event) => {
metrics.addMetadata('request_id', event.requestId);
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.addMetadata('bookingId', '7051cd10-6283-11ec-90d6-0242ac120003');
};
export const handler = middy(lambdaHandler).use(logMetrics(metrics));
}).use(logMetrics(metrics, {
captureColdStartMetric: true,
throwOnEmptyMetrics: true,
}));
```
The `logMetrics()` middleware is compatible with `@middy/core@3.x` and above.
## Contribute

@@ -210,2 +174,3 @@

- [Elva](https://elva-group.com)
- [Flyweight](https://flyweight.io/)
- [globaldatanet](https://globaldatanet.com/)

@@ -212,0 +177,0 @@ - [Hashnode](https://hashnode.com/)

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc