Socket
Socket
Sign inDemoInstall

@aws-lambda-powertools/metrics

Package Overview
Dependencies
Maintainers
3
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.7.0 to 2.8.0

2

lib/cjs/config/EnvironmentVariablesService.d.ts

@@ -7,4 +7,2 @@ import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';

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

@@ -11,0 +9,0 @@ getNamespace(): string;

@@ -9,4 +9,2 @@ "use strict";

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

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

78

lib/cjs/Metrics.d.ts

@@ -43,3 +43,3 @@ import { Utility } from '@aws-lambda-powertools/commons';

*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically:
* 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

@@ -102,11 +102,47 @@ * * flush buffered metrics

private console;
/**
* Custom configuration service for metrics
*/
private customConfigService?;
/**
* Default dimensions to be added to all metrics
* @default {}
*/
private defaultDimensions;
/**
* Additional dimensions for the current metrics context
* @default {}
*/
private dimensions;
/**
* Service for accessing environment variables
*/
private envVarsService?;
/**
* Name of the Lambda function
*/
private functionName?;
/**
* Flag indicating if this is a single metric instance
* @default false
*/
private isSingleMetric;
/**
* Additional metadata to be included with metrics
* @default {}
*/
private metadata;
/**
* Namespace for the metrics
*/
private namespace?;
/**
* Flag to determine if an error should be thrown when no metrics are recorded
* @default false
*/
private shouldThrowOnEmptyMetrics;
/**
* Storage for metrics before they are published
* @default {}
*/
private storedMetrics;

@@ -120,4 +156,4 @@ constructor(options?: MetricsOptions);

* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name
* @param value
* @param name The name of the dimension
* @param value The value of the dimension
*/

@@ -175,5 +211,5 @@ addDimension(name: string, value: string): void;

*
* @param name - The metric name
* @param unit - The metric unit
* @param value - The metric value
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution

@@ -242,3 +278,3 @@ */

*
* @decorator Class
* @param options - The options to configure the logMetrics decorator
*/

@@ -276,3 +312,3 @@ logMetrics(options?: ExtraOptions): HandlerMethodDecorator;

/**
* Sets default dimensions that will be added to all metrics.
* Set default dimensions that will be added to all metrics.
*

@@ -328,15 +364,11 @@ * @param dimensions The default dimensions to be added to all metrics.

/**
* Gets the custom config service if it exists.
*
* @returns the custom config service if it exists, undefined otherwise
* Get the custom config service if it exists.
*/
private getCustomConfigService;
/**
* Gets the environment variables service.
*
* @returns the environment variables service
* Get the environment variables service.
*/
private getEnvVarsService;
/**
* Checks if a metric is new or not.
* Check if a metric is new or not.
*

@@ -351,7 +383,6 @@ * A metric is considered new if there is no metric with the same name already stored.

* @param unit The unit of the metric
* @returns true if the metric is new, false if another metric with the same name already exists
*/
private isNewMetric;
/**
* It initializes 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.

@@ -364,3 +395,3 @@ *

/**
* Sets the custom config service to be used.
* Set the custom config service to be used.
*

@@ -371,7 +402,7 @@ * @param customConfigService The custom config service to be used

/**
* Sets the environment variables service to be used.
* Set the environment variables service to be used.
*/
private setEnvVarsService;
/**
* Sets the namespace to be used.
* Set the namespace to be used.
*

@@ -382,3 +413,3 @@ * @param namespace The namespace to be used

/**
* Sets the options to be used by the Metrics instance.
* Set the options to be used by the Metrics instance.
*

@@ -388,7 +419,6 @@ * This method is used during the initialization of the Metrics instance.

* @param options The options to be used
* @returns the Metrics instance
*/
private setOptions;
/**
* Sets the service to be used.
* Set the service to be used.
*

@@ -399,3 +429,3 @@ * @param service The service to be used

/**
* Stores a metric in the buffer.
* Store a metric in the buffer.
*

@@ -402,0 +432,0 @@ * If the buffer is full, or the metric reaches the maximum number of values,

@@ -47,3 +47,3 @@ "use strict";

*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically:
* 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

@@ -106,11 +106,47 @@ * * flush buffered metrics

console;
/**
* Custom configuration service for metrics
*/
customConfigService;
/**
* Default dimensions to be added to all metrics
* @default {}
*/
defaultDimensions = {};
/**
* Additional dimensions for the current metrics context
* @default {}
*/
dimensions = {};
/**
* Service for accessing environment variables
*/
envVarsService;
/**
* Name of the Lambda function
*/
functionName;
/**
* Flag indicating if this is a single metric instance
* @default false
*/
isSingleMetric = false;
/**
* Additional metadata to be included with metrics
* @default {}
*/
metadata = {};
/**
* Namespace for the metrics
*/
namespace;
/**
* Flag to determine if an error should be thrown when no metrics are recorded
* @default false
*/
shouldThrowOnEmptyMetrics = false;
/**
* Storage for metrics before they are published
* @default {}
*/
storedMetrics = {};

@@ -128,4 +164,4 @@ constructor(options = {}) {

* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name
* @param value
* @param name The name of the dimension
* @param value The value of the dimension
*/

@@ -197,5 +233,5 @@ addDimension(name, value) {

*
* @param name - The metric name
* @param unit - The metric unit
* @param value - The metric value
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution

@@ -289,3 +325,3 @@ */

*
* @decorator Class
* @param options - The options to configure the logMetrics decorator
*/

@@ -340,9 +376,9 @@ logMetrics(options = {}) {

publishStoredMetrics() {
if (!this.shouldThrowOnEmptyMetrics &&
Object.keys(this.storedMetrics).length === 0) {
const hasMetrics = Object.keys(this.storedMetrics).length > 0;
if (!this.shouldThrowOnEmptyMetrics && !hasMetrics) {
console.warn('No application metrics to publish. The cold-start metric may be published if enabled. ' +
'If application metrics should never be empty, consider using `throwOnEmptyMetrics`');
}
const target = this.serializeMetrics();
this.console.log(JSON.stringify(target));
const emfOutput = this.serializeMetrics();
hasMetrics && this.console.log(JSON.stringify(emfOutput));
this.clearMetrics();

@@ -406,3 +442,3 @@ this.clearDimensions();

/**
* Sets default dimensions that will be added to all metrics.
* Set default dimensions that will be added to all metrics.
*

@@ -481,5 +517,3 @@ * @param dimensions The default dimensions to be added to all metrics.

/**
* Gets the custom config service if it exists.
*
* @returns the custom config service if it exists, undefined otherwise
* Get the custom config service if it exists.
*/

@@ -490,5 +524,3 @@ getCustomConfigService() {

/**
* Gets the environment variables service.
*
* @returns the environment variables service
* Get the environment variables service.
*/

@@ -499,3 +531,3 @@ getEnvVarsService() {

/**
* Checks if a metric is new or not.
* Check if a metric is new or not.
*

@@ -510,3 +542,2 @@ * A metric is considered new if there is no metric with the same name already stored.

* @param unit The unit of the metric
* @returns true if the metric is new, false if another metric with the same name already exists
*/

@@ -524,3 +555,3 @@ isNewMetric(name, unit) {

/**
* It initializes 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.

@@ -543,3 +574,3 @@ *

/**
* Sets the custom config service to be used.
* Set the custom config service to be used.
*

@@ -554,3 +585,3 @@ * @param customConfigService The custom config service to be used

/**
* Sets the environment variables service to be used.
* Set the environment variables service to be used.
*/

@@ -561,3 +592,3 @@ setEnvVarsService() {

/**
* Sets the namespace to be used.
* Set the namespace to be used.
*

@@ -572,3 +603,3 @@ * @param namespace The namespace to be used

/**
* Sets the options to be used by the Metrics instance.
* Set the options to be used by the Metrics instance.
*

@@ -578,3 +609,2 @@ * This method is used during the initialization of the Metrics instance.

* @param options The options to be used
* @returns the Metrics instance
*/

@@ -593,3 +623,3 @@ setOptions(options) {

/**
* Sets the service to be used.
* Set the service to be used.
*

@@ -608,3 +638,3 @@ * @param service The service to be used

/**
* Stores a metric in the buffer.
* Store a metric in the buffer.
*

@@ -611,0 +641,0 @@ * If the buffer is full, or the metric reaches the maximum number of values,

@@ -30,3 +30,2 @@ import type { MiddlewareLikeObj } from '@aws-lambda-powertools/commons/types';

* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/

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

@@ -31,3 +31,2 @@ "use strict";

* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/

@@ -34,0 +33,0 @@ const logMetrics = (target, options = {}) => {

@@ -7,4 +7,2 @@ import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';

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

@@ -11,0 +9,0 @@ getNamespace(): string;

@@ -6,4 +6,2 @@ import { EnvironmentVariablesService as CommonEnvironmentVariablesService } from '@aws-lambda-powertools/commons';

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

@@ -10,0 +8,0 @@ getNamespace() {

@@ -43,3 +43,3 @@ import { Utility } from '@aws-lambda-powertools/commons';

*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically:
* 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

@@ -102,11 +102,47 @@ * * flush buffered metrics

private console;
/**
* Custom configuration service for metrics
*/
private customConfigService?;
/**
* Default dimensions to be added to all metrics
* @default {}
*/
private defaultDimensions;
/**
* Additional dimensions for the current metrics context
* @default {}
*/
private dimensions;
/**
* Service for accessing environment variables
*/
private envVarsService?;
/**
* Name of the Lambda function
*/
private functionName?;
/**
* Flag indicating if this is a single metric instance
* @default false
*/
private isSingleMetric;
/**
* Additional metadata to be included with metrics
* @default {}
*/
private metadata;
/**
* Namespace for the metrics
*/
private namespace?;
/**
* Flag to determine if an error should be thrown when no metrics are recorded
* @default false
*/
private shouldThrowOnEmptyMetrics;
/**
* Storage for metrics before they are published
* @default {}
*/
private storedMetrics;

@@ -120,4 +156,4 @@ constructor(options?: MetricsOptions);

* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name
* @param value
* @param name The name of the dimension
* @param value The value of the dimension
*/

@@ -175,5 +211,5 @@ addDimension(name: string, value: string): void;

*
* @param name - The metric name
* @param unit - The metric unit
* @param value - The metric value
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution

@@ -242,3 +278,3 @@ */

*
* @decorator Class
* @param options - The options to configure the logMetrics decorator
*/

@@ -276,3 +312,3 @@ logMetrics(options?: ExtraOptions): HandlerMethodDecorator;

/**
* Sets default dimensions that will be added to all metrics.
* Set default dimensions that will be added to all metrics.
*

@@ -328,15 +364,11 @@ * @param dimensions The default dimensions to be added to all metrics.

/**
* Gets the custom config service if it exists.
*
* @returns the custom config service if it exists, undefined otherwise
* Get the custom config service if it exists.
*/
private getCustomConfigService;
/**
* Gets the environment variables service.
*
* @returns the environment variables service
* Get the environment variables service.
*/
private getEnvVarsService;
/**
* Checks if a metric is new or not.
* Check if a metric is new or not.
*

@@ -351,7 +383,6 @@ * A metric is considered new if there is no metric with the same name already stored.

* @param unit The unit of the metric
* @returns true if the metric is new, false if another metric with the same name already exists
*/
private isNewMetric;
/**
* It initializes 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.

@@ -364,3 +395,3 @@ *

/**
* Sets the custom config service to be used.
* Set the custom config service to be used.
*

@@ -371,7 +402,7 @@ * @param customConfigService The custom config service to be used

/**
* Sets the environment variables service to be used.
* Set the environment variables service to be used.
*/
private setEnvVarsService;
/**
* Sets the namespace to be used.
* Set the namespace to be used.
*

@@ -382,3 +413,3 @@ * @param namespace The namespace to be used

/**
* Sets the options to be used by the Metrics instance.
* Set the options to be used by the Metrics instance.
*

@@ -388,7 +419,6 @@ * This method is used during the initialization of the Metrics instance.

* @param options The options to be used
* @returns the Metrics instance
*/
private setOptions;
/**
* Sets the service to be used.
* Set the service to be used.
*

@@ -399,3 +429,3 @@ * @param service The service to be used

/**
* Stores a metric in the buffer.
* Store a metric in the buffer.
*

@@ -402,0 +432,0 @@ * If the buffer is full, or the metric reaches the maximum number of values,

@@ -44,3 +44,3 @@ import { Console } from 'node:console';

*
* If you are used to TypeScript Class usage to encapsulate your Lambda handler you can leverage the [@metrics.logMetrics()](./_aws_lambda_powertools_metrics.Metrics.html#logMetrics) decorator to automatically:
* 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

@@ -103,11 +103,47 @@ * * flush buffered metrics

console;
/**
* Custom configuration service for metrics
*/
customConfigService;
/**
* Default dimensions to be added to all metrics
* @default {}
*/
defaultDimensions = {};
/**
* Additional dimensions for the current metrics context
* @default {}
*/
dimensions = {};
/**
* Service for accessing environment variables
*/
envVarsService;
/**
* Name of the Lambda function
*/
functionName;
/**
* Flag indicating if this is a single metric instance
* @default false
*/
isSingleMetric = false;
/**
* Additional metadata to be included with metrics
* @default {}
*/
metadata = {};
/**
* Namespace for the metrics
*/
namespace;
/**
* Flag to determine if an error should be thrown when no metrics are recorded
* @default false
*/
shouldThrowOnEmptyMetrics = false;
/**
* Storage for metrics before they are published
* @default {}
*/
storedMetrics = {};

@@ -125,4 +161,4 @@ constructor(options = {}) {

* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#Dimension for more details.
* @param name
* @param value
* @param name The name of the dimension
* @param value The value of the dimension
*/

@@ -194,5 +230,5 @@ addDimension(name, value) {

*
* @param name - The metric name
* @param unit - The metric unit
* @param value - The metric value
* @param name The metric name
* @param unit The metric unit
* @param value The metric value
* @param resolution - The metric resolution

@@ -286,3 +322,3 @@ */

*
* @decorator Class
* @param options - The options to configure the logMetrics decorator
*/

@@ -337,9 +373,9 @@ logMetrics(options = {}) {

publishStoredMetrics() {
if (!this.shouldThrowOnEmptyMetrics &&
Object.keys(this.storedMetrics).length === 0) {
const hasMetrics = Object.keys(this.storedMetrics).length > 0;
if (!this.shouldThrowOnEmptyMetrics && !hasMetrics) {
console.warn('No application metrics to publish. The cold-start metric may be published if enabled. ' +
'If application metrics should never be empty, consider using `throwOnEmptyMetrics`');
}
const target = this.serializeMetrics();
this.console.log(JSON.stringify(target));
const emfOutput = this.serializeMetrics();
hasMetrics && this.console.log(JSON.stringify(emfOutput));
this.clearMetrics();

@@ -403,3 +439,3 @@ this.clearDimensions();

/**
* Sets default dimensions that will be added to all metrics.
* Set default dimensions that will be added to all metrics.
*

@@ -478,5 +514,3 @@ * @param dimensions The default dimensions to be added to all metrics.

/**
* Gets the custom config service if it exists.
*
* @returns the custom config service if it exists, undefined otherwise
* Get the custom config service if it exists.
*/

@@ -487,5 +521,3 @@ getCustomConfigService() {

/**
* Gets the environment variables service.
*
* @returns the environment variables service
* Get the environment variables service.
*/

@@ -496,3 +528,3 @@ getEnvVarsService() {

/**
* Checks if a metric is new or not.
* Check if a metric is new or not.
*

@@ -507,3 +539,2 @@ * A metric is considered new if there is no metric with the same name already stored.

* @param unit The unit of the metric
* @returns true if the metric is new, false if another metric with the same name already exists
*/

@@ -521,3 +552,3 @@ isNewMetric(name, unit) {

/**
* It initializes 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.

@@ -540,3 +571,3 @@ *

/**
* Sets the custom config service to be used.
* Set the custom config service to be used.
*

@@ -551,3 +582,3 @@ * @param customConfigService The custom config service to be used

/**
* Sets the environment variables service to be used.
* Set the environment variables service to be used.
*/

@@ -558,3 +589,3 @@ setEnvVarsService() {

/**
* Sets the namespace to be used.
* Set the namespace to be used.
*

@@ -569,3 +600,3 @@ * @param namespace The namespace to be used

/**
* Sets the options to be used by the Metrics instance.
* Set the options to be used by the Metrics instance.
*

@@ -575,3 +606,2 @@ * This method is used during the initialization of the Metrics instance.

* @param options The options to be used
* @returns the Metrics instance
*/

@@ -590,3 +620,3 @@ setOptions(options) {

/**
* Sets the service to be used.
* Set the service to be used.
*

@@ -605,3 +635,3 @@ * @param service The service to be used

/**
* Stores a metric in the buffer.
* Store a metric in the buffer.
*

@@ -608,0 +638,0 @@ * If the buffer is full, or the metric reaches the maximum number of values,

@@ -30,3 +30,2 @@ import type { MiddlewareLikeObj } from '@aws-lambda-powertools/commons/types';

* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/

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

@@ -28,3 +28,2 @@ import { METRICS_KEY } from '@aws-lambda-powertools/commons';

* @param options - (_optional_) Options for the middleware
* @returns middleware - The middy middleware object
*/

@@ -31,0 +30,0 @@ const logMetrics = (target, options = {}) => {

{
"name": "@aws-lambda-powertools/metrics",
"version": "2.7.0",
"version": "2.8.0",
"description": "The metrics package for the Powertools for AWS Lambda (TypeScript) library",

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

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

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

@@ -7,13 +7,8 @@ # Powertools for AWS Lambda (TypeScript) <!-- omit in toc -->

> Also available in [Python](https://github.com/aws-powertools/powertools-lambda-python), [Java](https://github.com/aws-powertools/powertools-lambda-java), and [.NET](https://github.com/aws-powertools/powertools-lambda-dotnet).
**[Documentation](https://docs.powertools.aws.dev/lambda/typescript/)** | **[npm](https://www.npmjs.com/org/aws-lambda-powertools)** | **[Roadmap](https://docs.powertools.aws.dev/lambda/typescript/latest/roadmap)** | **[Examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples)** | **[Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo)**
## Table of contents <!-- omit in toc -->
- [Features](#features)
- [Getting started](#getting-started)
- [Installation](#installation)
- [Examples](#examples)
- [Demo applications](#demo-applications)
- [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)
- [Contribute](#contribute)

@@ -26,48 +21,151 @@ - [Roadmap](#roadmap)

- [Using Lambda Layer](#using-lambda-layer)
- [Credits](#credits)
- [License](#license)
## Features
## Intro
- **[Tracer](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer/)** - Utilities to trace Lambda function handlers, and both synchronous and asynchronous functions
- **[Logger](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger/)** - Structured logging made easier, and a middleware to enrich log items with key details of the Lambda context
- **[Metrics](https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics/)** - Custom Metrics created asynchronously via CloudWatch Embedded Metric Format (EMF)
- **[Parameters](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/parameters/)** - High-level functions to retrieve one or more parameters from AWS SSM, Secrets Manager, AppConfig, and DynamoDB
## Usage
## Getting started
To get started, install the library by running:
Find the complete project's [documentation here](https://docs.powertools.aws.dev/lambda/typescript).
```sh
npm i @aws-lambda-powertools/metrics
```
### Installation
### Basic usage
The Powertools for AWS Lambda (TypeScript) utilities follow a modular approach, similar to the official [AWS SDK v3 for JavaScript](https://github.com/aws/aws-sdk-js-v3).
Each TypeScript utility is installed as standalone NPM package.
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).
Install all three core utilities at once with this single command:
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
```shell
npm install @aws-lambda-powertools/logger @aws-lambda-powertools/tracer @aws-lambda-powertools/metrics
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
export const handler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
};
```
Or refer to the installation guide of each utility:
### Flushing metrics
πŸ‘‰ [Installation guide for the **Tracer** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/tracer#getting-started)
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.
πŸ‘‰ [Installation guide for the **Logger** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/logger#getting-started)
You can flush metrics automatically using one of the following methods:
πŸ‘‰ [Installation guide for the **Metrics** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/core/metrics#getting-started)
- manually by calling `publishStoredMetrics()` at the end of your Lambda function
πŸ‘‰ [Installation guide for the **Parameters** utility](https://docs.powertools.aws.dev/lambda/typescript/latest/utilities/parameters/#getting-started)
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
### Examples
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
You can find examples of how to use Powertools for AWS Lambda (TypeScript) in the [examples](https://github.com/aws-powertools/powertools-lambda-typescript/tree/main/examples/app) directory. The application is a simple REST API that can be deployed via either AWS CDK or AWS SAM.
export const handler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.publishStoredMetrics();
};
```
### Demo applications
- middy compatible middleware `logMetrics()`
The [Serverless TypeScript Demo](https://github.com/aws-samples/serverless-typescript-demo) shows how to use Powertools for AWS Lambda (TypeScript).
You can find instructions on how to deploy and load test this application in the [repository](https://github.com/aws-samples/serverless-typescript-demo).
```ts
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
import middy from '@middy/core';
The [AWS Lambda performance tuning](https://github.com/aws-samples/optimizations-for-lambda-functions) repository also uses Powertools for AWS Lambda (TypeScript) as well as demonstrating other performance tuning techniques for Lambda functions written in TypeScript.
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
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 { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
class Lambda implements LambdaInterface {
@metrics.logMetrics()
public async handler(_event: unknown, _context: unknown): Promise<void> {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
}
}
const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);
```
Using the Middy middleware or decorator will automatically validate, serialize, and flush all your metrics.
### Capturing cold start as a metric
You can optionally capture cold start metrics with the logMetrics middleware or decorator via the captureColdStartMetric param.
```ts
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
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 { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
import middy from '@middy/core';
const metrics = new Metrics({
namespace: 'serverlessAirline',
serviceName: 'orders',
});
const lambdaHandler = async (
_event: unknown,
_context: unknown
): Promise<void> => {
metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
metrics.addMetadata('bookingId', '7051cd10-6283-11ec-90d6-0242ac120003');
};
export const handler = middy(lambdaHandler).use(logMetrics(metrics));
```
## Contribute

@@ -91,3 +189,6 @@

Knowing which companies are using this library is important to help prioritize the project internally. If your company is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by raising a [Support Powertools for AWS Lambda (TypeScript) (become a reference)](https://github.com/aws-powertools/powertools-lambda-typescript/issues/new?assignees=&labels=customer-reference&template=support_powertools.yml&title=%5BSupport+Lambda+Powertools%5D%3A+%3Cyour+organization+name%3E) issue.
Knowing which companies are using this library is important to help prioritize the project internally. If your company
is using Powertools for AWS Lambda (TypeScript), you can request to have your name and logo added to the README file by
raising a [Support Powertools for AWS Lambda (TypeScript) (become a reference)](https://s12d.com/become-reference-pt-ts)
issue.

@@ -118,10 +219,6 @@ The following companies, among others, use Powertools:

This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When [using Layers](#lambda-layers), you can add Powertools for AWS Lambda (TypeScript) as a dev dependency (or as part of your virtual env) to not impact the development process.
This helps us understand who uses Powertools for AWS Lambda (TypeScript) in a non-intrusive way, and helps us gain future investments for other Powertools for AWS Lambda languages. When [using Layers](https://docs.powertools.aws.dev/lambda/typescript/latest/#lambda-layer), you can add Powertools as a dev dependency to not impact the development process.
## Credits
Credits for the Powertools for AWS Lambda (TypeScript) idea go to [DAZN](https://github.com/getndazn) and their [DAZN Lambda Powertools](https://github.com/getndazn/dazn-lambda-powertools/).
## License
This library is licensed under the MIT-0 License. See the LICENSE file.

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