nestjs-cloudwatch-metrics
v0.0.1
Published
NestJS CloudWatch Metrics
Readme
NestJS CloudWatch Metrics
A NestJS module for easy integration with AWS CloudWatch Metrics. This module provides a simple way to create, publish, and manage custom metrics for your application.
Installation
To install the module, you can use pnpm (or your preferred package manager):
pnpm add nestjs-cloudwatch-metricsUsage
1. Import and Configure the Module
Import CloudwatchMetricsModule into your application module (e.g., app.module.ts) and configure it using the .forRoot() or .forRootAsync() static methods. You'll need to provide your AWS region and, optionally, your AWS credentials and default metric options.
// app.module.ts
import { Module } from "@nestjs/common";
import { CloudwatchMetricsModule } from "nestjs-cloudwatch-metrics";
@Module({
imports: [
CloudwatchMetricsModule.forRoot({
region: "your-aws-region", // e.g., "us-east-1"
// Optional: AWS credentials (if not configured elsewhere, e.g., via IAM roles)
// accessKeyId: "YOUR_AWS_ACCESS_KEY_ID",
// secretAccessKey: "YOUR_AWS_SECRET_ACCESS_KEY",
// Optional: Default options for all metrics created by the service
defaultMetricOptions: {
sendInterval: 10000, // Send metrics every 10 seconds
maxCapacity: 20, // Max metrics to store before sending
// ... other MetricOptions
},
}),
// ... other modules
],
})
export class AppModule {}2. Inject the Service and Use Metrics
Inject CloudwatchMetricsService into your services or controllers where you want to publish metrics.
// my-service.service.ts
import { Injectable } from "@nestjs/common";
import {
CloudwatchMetricsService,
Metric,
StandardUnit,
} from "nestjs-cloudwatch-metrics";
// Adjust path if using locally
@Injectable()
export class MyService {
private readonly requestCounterMetric: Metric;
constructor(private readonly cloudwatchService: CloudwatchMetricsService) {
// Create a metric instance
this.requestCounterMetric = this.cloudwatchService.createMetric(
"MyApplicationNamespace", // Your CloudWatch Namespace
StandardUnit.Count, // The unit for this metric
[
{ Name: "Environment", Value: "Production" }, // Default dimensions for this metric
],
{
// Metric-specific options (overrides defaultMetricOptions)
sendInterval: 5000, // Send this specific metric every 5 seconds
},
);
}
handleRequest() {
// ... your request handling logic ...
// Publish a metric datapoint
this.requestCounterMetric.put(
1, // The value of the metric
"IncomingRequests", // The name of the metric
[{ Name: "Route", Value: "/api/data" }], // Additional dimensions for this specific datapoint
);
}
async processBatchJob(items: any[]) {
// ... your batch job logic ...
const batchSize = items.length;
// Example of summarizing metric data over time
// This is useful for things like processing time, where you want min/max/avg/sum/count
this.requestCounterMetric.summaryPut(batchSize, "ProcessedBatchSize", [
{ Name: "JobType", Value: "NightlySync" },
]);
// Example of sampling metric data (e.g., only send 10% of datapoints)
this.requestCounterMetric.sample(
batchSize,
"SampledProcessedBatchSize",
[{ Name: "JobType", Value: "NightlySync" }],
0.1, // Sample rate: 10%
);
}
}Metric Options
The following options can be provided when creating a metric or as default options for the module:
enabled:boolean(default:true) - Whether the metric is enabled and should send data.sendInterval:number(default:5000ms) - Interval in milliseconds to send batched metrics.summaryInterval:number(default:10000ms) - Interval in milliseconds to send summarized metrics.sendCallback:(err?: Error) => void(default:() => {}) - Callback function executed after metrics are sent.maxCapacity:number(default:20) - Maximum number of metric data points to store before sending immediately.withTimestamp:boolean(default:false) - Whether to include aTimestampwith each metric data point.storageResolution:number(default:undefined) - The resolution, in seconds, for the metric. Valid values are 1 and 60.
Available Methods on Metric instances
put(value: number, metricName: string, additionalDimensions?: Dimension[]): void- Publishes a single metric data point.
summaryPut(value: number, metricName: string, additionalDimensions?: Dimension[]): void- Adds a data point to a summary set (sends min, max, sum, count, avg at
summaryInterval).
- Adds a data point to a summary set (sends min, max, sum, count, avg at
sample(value: number, metricName: string, additionalDimensions?: Dimension[], sampleRate: number): void- Publishes a metric data point based on a sample rate (0.0 to 1.0).
shutdown(): void- Clears intervals and sends any pending metrics. Called automatically
OnModuleDestroyfor metrics created via the service.
- Clears intervals and sends any pending metrics. Called automatically
hasMetrics(): boolean- Returns
trueif there are metrics pending to be sent.
- Returns
