使用 Prometheus 进行监控
集成 Prometheus 进行指标收集并构建仪表板,以监控您的 NestJS 应用性能和运行状况。
使用 Prometheus 进行监控 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 NestJS Enterprise Backend APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Monitor Your App?
Monitoring is crucial for understanding your application's health and performance. It helps you catch issues early, debug problems, and ensure a smooth user experience.
- Performance: Is your API fast enough?
- Availability: Is your service online and responding?
- Errors: Are there unexpected failures?
- Resource Usage: How much CPU, memory, or disk space is being used?
Without monitoring, you're flying blind!
Meet Prometheus
Prometheus is an open-source monitoring system designed for reliability and scalability. It collects metrics from your applications and infrastructure, storing them as time-series data.
Think of it as a vigilant observer, constantly gathering data points about your system's behavior over time.
Prometheus Architecture
Prometheus works by scraping (pulling) metrics from configured targets. Key components:
- Prometheus Server: The core component that scrapes, stores, and queries metrics.
- Exporters: Specialized agents that expose existing metrics from third-party systems (like databases, OS) in a Prometheus-compatible format.
- Client Libraries: Integrate directly into application code to expose custom metrics (what we'll use in NestJS).
- Grafana: A popular dashboard tool for visualizing Prometheus data.
NestJS & `nestjs-prometheus`
To integrate Prometheus with a NestJS application, we use the nestjs-prometheus library. It simplifies exposing metrics and creating custom ones.
This library acts as a bridge, allowing your NestJS app to generate and expose metrics that the Prometheus server can then scrape.
Setting Up `nestjs-prometheus`
First, install the package:
npm install --save @willsoto/nestjs-prometheus prom-clientThen, import PrometheusModule into your root module (e.g., AppModule) and configure it:
import { Module } from '@nestjs/common';
import { PrometheusModule } from '@willsoto/nestjs-prometheus';
import { AppController } from './app.controller';
@Module({
imports: [
PrometheusModule.register({
path: '/metrics',
collectDefaultMetrics: true
})
],
controllers: [AppController],
providers: [],
})
export class AppModule {}
Exposing Default HTTP Metrics
With collectDefaultMetrics: true, nestjs-prometheus automatically exposes basic Node.js process metrics. To also expose HTTP request metrics, you need to add an interceptor.
Update your main.ts to enable this:
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { PrometheusInterceptor } from '@willsoto/nestjs-prometheus';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalInterceptors(new PrometheusInterceptor());
await app.listen(3000);
console.log('App is running on port 3000');
// Access metrics at http://localhost:3000/metrics
}
bootstrap();
Custom Metrics: Counter
A Counter is a cumulative metric that represents a single monotonically increasing value. It can only go up or be reset to zero on restart. Use it for things like the total number of requests served, errors encountered, or items processed.
Here's how to inject and use a custom counter in a service:
import { Injectable } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Counter } from 'prom-client';
@Injectable()
export class UserService {
constructor(
@InjectMetric('users_created_total') public usersCreatedCounter: Counter,
) {}
createUser(name: string): string {
// Logic to create a user...
this.usersCreatedCounter.inc(); // Increment the counter
return `User ${name} created`;
}
}
Custom Metrics: Gauge
A Gauge is a metric that represents a single numerical value that can arbitrarily go up and down. Use it for things like current memory usage, number of concurrent requests, or the current queue size.
Let's track active connections with a Gauge:
import { Injectable } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import { Gauge } from 'prom-client';
@Injectable()
export class ConnectionService {
constructor(
@InjectMetric('active_connections_count') public activeConnectionsGauge: Gauge,
) {}
connectUser(): void {
// User connects logic...
this.activeConnectionsGauge.inc(); // Increment active connections
}
disconnectUser(): void {
// User disconnects logic...
this.activeConnectionsGauge.dec(); // Decrement active connections
}
}
Other Metric Types
Prometheus also offers other metric types for more specific use cases:
- Histogram: Samples observations (e.g., request durations) and counts them in configurable buckets. Useful for understanding distributions and percentiles.
- Summary: Similar to Histogram but calculates configurable quantiles over a sliding time window. Good for latency.
For most common scenarios, Counters and Gauges are often sufficient.
Visualizing with Grafana
While Prometheus collects metrics, Grafana is typically used to visualize them. Grafana connects to Prometheus as a data source and allows you to build powerful, customizable dashboards.
You can create graphs, charts, and alerts based on the metrics exposed by your NestJS application, giving you real-time insights into its performance and health.
Quick Check
You've learned about setting up Prometheus monitoring in NestJS.
Recap: Monitoring with Prometheus
In this lesson, you learned the importance of monitoring and how Prometheus helps collect time-series metrics from your NestJS application.
- We explored the Prometheus architecture and its components.
- You saw how to integrate
nestjs-prometheusto expose default and custom metrics. - We distinguished between Counter and Gauge metric types.
- Finally, we touched on how Grafana is used for powerful visualization.
Monitoring is a vital practice for maintaining robust and performant applications!
常见问题解答
「使用 Prometheus 进行监控」课时是免费的吗?
是的 — 「使用 Prometheus 进行监控」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
「使用 Prometheus 进行监控」这节课中我会学到什么?
集成 Prometheus 进行指标收集并构建仪表板,以监控您的 NestJS 应用性能和运行状况。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NestJS Enterprise Backend APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「使用 Prometheus 进行监控」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?
能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 速率限制与节流
- 使用 Winston/Pino 进行日志记录
- 使用 Prometheus 进行监控