0Pricing
NestJS Enterprise Backend APIs · درس

المراقبة باستخدام Prometheus

ادمجوا Prometheus لجمع المقاييس وأنشئوا لوحات معلومات لمراقبة أداء تطبيق NestJS وحالته.

المراقبة باستخدام Prometheus درس مجاني في NestJS Enterprise Backend APIs على CoddyKit. هذا هو الدرس 3 من أصل 3. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في 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-client

Then, 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-prometheus to 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» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة NestJS Enterprise Backend APIs، انتقل إلى CoddyKit PRO. تتضمن دورة NestJS Enterprise Backend APIs 3 دروس في المجموع.

ماذا ستتعلم في «المراقبة باستخدام Prometheus»؟

ادمجوا Prometheus لجمع المقاييس وأنشئوا لوحات معلومات لمراقبة أداء تطبيق NestJS وحالته. تتمرن على NestJS Enterprise Backend APIs مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ NestJS Enterprise Backend APIs؟

لا تُشترط خبرة سابقة. NestJS Enterprise Backend APIs على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 3.

كم من الوقت يستغرق درس «المراقبة باستخدام Prometheus»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس NestJS Enterprise Backend APIs هذا؟

نعم. كل درس في NestJS Enterprise Backend APIs يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تحديد معدل الطلبات وخنقها
  2. تسجيل الأحداث باستخدام Winston/Pino
  3. المراقبة باستخدام Prometheus
← العودة إلى NestJS Enterprise Backend APIs