CloudWatch dashboards provide a customizable view of your AWS resources and applications in a unified dashboard. This module offers comprehensive dashboard functionality with multiple widget types for rich visualization and monitoring.
Create and configure CloudWatch dashboards with flexible widget management and time range controls.
/**
* A CloudWatch dashboard
*/
class Dashboard extends Resource {
/**
* Create a new dashboard
* @param scope - Construct scope
* @param id - Construct ID
* @param props - Dashboard configuration properties
*/
constructor(scope: Construct, id: string, props?: DashboardProps);
/**
* Add widgets to the dashboard
* @param widgets - Widgets to add to the dashboard
*/
addWidgets(...widgets: IWidget[]): void;
readonly dashboardName: string;
readonly dashboardArn: string;
}
interface DashboardProps {
/** Name of the dashboard */
readonly dashboardName?: string;
/** List of the widgets on the dashboard */
readonly widgets?: IWidget[][];
/** The start time for the dashboard */
readonly start?: string;
/** The end time for the dashboard */
readonly end?: string;
/** Specify the period for the graphs when the dashboard loads */
readonly periodOverride?: PeriodOverride;
}
enum PeriodOverride {
/** Period of all graphs on the dashboard automatically adapt to the time range */
AUTO = 'auto',
/** Period set for each graph will be used */
INHERIT = 'inherit'
}Usage Examples:
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
// Create a basic dashboard
const dashboard = new cloudwatch.Dashboard(this, 'MyDashboard', {
dashboardName: 'ApplicationMetrics',
start: '-PT6H', // Last 6 hours
periodOverride: cloudwatch.PeriodOverride.AUTO
});
// Add widgets to dashboard
dashboard.addWidgets(
new cloudwatch.GraphWidget({
title: 'CPU Usage',
left: [cpuMetric],
width: 12,
height: 6
}),
new cloudwatch.SingleValueWidget({
title: 'Request Count',
metrics: [requestMetric],
width: 12,
height: 6
})
);
// Dashboard with pre-configured widgets
const preConfiguredDashboard = new cloudwatch.Dashboard(this, 'PreConfigured', {
dashboardName: 'SystemOverview',
widgets: [
[graphWidget1, graphWidget2],
[singleValueWidget, alarmWidget]
]
});Create sophisticated graph widgets for time-series data visualization with multiple metrics and annotations.
/**
* A graph widget that displays metrics over time
*/
class GraphWidget extends ConcreteWidget {
/**
* Create a new graph widget
* @param props - Graph widget configuration properties
*/
constructor(props: GraphWidgetProps);
/**
* Add a metric to the left Y axis
* @param metric - The metric to add
*/
addLeftMetric(metric: IMetric): void;
/**
* Add a metric to the right Y axis
* @param metric - The metric to add
*/
addRightMetric(metric: IMetric): void;
}
interface GraphWidgetProps extends MetricWidgetProps {
/** Metrics to display on left Y axis */
readonly left?: IMetric[];
/** Metrics to display on right Y axis */
readonly right?: IMetric[];
/** Annotations for the left Y axis */
readonly leftAnnotations?: HorizontalAnnotation[];
/** Annotations for the right Y axis */
readonly rightAnnotations?: HorizontalAnnotation[];
/** Whether the graph should be shown as stacked lines */
readonly stacked?: boolean;
/** Properties of the left Y axis */
readonly leftYAxis?: YAxisProps;
/** Properties of the right Y axis */
readonly rightYAxis?: YAxisProps;
/** Position of the legend */
readonly legendPosition?: LegendPosition;
/** Whether to show live data */
readonly liveData?: boolean;
/** Type of widget view */
readonly view?: GraphWidgetView;
/** Whether to set period to time range */
readonly setPeriodToTimeRange?: boolean;
/** The default period for the widget */
readonly period?: Duration;
/** The default statistic for the widget */
readonly statistic?: string;
}
interface MetricWidgetProps {
/** Title for the widget */
readonly title?: string;
/** The region the metrics of this graph should be taken from */
readonly region?: string;
/** Width of the widget in grid units (1-24) */
readonly width?: number;
/** Height of the widget in grid units */
readonly height?: number;
}
interface YAxisProps {
/** The min value */
readonly min?: number;
/** The max value */
readonly max?: number;
/** The label */
readonly label?: string;
/** Whether to show units */
readonly showUnits?: boolean;
}
interface HorizontalAnnotation {
/** The value at which to draw the annotation */
readonly value: number;
/** Label for the annotation */
readonly label?: string;
/** Color of the annotation line */
readonly color?: string;
/** Shading to apply */
readonly fill?: Shading;
/** Whether the annotation is visible */
readonly visible?: boolean;
}
enum GraphWidgetView {
TIME_SERIES = 'timeSeries',
BAR = 'bar',
PIE = 'pie'
}
enum LegendPosition {
BOTTOM = 'bottom',
RIGHT = 'right',
HIDDEN = 'hidden'
}
enum Shading {
NONE = 'none',
ABOVE = 'above',
BELOW = 'below'
}Usage Examples:
// Basic graph widget
const basicGraph = new cloudwatch.GraphWidget({
title: 'CPU and Memory Usage',
left: [cpuMetric],
right: [memoryMetric],
width: 12,
height: 6,
legendPosition: cloudwatch.LegendPosition.BOTTOM
});
// Graph with annotations and custom Y axes
const annotatedGraph = new cloudwatch.GraphWidget({
title: 'Response Time with SLA',
left: [responseTimeMetric],
leftAnnotations: [{
value: 1000,
label: 'SLA Threshold',
color: '#FF0000',
fill: cloudwatch.Shading.ABOVE
}],
leftYAxis: {
min: 0,
max: 2000,
label: 'Milliseconds',
showUnits: true
},
view: cloudwatch.GraphWidgetView.TIME_SERIES,
stacked: false
});
// Stacked area chart
const stackedGraph = new cloudwatch.GraphWidget({
title: 'Request Types',
left: [getRequestsMetric, postRequestsMetric, putRequestsMetric],
stacked: true,
view: cloudwatch.GraphWidgetView.TIME_SERIES
});Display current metric values as single numbers with optional precision control.
/**
* A widget that displays a single value
*/
class SingleValueWidget extends ConcreteWidget {
/**
* Create a new single value widget
* @param props - Single value widget configuration properties
*/
constructor(props: SingleValueWidgetProps);
}
interface SingleValueWidgetProps extends MetricWidgetProps {
/** Metrics to display */
readonly metrics: IMetric[];
/** Whether to set period to time range */
readonly setPeriodToTimeRange?: boolean;
/** Whether to show full precision */
readonly fullPrecision?: boolean;
}Usage Examples:
// Basic single value widget
const singleValue = new cloudwatch.SingleValueWidget({
title: 'Current Active Users',
metrics: [activeUsersMetric],
width: 6,
height: 6,
fullPrecision: false
});
// Multiple metrics in single widget
const multiValue = new cloudwatch.SingleValueWidget({
title: 'Key Metrics',
metrics: [requestsMetric, errorsMetric, latencyMetric],
width: 8,
height: 4,
setPeriodToTimeRange: true
});Display alarm status and history in dashboard widgets.
/**
* A widget that displays alarms in a table
*/
class AlarmWidget extends ConcreteWidget {
/**
* Create a new alarm widget
* @param props - Alarm widget configuration properties
*/
constructor(props: AlarmWidgetProps);
}
interface AlarmWidgetProps extends MetricWidgetProps {
/** The alarm to show */
readonly alarm: IAlarm;
/** Properties of the left Y axis */
readonly leftYAxis?: YAxisProps;
}
/**
* A widget that displays alarm status
*/
class AlarmStatusWidget extends ConcreteWidget {
/**
* Create a new alarm status widget
* @param props - Alarm status widget configuration properties
*/
constructor(props: AlarmStatusWidgetProps);
}
interface AlarmStatusWidgetProps {
/** Alarms to display */
readonly alarms: IAlarm[];
/** Title for the widget */
readonly title?: string;
/** Width of the widget */
readonly width?: number;
/** Height of the widget */
readonly height?: number;
/** Sorting criteria for the alarm list */
readonly sortBy?: AlarmStatusWidgetSortBy;
/** States to display */
readonly states?: AlarmState[];
}
enum AlarmStatusWidgetSortBy {
/** Default sorting */
DEFAULT = 'default',
/** Sort by state updated timestamp */
STATE_UPDATED_TIMESTAMP = 'stateUpdatedTimestamp',
/** Sort by timestamp */
TIMESTAMP = 'timestamp'
}Add markdown-formatted text content to dashboards for documentation and context.
/**
* A widget that displays text
*/
class TextWidget extends ConcreteWidget {
/**
* Create a new text widget
* @param props - Text widget configuration properties
*/
constructor(props: TextWidgetProps);
}
interface TextWidgetProps {
/** The text to display (supports markdown) */
readonly markdown: string;
/** Width of the widget */
readonly width?: number;
/** Height of the widget */
readonly height?: number;
}Usage Examples:
// Documentation text widget
const docsWidget = new cloudwatch.TextWidget({
markdown: `
# System Overview
This dashboard shows key metrics for our production environment.
## Key Indicators
- **CPU Usage**: Should remain below 80%
- **Memory Usage**: Should remain below 85%
- **Response Time**: Should stay under 500ms
Contact: devops@company.com
`,
width: 12,
height: 8
});Display CloudWatch Logs Insights queries results in dashboard widgets.
/**
* A widget that displays log query results
*/
class LogQueryWidget extends ConcreteWidget {
/**
* Create a new log query widget
* @param props - Log query widget configuration properties
*/
constructor(props: LogQueryWidgetProps);
}
interface LogQueryWidgetProps {
/** Title for the widget */
readonly title?: string;
/** Names of log groups to query */
readonly logGroupNames: string[];
/** CloudWatch Logs Insights query string */
readonly queryString?: string;
/** Query string as an array of lines */
readonly queryLines?: string[];
/** The region for the query */
readonly region?: string;
/** Type of visualization */
readonly view?: LogQueryVisualizationType;
/** Width of the widget */
readonly width?: number;
/** Height of the widget */
readonly height?: number;
}
enum LogQueryVisualizationType {
TABLE = 'table',
LINE = 'line',
STACKEDAREA = 'stackedarea',
BAR = 'bar',
PIE = 'pie'
}Usage Examples:
// Log query widget for error analysis
const errorLogsWidget = new cloudwatch.LogQueryWidget({
title: 'Recent Errors',
logGroupNames: ['/aws/lambda/my-function'],
queryString: `
fields @timestamp, @message
| filter @message like /ERROR/
| sort @timestamp desc
| limit 20
`,
view: cloudwatch.LogQueryVisualizationType.TABLE,
width: 24,
height: 8
});
// Performance analysis query
const performanceWidget = new cloudwatch.LogQueryWidget({
title: 'Request Duration Trends',
logGroupNames: ['/aws/apigateway/my-api'],
queryLines: [
'fields @timestamp, responseTime',
'filter responseTime > 1000',
'stats avg(responseTime) by bin(5m)'
],
view: cloudwatch.LogQueryVisualizationType.LINE
});Create custom widgets using AWS Lambda functions for specialized visualizations.
/**
* A custom widget powered by a Lambda function
*/
class CustomWidget extends ConcreteWidget {
/**
* Create a new custom widget
* @param props - Custom widget configuration properties
*/
constructor(props: CustomWidgetProps);
}
interface CustomWidgetProps {
/** ARN of the Lambda function that implements the custom widget */
readonly functionArn: string;
/** Width of the widget */
readonly width?: number;
/** Height of the widget */
readonly height?: number;
/** Title for the widget */
readonly title: string;
/** Whether to update the widget on refresh */
readonly updateOnRefresh?: boolean;
/** Whether to update the widget on resize */
readonly updateOnResize?: boolean;
/** Whether to update the widget on time range change */
readonly updateOnTimeRangeChange?: boolean;
/** Parameters to pass to the Lambda function */
readonly params?: any;
}Core widget interfaces and base classes used throughout the dashboard system.
/**
* A widget for a dashboard
*/
interface IWidget {
/** Width of the widget in grid units */
readonly width: number;
/** Height of the widget in grid units */
readonly height: number;
/** Warnings attached to this widget */
readonly warnings?: string[];
/**
* Position the widget at the given coordinates
* @param x - X coordinate
* @param y - Y coordinate
*/
position(x: number, y: number): void;
/**
* Return the JSON structure that represents this widget
* @returns Widget JSON configuration
*/
toJson(): any[];
}
/**
* Abstract base class for widgets
*/
abstract class ConcreteWidget implements IWidget {
/** Width of the widget */
readonly width: number;
/** Height of the widget */
readonly height: number;
/** Warnings for this widget */
readonly warnings?: string[];
/**
* Position the widget at given coordinates
* @param x - X coordinate
* @param y - Y coordinate
*/
position(x: number, y: number): void;
/**
* Return the JSON representation of this widget
*/
abstract toJson(): any[];
/**
* Copy warnings from metrics to this widget
* @param ms - Metrics to copy warnings from
*/
protected copyMetricWarnings(...ms: IMetric[]): void;
}
/** Grid width for dashboard widgets */
const GRID_WIDTH = 24;Create custom widgets using AWS Lambda functions for specialized visualizations.
/**
* A custom widget powered by a Lambda function
*/
class CustomWidget extends ConcreteWidget {
/**
* Create a new custom widget
* @param props - Custom widget configuration properties
*/
constructor(props: CustomWidgetProps);
}
interface CustomWidgetProps {
/** ARN of the Lambda function that implements the custom widget */
readonly functionArn: string;
/** Width of the widget */
readonly width?: number;
/** Height of the widget */
readonly height?: number;
/** Title for the widget */
readonly title: string;
/** Whether to update the widget on refresh */
readonly updateOnRefresh?: boolean;
/** Whether to update the widget on resize */
readonly updateOnResize?: boolean;
/** Whether to update the widget on time range change */
readonly updateOnTimeRangeChange?: boolean;
/** Parameters to pass to the Lambda function */
readonly params?: any;
}Usage Examples:
// Basic custom widget
const customWidget = new cloudwatch.CustomWidget({
functionArn: 'arn:aws:lambda:us-east-1:123456789012:function:MyCustomWidget',
title: 'Custom Visualization',
width: 12,
height: 8,
updateOnRefresh: true,
updateOnResize: false,
params: {
customParam: 'value',
threshold: 100
}
});
// Custom widget with minimal updates
const staticCustomWidget = new cloudwatch.CustomWidget({
functionArn: myLambdaFunction.functionArn,
title: 'Static Report',
width: 24,
height: 12,
updateOnRefresh: false,
updateOnResize: false,
updateOnTimeRangeChange: false
});Predefined colors for consistent metric and widget styling.
/**
* Utility class with predefined colors
*/
class Color {
static readonly BLUE = '#1f77b4';
static readonly BROWN = '#8c564b';
static readonly GREEN = '#2ca02c';
static readonly GREY = '#7f7f7f';
static readonly ORANGE = '#ff7f0e';
static readonly PINK = '#e377c2';
static readonly PURPLE = '#9467bd';
static readonly RED = '#d62728';
}Complete Dashboard Example:
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
// Create comprehensive dashboard
const dashboard = new cloudwatch.Dashboard(this, 'ProductionDashboard', {
dashboardName: 'Production-System-Overview',
periodOverride: cloudwatch.PeriodOverride.AUTO
});
// Add multiple widgets
dashboard.addWidgets(
// First row: Key metrics
new cloudwatch.SingleValueWidget({
title: 'Active Users',
metrics: [activeUsersMetric],
width: 6
}),
new cloudwatch.SingleValueWidget({
title: 'Error Rate',
metrics: [errorRateMetric],
width: 6
}),
new cloudwatch.AlarmStatusWidget({
title: 'System Alarms',
alarms: [cpuAlarm, memoryAlarm, diskAlarm],
width: 12
}),
// Second row: Graphs
new cloudwatch.GraphWidget({
title: 'System Performance',
left: [cpuMetric, memoryMetric],
right: [responseTimeMetric],
width: 12,
leftYAxis: { label: 'Percentage', max: 100 },
rightYAxis: { label: 'Milliseconds' }
}),
new cloudwatch.LogQueryWidget({
title: 'Recent Errors',
logGroupNames: ['/aws/lambda/api'],
queryString: 'fields @message | filter @message like /ERROR/',
width: 12
})
);