class Metrics {
constructor(options?: MetricsOptions);
// Core Operations
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;
publishStoredMetrics(): void;
hasStoredMetrics(): boolean;
clearMetrics(): void;
setThrowOnEmptyMetrics(enabled: boolean): void;
// Dimensions
addDimension(name: string, value: string): void;
addDimensions(dimensions: Dimensions): void;
setDefaultDimensions(dimensions: Dimensions): void;
clearDefaultDimensions(): void;
clearDimensions(): void;
// Metadata
addMetadata(key: string, value: string): void;
clearMetadata(): void;
// Automatic Flushing
logMetrics(options?: ExtraOptions): HandlerMethodDecorator;
// Cold Start
captureColdStartMetric(functionName?: string): void;
// Advanced
singleMetric(): Metrics;
setTimestamp(timestamp: number | Date): void;
serializeMetrics(): EmfOutput;
}constructor(options?: MetricsOptions);
interface MetricsOptions {
customConfigService?: ConfigServiceInterface;
namespace?: string; // Required for CloudWatch organization
serviceName?: string; // Added as default dimension
singleMetric?: boolean; // Immediately flush each metric
defaultDimensions?: Dimensions;
functionName?: string; // For cold start metric dimension
logger?: GenericLogger;
}Behavior: Creates Metrics instance. Namespace can be set via constructor, env var (POWERTOOLS_METRICS_NAMESPACE), or custom config service. Service name automatically added as default dimension if provided.
Errors: None thrown. Missing namespace logs warning when publishing.
addMetric(name: string, unit: MetricUnit, value: number, resolution?: MetricResolution): void;Behavior: Buffers metric until publishStoredMetrics() called. Auto-publishes at 100 metrics or 100 values per metric. In singleMetric mode, publishes immediately.
Errors: Throws Error if name invalid. Throws RangeError if name length not 1-255 chars, value not valid number, or unit/resolution invalid.
publishStoredMetrics(): void;Behavior: Flushes buffered metrics to stdout in EMF format. Clears metrics buffer, request-specific dimensions (not default), and metadata. Logs warning if no metrics (unless throwOnEmptyMetrics enabled).
Errors: Throws RangeError if throwOnEmptyMetrics enabled and no metrics recorded.
addDimension(name: string, value: string): void;
addDimensions(dimensions: Dimensions): void;
setDefaultDimensions(dimensions: Dimensions): void;
clearDefaultDimensions(): void;
clearDimensions(): void;
type Dimensions = Record<string, string>;addDimension/addDimensions: Request-specific dimensions included in all subsequent metrics until publishStoredMetrics() called. Warns if empty/null/undefined. Overwrites existing dimension with same name.
Errors: Throws RangeError if total dimensions exceed 29.
setDefaultDimensions: Persistent dimensions included in all metrics, not cleared by publishStoredMetrics(). Merges with existing defaults.
clearDefaultDimensions: Removes all default dimensions.
clearDimensions: Removes request-specific dimensions only. Automatically called by publishStoredMetrics().
addMetadata(key: string, value: string): void;
clearMetadata(): void;Behavior: Metadata included in EMF output, searchable in CloudWatch Logs, not shown in Metrics UI. Cleared by publishStoredMetrics(). No limit on entries.
logMetrics(options?: ExtraOptions): HandlerMethodDecorator;
interface ExtraOptions {
throwOnEmptyMetrics?: boolean;
defaultDimensions?: Dimensions;
captureColdStartMetric?: boolean;
}Behavior: Automatically publishes metrics after handler completes or throws error. Requires TypeScript with experimentalDecorators: true, handler as class method implementing LambdaInterface.
Usage:
import type { LambdaInterface } from '@aws-lambda-powertools/commons/types';
class Lambda implements LambdaInterface {
@metrics.logMetrics({ captureColdStartMetric: true, throwOnEmptyMetrics: true })
public async handler(event: any, context: Context) {
metrics.addMetric('invocations', MetricUnit.Count, 1);
}
}
const handlerClass = new Lambda();
export const handler = handlerClass.handler.bind(handlerClass);captureColdStartMetric(functionName?: string): void;Behavior: Emits ColdStart metric with value 1 only on cold starts. Flushed immediately with singleMetric(). No metric on warm starts. Function name resolved from: parameter > constructor > env var POWERTOOLS_METRICS_FUNCTION_NAME > Lambda context (decorator/middleware).
singleMetric(): Metrics;
setTimestamp(timestamp: number | Date): void;
serializeMetrics(): EmfOutput;
hasStoredMetrics(): boolean;
clearMetrics(): void;
setThrowOnEmptyMetrics(enabled: boolean): void;singleMetric: Returns new Metrics instance configured for immediate flushing. Each addMetric() publishes immediately. Inherits namespace and default dimensions. Use for different dimension sets per metric.
setTimestamp: Sets custom timestamp for metrics. Must be within 14 days past or 2 hours future. Invalid timestamps log warning.
serializeMetrics: Returns EMF-formatted object without publishing or clearing buffer. For testing or custom publishing.
hasStoredMetrics: Returns true if metrics buffered, false otherwise.
clearMetrics: Clears metrics buffer without publishing.
setThrowOnEmptyMetrics: When enabled, publishStoredMetrics() throws RangeError if no metrics. When disabled (default), logs warning.
function logMetrics(
target: Metrics | Metrics[],
options?: ExtraOptions
): MiddlewareLikeObj;
interface ExtraOptions {
throwOnEmptyMetrics?: boolean;
defaultDimensions?: Dimensions;
captureColdStartMetric?: boolean;
}Behavior: Middy.js middleware (v3.x-6.x) that automatically publishes metrics in after hook (success) and onError hook (error). Supports single or multiple Metrics instances.
Usage:
import { logMetrics } from '@aws-lambda-powertools/metrics/middleware';
import middy from '@middy/core';
const metrics = new Metrics({ namespace: 'app', serviceName: 'orders' });
const lambdaHandler = async (event: any) => {
metrics.addMetric('apiCall', MetricUnit.Count, 1);
};
export const handler = middy(lambdaHandler).use(
logMetrics(metrics, { captureColdStartMetric: true, throwOnEmptyMetrics: true })
);interface MetricsOptions {
customConfigService?: ConfigServiceInterface;
namespace?: string;
serviceName?: string;
singleMetric?: boolean;
defaultDimensions?: Dimensions;
functionName?: string;
logger?: GenericLogger;
}interface EmfOutput {
_aws: {
Timestamp: number;
CloudWatchMetrics: {
Namespace: string;
Dimensions: [string[]];
Metrics: MetricDefinition[];
}[];
};
[key: string]: string | number | object;
}
interface MetricDefinition {
Name: string;
Unit: MetricUnit;
StorageResolution?: MetricResolution;
}interface ConfigServiceInterface {
getNamespace(): string;
getFunctionName(): string;
getServiceName(): string;
}Usage: Custom configuration source. Resolution order: explicit constructor params > custom config service > env vars > defaults.
interface GenericLogger {
debug(message: string, ...args: unknown[]): void;
info(message: string, ...args: unknown[]): void;
warn(message: string, ...args: unknown[]): void;
error(message: string, ...args: unknown[]): void;
}Note: Only for debug/warning/error messages. EMF output always goes to stdout.
interface MiddlewareLikeObj {
before?: (request: MiddyLikeRequest) => unknown;
after?: (request: MiddyLikeRequest) => unknown;
onError?: (request: MiddyLikeRequest) => unknown;
}
interface MiddyLikeRequest {
event: unknown;
context: Context;
response: unknown;
error: Error | null;
internal: { [key: string]: unknown };
}type HandlerMethodDecorator = (
target: LambdaInterface,
propertyKey: string | symbol,
descriptor: TypedPropertyDescriptor<SyncHandler<Handler>> | TypedPropertyDescriptor<AsyncHandler<Handler>>
) => void | TypedPropertyDescriptor<SyncHandler<Handler>> | TypedPropertyDescriptor<AsyncHandler<Handler>>;