New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@aws-lambda-powertools/metrics

Package Overview
Dependencies
Maintainers
3
Versions
99
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.10.0 to 2.11.0

12

lib/cjs/constants.d.ts

@@ -22,2 +22,12 @@ /**

/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 14 days.
*/
declare const EMF_MAX_TIMESTAMP_PAST_AGE: number;
/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 2 hours.
*/
declare const EMF_MAX_TIMESTAMP_FUTURE_AGE: number;
/**
* The unit of the metric.

@@ -66,3 +76,3 @@ *

};
export { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MAX_DIMENSION_COUNT, MetricUnit, MetricResolution, };
export { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MAX_DIMENSION_COUNT, MetricUnit, MetricResolution, EMF_MAX_TIMESTAMP_PAST_AGE, EMF_MAX_TIMESTAMP_FUTURE_AGE, };
//# sourceMappingURL=constants.d.ts.map
"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;
exports.EMF_MAX_TIMESTAMP_FUTURE_AGE = exports.EMF_MAX_TIMESTAMP_PAST_AGE = 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;
/**

@@ -30,2 +30,14 @@ * The dimension key for the cold start metric.

/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 14 days.
*/
const EMF_MAX_TIMESTAMP_PAST_AGE = 14 * 24 * 60 * 60 * 1000;
exports.EMF_MAX_TIMESTAMP_PAST_AGE = EMF_MAX_TIMESTAMP_PAST_AGE;
/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 2 hours.
*/
const EMF_MAX_TIMESTAMP_FUTURE_AGE = 2 * 60 * 60 * 1000;
exports.EMF_MAX_TIMESTAMP_FUTURE_AGE = EMF_MAX_TIMESTAMP_FUTURE_AGE;
/**
* The unit of the metric.

@@ -32,0 +44,0 @@ *

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

declare class Metrics extends Utility implements MetricsInterface {
#private;
/**

@@ -163,2 +164,3 @@ * Console instance used to print logs.

* 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.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -177,2 +179,3 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

* This method is useful when you want to add multiple dimensions to the metrics at once.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -346,2 +349,6 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

/**
* Check if there are stored metrics in the buffer.
*/
hasStoredMetrics(): boolean;
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.

@@ -409,2 +416,33 @@ *

/**
* Sets the timestamp for the metric.
*
* If an integer is provided, it is assumed to be the epoch time in milliseconds.
* If a Date object is provided, it will be converted to epoch time in milliseconds.
*
* The timestamp must be a Date object or an integer representing an epoch time.
* This should not exceed 14 days in the past or be more than 2 hours in the future.
* Any metrics failing to meet this criteria will be skipped by Amazon CloudWatch.
*
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html
*
* @example
* ```typescript
* import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* export const handler = async () => {
* const metricTimestamp = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours ago
* metrics.setTimestamp(metricTimestamp);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* };
* ```
* @param timestamp - The timestamp to set, which can be a number or a Date object.
*/
setTimestamp(timestamp: number | Date): void;
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.

@@ -411,0 +449,0 @@ *

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

const node_console_1 = require("node:console");
const types_1 = require("node:util/types");
const commons_1 = require("@aws-lambda-powertools/commons");

@@ -139,2 +140,8 @@ const EnvironmentVariablesService_js_1 = require("./config/EnvironmentVariablesService.js");

/**
* Custom logger object used for emitting debug, warning, and error messages.
*
* Note that this logger is not used for emitting metrics which are emitted to standard output using the `Console` object.
*/
#logger;
/**
* Flag indicating if this is a single metric instance

@@ -163,2 +170,6 @@ * @default false

storedMetrics = {};
/**
* Custom timestamp for the metrics
*/
#timestamp;
constructor(options = {}) {

@@ -168,2 +179,3 @@ super();

this.setOptions(options);
this.#logger = options.logger || this.console;
}

@@ -174,2 +186,3 @@ /**

* 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.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -184,2 +197,6 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

addDimension(name, value) {
if (!value) {
this.#logger.warn(`The dimension ${name} doesn't meet the requirements and won't be added. Ensure the dimension name and value are non empty strings`);
return;
}
if (constants_js_1.MAX_DIMENSION_COUNT <= this.getCurrentDimensionsCount()) {

@@ -194,2 +211,3 @@ throw new RangeError(`The number of metric dimensions must be lower than ${constants_js_1.MAX_DIMENSION_COUNT}`);

* This method is useful when you want to add multiple dimensions to the metrics at once.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -205,3 +223,9 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

for (const dimensionName of Object.keys(dimensions)) {
newDimensions[dimensionName] = dimensions[dimensionName];
const value = dimensions[dimensionName];
if (value) {
newDimensions[dimensionName] = value;
}
else {
this.#logger.warn(`The dimension ${dimensionName} doesn't meet the requirements and won't be added. Ensure the dimension name and value are non empty strings`);
}
}

@@ -400,2 +424,8 @@ if (Object.keys(newDimensions).length > constants_js_1.MAX_DIMENSION_COUNT) {

/**
* Check if there are stored metrics in the buffer.
*/
hasStoredMetrics() {
return Object.keys(this.storedMetrics).length > 0;
}
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.

@@ -491,5 +521,5 @@ *

publishStoredMetrics() {
const hasMetrics = Object.keys(this.storedMetrics).length > 0;
const hasMetrics = this.hasStoredMetrics();
if (!this.shouldThrowOnEmptyMetrics && !hasMetrics) {
console.warn('No application metrics to publish. The cold-start metric may be published if enabled. ' +
this.#logger.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`');

@@ -504,2 +534,39 @@ }

/**
* Sets the timestamp for the metric.
*
* If an integer is provided, it is assumed to be the epoch time in milliseconds.
* If a Date object is provided, it will be converted to epoch time in milliseconds.
*
* The timestamp must be a Date object or an integer representing an epoch time.
* This should not exceed 14 days in the past or be more than 2 hours in the future.
* Any metrics failing to meet this criteria will be skipped by Amazon CloudWatch.
*
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html
*
* @example
* ```typescript
* import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* export const handler = async () => {
* const metricTimestamp = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours ago
* metrics.setTimestamp(metricTimestamp);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* };
* ```
* @param timestamp - The timestamp to set, which can be a number or a Date object.
*/
setTimestamp(timestamp) {
if (!this.#validateEmfTimestamp(timestamp)) {
this.#logger.warn("This metric doesn't meet the requirements and will be skipped by Amazon CloudWatch. " +
'Ensure the timestamp is within 14 days in the past or up to 2 hours in the future and is also a valid number or Date object.');
}
this.#timestamp = this.#convertTimestampToEmfFormat(timestamp);
}
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.

@@ -529,3 +596,3 @@ *

if (!this.namespace)
console.warn('Namespace should be defined, default used');
this.#logger.warn('Namespace should be defined, default used');
// We reduce the stored metrics to a single object with the metric

@@ -545,3 +612,3 @@ // name as the key and the value as the value.

_aws: {
Timestamp: new Date().getTime(),
Timestamp: this.#timestamp ?? new Date().getTime(),
CloudWatchMetrics: [

@@ -664,2 +731,3 @@ {

singleMetric: true,
logger: this.#logger,
});

@@ -823,3 +891,43 @@ }

}
/**
* Validates a given timestamp based on CloudWatch Timestamp guidelines.
*
* Timestamp must meet CloudWatch requirements.
* The time stamp can be up to two weeks in the past and up to two hours into the future.
* See [Timestamps](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#about_timestamp)
* for valid values.
*
* @param timestamp - Date object or epoch time in milliseconds representing the timestamp to validate.
*/
#validateEmfTimestamp(timestamp) {
if (!(0, types_1.isDate)(timestamp) && !(0, commons_1.isIntegerNumber)(timestamp)) {
return false;
}
const timestampMs = (0, types_1.isDate)(timestamp) ? timestamp.getTime() : timestamp;
const currentTime = new Date().getTime();
const minValidTimestamp = currentTime - constants_js_1.EMF_MAX_TIMESTAMP_PAST_AGE;
const maxValidTimestamp = currentTime + constants_js_1.EMF_MAX_TIMESTAMP_FUTURE_AGE;
return timestampMs >= minValidTimestamp && timestampMs <= maxValidTimestamp;
}
/**
* Converts a given timestamp to EMF compatible format.
*
* @param timestamp - The timestamp to convert, which can be either a number (in milliseconds) or a Date object.
* @returns The timestamp in milliseconds. If the input is invalid, returns 0.
*/
#convertTimestampToEmfFormat(timestamp) {
if ((0, commons_1.isIntegerNumber)(timestamp)) {
return timestamp;
}
if ((0, types_1.isDate)(timestamp)) {
return timestamp.getTime();
}
/**
* If this point is reached, it indicates timestamp was neither a valid number nor Date
* Returning zero represents the initial date of epoch time,
* which will be skipped by Amazon CloudWatch.
**/
return 0;
}
}
exports.Metrics = Metrics;

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

import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { GenericLogger, HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { MetricResolution as MetricResolutions, MetricUnit as MetricUnits } from '../constants.js';

@@ -55,2 +55,11 @@ import type { ConfigServiceInterface } from './ConfigServiceInterface.js';

defaultDimensions?: Dimensions;
/**
* Logger object to be used for emitting debug, warning, and error messages.
*
* If not provided, debug messages will be suppressed, and warning and error messages will be sent to stdout.
*
* Note that EMF metrics are always sent directly to stdout, regardless of the logger
* to avoid compatibility issues with custom loggers.
*/
logger?: GenericLogger;
};

@@ -449,2 +458,33 @@ /**

/**
* Sets the timestamp for the metric.
*
* If an integer is provided, it is assumed to be the epoch time in milliseconds.
* If a Date object is provided, it will be converted to epoch time in milliseconds.
*
* The timestamp must be a Date object or an integer representing an epoch time.
* This should not exceed 14 days in the past or be more than 2 hours in the future.
* Any metrics failing to meet this criteria will be skipped by Amazon CloudWatch.
*
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html
*
* @example
* ```typescript
* import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* export const handler = async () => {
* const metricTimestamp = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours ago
* metrics.setTimestamp(metricTimestamp);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* };
* ```
* @param timestamp - The timestamp to set, which can be a number or a Date object.
*/
setTimestamp(timestamp: number | Date): void;
/**
* Create a new Metrics instance configured to immediately flush a single metric.

@@ -451,0 +491,0 @@ *

@@ -22,2 +22,12 @@ /**

/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 14 days.
*/
declare const EMF_MAX_TIMESTAMP_PAST_AGE: number;
/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 2 hours.
*/
declare const EMF_MAX_TIMESTAMP_FUTURE_AGE: number;
/**
* The unit of the metric.

@@ -66,3 +76,3 @@ *

};
export { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MAX_DIMENSION_COUNT, MetricUnit, MetricResolution, };
export { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MAX_DIMENSION_COUNT, MetricUnit, MetricResolution, EMF_MAX_TIMESTAMP_PAST_AGE, EMF_MAX_TIMESTAMP_FUTURE_AGE, };
//# sourceMappingURL=constants.d.ts.map

@@ -22,2 +22,12 @@ /**

/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 14 days.
*/
const EMF_MAX_TIMESTAMP_PAST_AGE = 14 * 24 * 60 * 60 * 1000;
/**
* The maximum age of a timestamp in milliseconds that can be emitted in a metric.
* This is set to 2 hours.
*/
const EMF_MAX_TIMESTAMP_FUTURE_AGE = 2 * 60 * 60 * 1000;
/**
* The unit of the metric.

@@ -66,2 +76,2 @@ *

};
export { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MAX_DIMENSION_COUNT, MetricUnit, MetricResolution, };
export { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MAX_DIMENSION_COUNT, MetricUnit, MetricResolution, EMF_MAX_TIMESTAMP_PAST_AGE, EMF_MAX_TIMESTAMP_FUTURE_AGE, };

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

declare class Metrics extends Utility implements MetricsInterface {
#private;
/**

@@ -163,2 +164,3 @@ * Console instance used to print logs.

* 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.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -177,2 +179,3 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

* This method is useful when you want to add multiple dimensions to the metrics at once.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -346,2 +349,6 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

/**
* Check if there are stored metrics in the buffer.
*/
hasStoredMetrics(): boolean;
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.

@@ -409,2 +416,33 @@ *

/**
* Sets the timestamp for the metric.
*
* If an integer is provided, it is assumed to be the epoch time in milliseconds.
* If a Date object is provided, it will be converted to epoch time in milliseconds.
*
* The timestamp must be a Date object or an integer representing an epoch time.
* This should not exceed 14 days in the past or be more than 2 hours in the future.
* Any metrics failing to meet this criteria will be skipped by Amazon CloudWatch.
*
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html
*
* @example
* ```typescript
* import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* export const handler = async () => {
* const metricTimestamp = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours ago
* metrics.setTimestamp(metricTimestamp);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* };
* ```
* @param timestamp - The timestamp to set, which can be a number or a Date object.
*/
setTimestamp(timestamp: number | Date): void;
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.

@@ -411,0 +449,0 @@ *

import { Console } from 'node:console';
import { Utility } from '@aws-lambda-powertools/commons';
import { isDate } from 'node:util/types';
import { Utility, isIntegerNumber } from '@aws-lambda-powertools/commons';
import { EnvironmentVariablesService } from './config/EnvironmentVariablesService.js';
import { COLD_START_METRIC, DEFAULT_NAMESPACE, MAX_DIMENSION_COUNT, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MetricResolution as MetricResolutions, MetricUnit as MetricUnits, } from './constants.js';
import { COLD_START_METRIC, DEFAULT_NAMESPACE, EMF_MAX_TIMESTAMP_FUTURE_AGE, EMF_MAX_TIMESTAMP_PAST_AGE, MAX_DIMENSION_COUNT, MAX_METRICS_SIZE, MAX_METRIC_VALUES_SIZE, MetricResolution as MetricResolutions, MetricUnit as MetricUnits, } from './constants.js';
/**

@@ -135,2 +136,8 @@ * 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)}.

/**
* Custom logger object used for emitting debug, warning, and error messages.
*
* Note that this logger is not used for emitting metrics which are emitted to standard output using the `Console` object.
*/
#logger;
/**
* Flag indicating if this is a single metric instance

@@ -159,2 +166,6 @@ * @default false

storedMetrics = {};
/**
* Custom timestamp for the metrics
*/
#timestamp;
constructor(options = {}) {

@@ -164,2 +175,3 @@ super();

this.setOptions(options);
this.#logger = options.logger || this.console;
}

@@ -170,2 +182,3 @@ /**

* 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.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -180,2 +193,6 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

addDimension(name, value) {
if (!value) {
this.#logger.warn(`The dimension ${name} doesn't meet the requirements and won't be added. Ensure the dimension name and value are non empty strings`);
return;
}
if (MAX_DIMENSION_COUNT <= this.getCurrentDimensionsCount()) {

@@ -190,2 +207,3 @@ throw new RangeError(`The number of metric dimensions must be lower than ${MAX_DIMENSION_COUNT}`);

* This method is useful when you want to add multiple dimensions to the metrics at once.
* Invalid dimension values are skipped and a warning is logged.
*

@@ -201,3 +219,9 @@ * When calling the {@link Metrics.publishStoredMetrics | `publishStoredMetrics()`} method, the dimensions are cleared. This type of

for (const dimensionName of Object.keys(dimensions)) {
newDimensions[dimensionName] = dimensions[dimensionName];
const value = dimensions[dimensionName];
if (value) {
newDimensions[dimensionName] = value;
}
else {
this.#logger.warn(`The dimension ${dimensionName} doesn't meet the requirements and won't be added. Ensure the dimension name and value are non empty strings`);
}
}

@@ -396,2 +420,8 @@ if (Object.keys(newDimensions).length > MAX_DIMENSION_COUNT) {

/**
* Check if there are stored metrics in the buffer.
*/
hasStoredMetrics() {
return Object.keys(this.storedMetrics).length > 0;
}
/**
* A class method decorator to automatically log metrics after the method returns or throws an error.

@@ -487,5 +517,5 @@ *

publishStoredMetrics() {
const hasMetrics = Object.keys(this.storedMetrics).length > 0;
const hasMetrics = this.hasStoredMetrics();
if (!this.shouldThrowOnEmptyMetrics && !hasMetrics) {
console.warn('No application metrics to publish. The cold-start metric may be published if enabled. ' +
this.#logger.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`');

@@ -500,2 +530,39 @@ }

/**
* Sets the timestamp for the metric.
*
* If an integer is provided, it is assumed to be the epoch time in milliseconds.
* If a Date object is provided, it will be converted to epoch time in milliseconds.
*
* The timestamp must be a Date object or an integer representing an epoch time.
* This should not exceed 14 days in the past or be more than 2 hours in the future.
* Any metrics failing to meet this criteria will be skipped by Amazon CloudWatch.
*
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html
*
* @example
* ```typescript
* import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* export const handler = async () => {
* const metricTimestamp = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours ago
* metrics.setTimestamp(metricTimestamp);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* };
* ```
* @param timestamp - The timestamp to set, which can be a number or a Date object.
*/
setTimestamp(timestamp) {
if (!this.#validateEmfTimestamp(timestamp)) {
this.#logger.warn("This metric doesn't meet the requirements and will be skipped by Amazon CloudWatch. " +
'Ensure the timestamp is within 14 days in the past or up to 2 hours in the future and is also a valid number or Date object.');
}
this.#timestamp = this.#convertTimestampToEmfFormat(timestamp);
}
/**
* Serialize the stored metrics into a JSON object compliant with the Amazon CloudWatch EMF (Embedded Metric Format) schema.

@@ -525,3 +592,3 @@ *

if (!this.namespace)
console.warn('Namespace should be defined, default used');
this.#logger.warn('Namespace should be defined, default used');
// We reduce the stored metrics to a single object with the metric

@@ -541,3 +608,3 @@ // name as the key and the value as the value.

_aws: {
Timestamp: new Date().getTime(),
Timestamp: this.#timestamp ?? new Date().getTime(),
CloudWatchMetrics: [

@@ -660,2 +727,3 @@ {

singleMetric: true,
logger: this.#logger,
});

@@ -819,3 +887,43 @@ }

}
/**
* Validates a given timestamp based on CloudWatch Timestamp guidelines.
*
* Timestamp must meet CloudWatch requirements.
* The time stamp can be up to two weeks in the past and up to two hours into the future.
* See [Timestamps](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/cloudwatch_concepts.html#about_timestamp)
* for valid values.
*
* @param timestamp - Date object or epoch time in milliseconds representing the timestamp to validate.
*/
#validateEmfTimestamp(timestamp) {
if (!isDate(timestamp) && !isIntegerNumber(timestamp)) {
return false;
}
const timestampMs = isDate(timestamp) ? timestamp.getTime() : timestamp;
const currentTime = new Date().getTime();
const minValidTimestamp = currentTime - EMF_MAX_TIMESTAMP_PAST_AGE;
const maxValidTimestamp = currentTime + EMF_MAX_TIMESTAMP_FUTURE_AGE;
return timestampMs >= minValidTimestamp && timestampMs <= maxValidTimestamp;
}
/**
* Converts a given timestamp to EMF compatible format.
*
* @param timestamp - The timestamp to convert, which can be either a number (in milliseconds) or a Date object.
* @returns The timestamp in milliseconds. If the input is invalid, returns 0.
*/
#convertTimestampToEmfFormat(timestamp) {
if (isIntegerNumber(timestamp)) {
return timestamp;
}
if (isDate(timestamp)) {
return timestamp.getTime();
}
/**
* If this point is reached, it indicates timestamp was neither a valid number nor Date
* Returning zero represents the initial date of epoch time,
* which will be skipped by Amazon CloudWatch.
**/
return 0;
}
}
export { Metrics };

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

import type { HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { GenericLogger, HandlerMethodDecorator } from '@aws-lambda-powertools/commons/types';
import type { MetricResolution as MetricResolutions, MetricUnit as MetricUnits } from '../constants.js';

@@ -55,2 +55,11 @@ import type { ConfigServiceInterface } from './ConfigServiceInterface.js';

defaultDimensions?: Dimensions;
/**
* Logger object to be used for emitting debug, warning, and error messages.
*
* If not provided, debug messages will be suppressed, and warning and error messages will be sent to stdout.
*
* Note that EMF metrics are always sent directly to stdout, regardless of the logger
* to avoid compatibility issues with custom loggers.
*/
logger?: GenericLogger;
};

@@ -449,2 +458,33 @@ /**

/**
* Sets the timestamp for the metric.
*
* If an integer is provided, it is assumed to be the epoch time in milliseconds.
* If a Date object is provided, it will be converted to epoch time in milliseconds.
*
* The timestamp must be a Date object or an integer representing an epoch time.
* This should not exceed 14 days in the past or be more than 2 hours in the future.
* Any metrics failing to meet this criteria will be skipped by Amazon CloudWatch.
*
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/CloudWatch_Embedded_Metric_Format_Specification.html
* See: https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/CloudWatch-Logs-Monitoring-CloudWatch-Metrics.html
*
* @example
* ```typescript
* import { MetricUnit, Metrics } from '@aws-lambda-powertools/metrics';
*
* const metrics = new Metrics({
* namespace: 'serverlessAirline',
* serviceName: 'orders',
* });
*
* export const handler = async () => {
* const metricTimestamp = new Date(Date.now() - 24 * 60 * 60 * 1000); // 24 hours ago
* metrics.setTimestamp(metricTimestamp);
* metrics.addMetric('successfulBooking', MetricUnit.Count, 1);
* };
* ```
* @param timestamp - The timestamp to set, which can be a number or a Date object.
*/
setTimestamp(timestamp: number | Date): void;
/**
* Create a new Metrics instance configured to immediately flush a single metric.

@@ -451,0 +491,0 @@ *

4

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

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

"dependencies": {
"@aws-lambda-powertools/commons": "^2.10.0"
"@aws-lambda-powertools/commons": "^2.11.0"
},

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

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