Skip to content
Learni
View all tutorials
DevOps

How to Set Up CloudWatch for Monitoring in 2026

Lire en français

Introduction

In a cloud world where apps run 24/7, monitoring is essential to detect anomalies before they impact users. AWS CloudWatch, Amazon's native service, collects metrics, logs, and events for full visibility. This intermediate tutorial guides you through implementing complete monitoring: custom metrics, automated alarms, and interactive dashboards.

Why is it crucial in 2026? With the rise of AI and microservices, outages are expensive—up to €10,000 per minute according to Gartner. We use AWS CDK (Infrastructure as Code in TypeScript) for quick deployment and the AWS SDK to send metrics from your Node.js apps. The result: a scalable, observable, and actionable system. Follow these steps for a production-ready setup in under an hour.

Prerequisites

  • Active AWS account with IAM permissions (CloudWatchFullAccess, CDKDeploy).
  • Node.js 20+ installed.
  • AWS CLI v2 configured (aws --version).
  • Basic knowledge of TypeScript and AWS CDK.
  • Default AWS region (e.g., eu-west-1).

Initialize the CDK Project

terminal
mkdir cloud-monitoring-cdk
cd cloud-monitoring-cdk
npm init -y
npm install aws-cdk-lib constructs @aws-sdk/client-cloudwatch
npm install -D typescript ts-node @types/node cdk
cdk init app --language typescript
npm run build

These commands create a standard TypeScript CDK project, install essential dependencies (CDK v2, CloudWatch SDK), and set up the structure. cdk init generates customizable boilerplate. Avoid outdated CDK v1 for 2026 compatibility.

Configure AWS Credentials

Run aws configure to set your Access Key, Secret Key, region (e.g., eu-west-1), and output (json). Verify with aws sts get-caller-identity. This enables CDK and SDK without hardcoding secrets—a secure best practice.

Define the Main CDK Stack

lib/cloud-monitoring-stack.ts
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as cloudwatch from 'aws-cdk-lib/aws-cloudwatch';

export class CloudMonitoringStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // Métrique custom exemple (simule CPU app)
    const cpuMetric = new cloudwatch.Metric({
      namespace: 'MyApp',
      metricName: 'CPUUtilization',
      statistic: 'Average',
      period: cdk.Duration.minutes(1),
    });

    // Alarme si CPU > 80%
    new cloudwatch.Alarm(this, 'HighCPUAlarm', {
      metric: cpuMetric,
      threshold: 80,
      evaluationPeriods: 2,
      alarmDescription: 'Alarme CPU élevée pour MyApp',
    });

    // Dashboard avec widget
    const dashboard = new cloudwatch.Dashboard(this, 'MyAppDashboard', {
      dashboardName: 'MyApp-Monitoring',
    });

    dashboard.addWidgets(
      new cloudwatch.GraphWidget({
        title: 'CPU Utilization',
        left: [cpuMetric],
      }),
    );
  }
}

This stack creates a custom 'CPUUtilization' metric in the 'MyApp' namespace, an alarm that triggers above 80% over 2 periods, and a dashboard with a graph. CDK synthesizes to CloudFormation. Pitfall: Don't forget to import modules to avoid resolution errors.

Configure the CDK App

bin/cloud-monitoring.ts
#!/usr/bin/env node
import * as cdk from 'aws-cdk-lib';
import { CloudMonitoringStack } from '../lib/cloud-monitoring-stack';

const app = new cdk.App();
new CloudMonitoringStack(app, 'CloudMonitoringStack', {
  env: {
    account: process.env.CDK_DEFAULT_ACCOUNT,
    region: process.env.CDK_DEFAULT_REGION,
  },
});

Standard CDK entry file that instantiates the stack with auto-detected env. Add env to target specific region/account. Run cdk synth to validate before deploy—avoids prod surprises.

Deploy the Infrastructure

Run cdk bootstrap (once per account/region), then cdk deploy. This creates the CloudWatch resources. Check in the AWS console > CloudWatch > Dashboards and Alarms. The dashboard is live!

Send Custom Metrics

metric-sender.ts
import { CloudWatchClient, PutMetricDataCommand } from '@aws-sdk/client-cloudwatch';

const client = new CloudWatchClient({ region: 'eu-west-1' });

const params = {
  Namespace: 'MyApp',
  MetricData: [
    {
      MetricName: 'CPUUtilization',
      Value: 85.5,
      Unit: 'Percent',
      Timestamp: new Date(),
    },
  ],
};

const command = new PutMetricDataCommand(params);
client.send(command).then(() => console.log('Métrique envoyée !')).catch(console.error);

This script uses SDK v3 to push a CPU metric at 85.5% to the 'MyApp' namespace, triggering the alarm. Integrate it into your Node.js app (e.g., cron or middleware). Pitfall: Without credentials, it fails—use IAM roles in prod.

Complete Package.json for the Sender App

package.json
{
  "name": "metric-sender",
  "version": "1.0.0",
  "main": "metric-sender.js",
  "scripts": {
    "start": "ts-node metric-sender.ts",
    "build": "tsc"
  },
  "dependencies": {
    "@aws-sdk/client-cloudwatch": "^3.600.0",
    "typescript": "^5.5.3",
    "ts-node": "^10.9.2",
    "@types/node": "^20.14.10"
  }
}

Dedicated package.json for the sender: npm install then npm start to test. Separate sender from CDK for modularity. Version deps for CI/CD reproducibility.

Deploy and Test

terminal
cd cloud-monitoring-cdk
cdk deploy
cd ..
npm install
npm start  # Envoie métrique et trigger alarme

Deploys CDK then tests sender. Alarm triggers in ~2min. Monitor SNS/CloudWatch Events for notifications. Clean up with cdk destroy.

Best Practices

  • Use unique namespaces per app to isolate metrics.
  • Add dimensions (e.g., {InstanceId}) for granularity.
  • Integrate logs and traces with X-Ray for full-stack observability.
  • Automate with Lambda: Trigger alarms via SNS/EventBridge.
  • Tag CDK resources for cost tracking.

Common Errors to Avoid

  • No CDK bootstrap: "no bootstrap stack" error. Run cdk bootstrap.
  • Metrics without data: Alarms stay OK—send data first.
  • Region mismatch: SDK/CDK must match aws configure.
  • Missing IAM permissions: Add cloudwatch:PutMetricData to the role.

Next Steps

Dive deeper with CloudWatch Logs Insights or integrate Prometheus via ADOT. Check out our DevOps training at Learni to master Kubernetes monitoring and Grafana.