CloudWatch metrics represent data points that AWS services or your applications emit, such as CPU usage, error counts, or custom business metrics. This module provides comprehensive functionality for creating, configuring, and manipulating metrics.
Create and configure CloudWatch metrics with comprehensive options for dimensions, statistics, periods, and cross-account access.
/**
* A CloudWatch metric
*/
class Metric implements IMetric {
/**
* Create a new metric
* @param props - Metric configuration properties
*/
constructor(props: MetricProps);
/**
* Grant permissions to put metric data to CloudWatch
* @param grantee - The principal to grant permissions to
* @returns Grant object representing the permission
*/
static grantPutMetricData(grantee: iam.IGrantable): iam.Grant;
/**
* Return a copy of this metric with different properties
* @param props - Properties to override
* @returns New Metric instance with updated properties
*/
with(props: MetricOptions): Metric;
/**
* Attach the metric to a construct for automatic account/region detection
* @param scope - The construct to attach to
* @returns New Metric instance with attached scope
*/
attachTo(scope: IConstruct): Metric;
/**
* Turn this metric into an alarm configuration
* @returns Metric configuration for alarms
*/
toMetricConfig(): MetricConfig;
/**
* Make a new alarm for this metric
* @param scope - Construct scope
* @param id - Construct ID
* @param props - Alarm configuration properties
* @returns New Alarm instance
*/
createAlarm(scope: Construct, id: string, props: CreateAlarmOptions): Alarm;
/**
* Returns a string representation of this metric
*/
toString(): string;
readonly dimensions?: DimensionHash;
readonly namespace: string;
readonly metricName: string;
readonly period: Duration;
readonly statistic: string;
readonly label?: string;
readonly color?: string;
readonly unit?: Unit;
readonly account?: string;
readonly region?: string;
readonly warnings?: string[];
}
interface MetricProps extends CommonMetricOptions {
/** The namespace of the metric */
readonly namespace: string;
/** The name of the metric */
readonly metricName: string;
}
interface CommonMetricOptions {
/** The period over which the specified statistic is applied */
readonly period?: Duration;
/** What function to use for aggregating (Average, Sum, Min, Max, SampleCount, or pNN.NN) */
readonly statistic?: string;
/** Dimensions of the metric (deprecated, use dimensionsMap) */
readonly dimensions?: DimensionHash;
/** Dimensions of the metric as a map */
readonly dimensionsMap?: DimensionsMap;
/** Unit used to filter the metric stream */
readonly unit?: Unit;
/** Label for this metric when added to a Graph */
readonly label?: string;
/** Color for this metric when added to a Graph */
readonly color?: string;
/** Account which this metric comes from */
readonly account?: string;
/** Region which this metric comes from */
readonly region?: string;
}
interface MetricOptions extends CommonMetricOptions {}Usage Examples:
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as cdk from '@aws-cdk/core';
// Create a basic metric
const requestCount = new cloudwatch.Metric({
namespace: 'MyApp',
metricName: 'RequestCount',
dimensionsMap: {
Environment: 'Production',
Service: 'API'
},
statistic: 'Sum',
period: cdk.Duration.minutes(5)
});
// Create a metric with custom unit and color
const responseTime = new cloudwatch.Metric({
namespace: 'MyApp',
metricName: 'ResponseTime',
dimensionsMap: {
Environment: 'Production'
},
statistic: 'Average',
unit: cloudwatch.Unit.MILLISECONDS,
color: '#FF0000',
label: 'Avg Response Time'
});
// Cross-account metric
const crossAccountMetric = new cloudwatch.Metric({
namespace: 'AWS/Lambda',
metricName: 'Duration',
account: '123456789012',
region: 'us-west-2',
dimensionsMap: {
FunctionName: 'MyFunction'
}
});
// Grant permissions for custom metrics
cloudwatch.Metric.grantPutMetricData(myLambdaFunction);Combine and transform metrics using mathematical expressions with support for complex calculations and metric references.
/**
* A math expression built from one or more metrics
*/
class MathExpression implements IMetric {
/**
* Create a new math expression
* @param props - Math expression configuration
*/
constructor(props: MathExpressionProps);
/**
* Return a copy of this math expression with different properties
* @param props - Properties to override
* @returns New MathExpression with updated properties
*/
with(props: MathExpressionOptions): MathExpression;
/**
* Turn this math expression into a metric configuration
* @returns Metric configuration for use in alarms and graphs
*/
toMetricConfig(): MetricConfig;
/**
* Make a new alarm for this math expression
* @param scope - Construct scope
* @param id - Construct ID
* @param props - Alarm configuration properties
* @returns New Alarm instance
*/
createAlarm(scope: Construct, id: string, props: CreateAlarmOptions): Alarm;
/**
* Returns a string representation of this math expression
*/
toString(): string;
readonly expression: string;
readonly usingMetrics: Record<string, IMetric>;
readonly label?: string;
readonly color?: string;
readonly period: Duration;
readonly searchAccount?: string;
readonly searchRegion?: string;
readonly warnings?: string[];
}
interface MathExpressionProps extends MathExpressionOptions {
/** The expression defining the metric */
readonly expression: string;
/** The metrics used in the expression, mapped to their variable names */
readonly usingMetrics?: Record<string, IMetric>;
}
interface MathExpressionOptions {
/** Label for this expression when added to a Graph */
readonly label?: string;
/** Color for this expression when added to a Graph */
readonly color?: string;
/** The period over which the expression is evaluated */
readonly period?: Duration;
/** Account to search for metrics in */
readonly searchAccount?: string;
/** Region to search for metrics in */
readonly searchRegion?: string;
}Usage Examples:
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
// Basic math expression combining two metrics
const errors = new cloudwatch.Metric({
namespace: 'AWS/Lambda',
metricName: 'Errors',
dimensionsMap: { FunctionName: 'MyFunction' }
});
const invocations = new cloudwatch.Metric({
namespace: 'AWS/Lambda',
metricName: 'Invocations',
dimensionsMap: { FunctionName: 'MyFunction' }
});
const errorRate = new cloudwatch.MathExpression({
expression: 'errors / invocations * 100',
usingMetrics: {
errors: errors,
invocations: invocations
},
label: 'Error Rate (%)'
});
// Complex expression with multiple operations
const complexExpression = new cloudwatch.MathExpression({
expression: 'IF(invocations > 0, errors / invocations * 100, 0)',
usingMetrics: {
errors: errors,
invocations: invocations
},
label: 'Safe Error Rate'
});
// Using math expressions in other expressions
const totalProblems = new cloudwatch.MathExpression({
expression: 'errors + throttles',
usingMetrics: {
errors: errors,
throttles: new cloudwatch.Metric({
namespace: 'AWS/Lambda',
metricName: 'Throttles',
dimensionsMap: { FunctionName: 'MyFunction' }
})
}
});
const problemPercentage = new cloudwatch.MathExpression({
expression: 'problems / invocations * 100',
usingMetrics: {
problems: totalProblems,
invocations: invocations
}
});Core interfaces and types used throughout the metrics system.
interface IMetric {
/** Warnings attached to this metric */
readonly warnings?: string[];
/** Turn this metric into a configuration object */
toMetricConfig(): MetricConfig;
}
interface MetricConfig {
/** Configuration for a metric stat */
readonly metricStat?: MetricStatConfig;
/** Configuration for a math expression */
readonly mathExpression?: MetricExpressionConfig;
/** Additional rendering properties */
readonly renderingProperties?: Record<string, unknown>;
}
interface MetricStatConfig {
/** Dimensions for the metric */
readonly dimensions?: Dimension[];
/** Namespace of the metric */
readonly namespace: string;
/** Name of the metric */
readonly metricName: string;
/** Period over which the statistic is calculated */
readonly period: Duration;
/** Statistic to calculate */
readonly statistic: string;
/** Unit filter for the metric */
readonly unitFilter?: Unit;
/** Region where the metric is located */
readonly region?: string;
/** Account where the metric is located */
readonly account?: string;
}
interface MetricExpressionConfig {
/** The math expression */
readonly expression: string;
/** Metrics used in the expression */
readonly usingMetrics: Record<string, IMetric>;
/** Period in seconds */
readonly period: number;
/** Account to search for metrics */
readonly searchAccount?: string;
/** Region to search for metrics */
readonly searchRegion?: string;
}
interface Dimension {
/** Name of the dimension */
readonly name: string;
/** Value of the dimension */
readonly value: any;
}
enum Statistic {
/** The count (number) of data points used for the statistical calculation */
SAMPLE_COUNT = 'SampleCount',
/** The value of Sum / SampleCount during the specified period */
AVERAGE = 'Average',
/** All values submitted for the matching metric added together */
SUM = 'Sum',
/** The lowest value observed during the specified period */
MINIMUM = 'Minimum',
/** The highest value observed during the specified period */
MAXIMUM = 'Maximum'
}
/** Type alias for dimension hash */
type DimensionHash = {[dim: string]: any};
/** Type alias for dimensions map */
type DimensionsMap = { [dim: string]: string };