Nodejs Nestjs性能监控插件@nestjs/metrics的使用

Nodejs Nestjs性能监控插件@nestjs/metrics的使用
[@nestjs](/user/nestjs)/metrics 是一个用于 NestJS 应用程序的性能监控插件,它可以帮助你收集和监控各种指标(如请求延迟、错误率等)。以下是如何在 NestJS 项目中使用 [@nestjs](/user/nestjs)/metrics 的步骤:

安装依赖

首先,你需要安装 [@nestjs](/user/nestjs)/metrics 和相应的适配器(例如 Prometheus):

npm install [@nestjs](/user/nestjs)/metrics prom-client

配置 Metrics

在你的 NestJS 应用程序中配置 Metrics。你可以在模块级别或全局级别进行配置。

创建 Metrics 模块

创建一个新的模块来配置 Metrics:

import { Module } from '[@nestjs](/user/nestjs)/common';
import { MetricsModule } from '[@nestjs](/user/nestjs)/metrics';

@Module({
  imports: [
    MetricsModule.register({
      defaultLabels: {
        app: 'your-app-name',
      },
      metricsMethodInterceptor: true,
    }),
  ],
})
export class AppModule {}

配置 Prometheus

如果你打算使用 Prometheus 作为指标导出器,可以添加 Prometheus 模块:

import { Module } from '[@nestjs](/user/nestjs)/common';
import { MetricsModule, PrometheusExporter } from '[@nestjs](/user/nestjs)/metrics';

@Module({
  imports: [
    MetricsModule.register({
      defaultLabels: {
        app: 'your-app-name',
      },
      metricsMethodInterceptor: true,
      exporter: new PrometheusExporter(),
    }),
  ],
})
export class AppModule {}

使用 Metrics

现在你可以在控制器或服务中使用 Metrics。你可以使用装饰器或直接通过注入 MetricsService 来访问 Metrics。

使用装饰器

在控制器方法上使用 @Metric 装饰器来跟踪请求延迟:

import { Controller, Get, Metric } from '[@nestjs](/user/nestjs)/common';
import { MetricsService } from '[@nestjs](/user/nestjs)/metrics';

@Controller('metrics')
export class MetricsController {
  constructor(private readonly metricsService: MetricsService) {}

  @Get()
  @Metric({ name: 'api_requests_total', type: 'counter' })
  getHello(): string {
    this.metricsService.labels({ status: 'success' }).inc();
    return 'Hello World!';
  }
}

直接使用 MetricsService

你也可以直接在服务中使用 MetricsService

import { Injectable } from '[@nestjs](/user/nestjs)/common';
import { MetricsService } from '[@nestjs](/user/nestjs)/metrics';

@Injectable()
export class AppService {
  constructor(private readonly metricsService: MetricsService) {}

  getHello() {
    this.metricsService.labels({ status: 'success' }).inc();
    return 'Hello World!';
  }
}

导出 Metrics

为了将 Metrics 导出到 Prometheus,你需要启动一个 HTTP 服务器来暴露这些指标。这通常在你的主应用文件中完成:

import { NestFactory } from '[@nestjs](/user/nestjs)/core';
import { AppModule } from './app.module';
import { MetricsService } from '[@nestjs](/user/nestjs)/metrics';
import * as http from 'http';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  const server = http.createServer(app.getHttpServer());
  server.listen(3000);

  // Export metrics to Prometheus
  app.get(MetricsService).exportToPrometheus(server);
}

bootstrap();

这样,你就可以通过访问 http://localhost:3000/metrics 来查看 Prometheus 格式的 Metrics。

总结

以上步骤展示了如何在 NestJS 应用程序中使用 [@nestjs](/user/nestjs)/metrics 插件来监控性能。你可以根据需要调整配置,并选择不同的导出器(如 Prometheus)来收集和展示这些指标。


3 回复

当然,@nestjs/metrics插件可以帮助你在NestJS应用中轻松添加性能监控。首先,你需要安装它:

npm install [@nestjs](/user/nestjs)/metrics

然后,在你的模块中导入MetricsModule

import { Module } from '[@nestjs](/user/nestjs)/common';
import { MetricsModule } from '[@nestjs](/user/nestjs)/metrics';

@Module({
  imports: [MetricsModule.register()],
})
export class AppModule {}

接着,你可以在控制器或服务中注入MetricsService来记录和查询指标:

import { Controller, Get } from '[@nestjs](/user/nestjs)/common';
import { MetricsService } from '[@nestjs](/user/nestjs)/metrics';

@Controller('metrics')
export class MetricsController {
  constructor(private readonly metricsService: MetricsService) {}

  @Get()
  async getMetrics() {
    this.metricsService.gauge('requests', 1);
    return this.metricsService.getMetrics();
  }
}

这样,你就有了一个基本的性能监控系统!别忘了根据需要调整配置,让它更符合你的需求。祝你编程愉快!


[@nestjs](/user/nestjs)/metrics 是一个用于 NestJS 应用程序的性能监控库,它允许你跟踪和度量应用中的关键指标。以下是如何使用 [@nestjs](/user/nestjs)/metrics 的基本步骤:

  1. 安装依赖:首先,你需要安装 [@nestjs](/user/nestjs)/metrics 和相关的客户端库(如 Prometheus 客户端)。

    npm install [@nestjs](/user/nestjs)/metrics [@prometheus-client-js](/user/prometheus-client-js)/prom-client
    
  2. 配置模块:在你的 NestJS 应用中,导入并配置 MetricsModule

  3. 创建控制器和服务:创建一个服务来处理具体的指标收集,并在控制器中暴露这些指标。

  4. 暴露指标端点:通常,你需要暴露一个端点来获取这些指标,这可以通过 Express 路由来完成。

以下是一个简单的示例:

步骤 1: 安装依赖

确保你已经安装了 Node.js 和 npm,然后运行上述命令安装所需的包。

步骤 2: 配置模块

在你的 app.module.ts 文件中导入并配置 MetricsModule

import { Module } from '[@nestjs](/user/nestjs)/common';
import { MetricsModule } from '[@nestjs](/user/nestjs)/metrics';

@Module({
  imports: [
    MetricsModule.register({
      registry: new PrometheusClient.Registry(), // 创建一个新的 Prometheus 客户端注册表
    }),
  ],
})
export class AppModule {}

步骤 3: 创建服务

创建一个服务来定义和收集指标。

import { Injectable } from '[@nestjs](/user/nestjs)/common';
import { Registry, Counter } from '[@prometheus-client-js](/user/prometheus-client-js)/prom-client';

@Injectable()
export class MetricsService {
  private readonly counter: Counter;

  constructor(private readonly registry: Registry) {
    this.counter = new Counter({
      name: 'http_requests_total',
      help: 'Total number of HTTP requests',
      labelNames: ['method', 'code'],
      registers: [registry],
    });
  }

  incrementCounter(method: string, code: number) {
    this.counter.inc({ method, code });
  }
}

步骤 4: 创建控制器

在控制器中暴露一个端点来获取指标。

import { Controller, Get, Req } from '[@nestjs](/user/nestjs)/common';
import { Registry } from '[@prometheus-client-js](/user/prometheus-client-js)/prom-client';
import { MetricsService } from './metrics.service';

@Controller('metrics')
export class MetricsController {
  constructor(
    private readonly metricsService: MetricsService,
    private readonly registry: Registry,
  ) {}

  @Get()
  async getMetrics(@Req() request) {
    const handler = await this.registry.metricsHandler();
    return handler(request);
  }
}

步骤 5: 使用服务

在适当的地方调用 MetricsService 中的方法来增加计数器值。

import { Injectable, OnModuleInit } from '[@nestjs](/user/nestjs)/common';
import { HttpService } from '[@nestjs](/user/nestjs)/axios';
import { firstValueFrom } from 'rxjs';
import { MetricsService } from './metrics.service';

@Injectable()
export class AppService implements OnModuleInit {
  constructor(
    private readonly httpService: HttpService,
    private readonly metricsService: MetricsService,
  ) {}

  async onModuleInit() {
    const response = await firstValueFrom(this.httpService.get('https://example.com'));
    this.metricsService.incrementCounter('GET', response.status);
  }
}

以上就是一个基本的使用 [@nestjs](/user/nestjs)/metrics 来进行性能监控的例子。你可以根据需要调整和扩展这个示例。

@nestjs/metrics 是一个用于 NestJS 应用程序的性能监控插件,支持 Prometheus 等监控系统。首先,你需要安装它:

npm install @nestjs/metrics

然后,在你的模块中导入 MetricsModule 并配置它:

import { Module } from '@nestjs/common';
import { MetricsModule } from '@nestjs/metrics';

@Module({
  imports: [
    MetricsModule.register({
      enabled: true,
      defaultLabels: {
        application: 'your-application-name',
      },
    }),
  ],
})
export class ApplicationModule {}

你可以通过注入 MetricsService 来创建指标:

import { Injectable, Inject } from '@nestjs/common';
import { MetricsService } from '@nestjs/metrics';

@Injectable()
export class AppService {
  constructor(@Inject(MetricsService) private readonly metrics: MetricsService) {}

  createGauge() {
    this.metrics.gauge('example_gauge', 'An example gauge metric.');
  }
}

这样,你就有了一个基本的 NestJS 性能监控设置。

回到顶部