You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在LoopBack 4应用中使用prometheus-api-metrics中间件

LoopBack 4 集成 prometheus-api-metrics 中间件教程

1. 安装依赖

执行如下命令安装中间件包:
npm install prometheus-api-metrics

2. 调整 application.ts 配置

2.1 导入依赖

在 application.ts 文件头部添加导入语句:

import * as prometheusMetrics from 'prometheus-api-metrics';

2.2 注册中间件

在类的 constructor 方法中,super(options) 执行之后添加中间件注册逻辑,修改后的代码示例如下:

export class BackendV4Application extends BootMixin(ServiceMixin(RepositoryMixin(RestApplication))) {
  constructor(options?: ApplicationConfig) {
    options = { ...options, rest: { requestBodyParser: { json: { limit: '6mb' } } } };

    super(options);

    // Set up dotenv
    dotenv.config();

    // 注册prometheus监控中间件
    this.mountExpressMiddleware(prometheusMetrics({
      // 可按需调整配置项
      metricsPath: '/metrics',
      extractQueryParams: false,
      metricsPrefix: 'lb4_api_'
    }));

    // Set up the base path
    this.basePath('/api');

    this.api({
      openapi: '3.0.0',
      info: { title: pkg.name, version: pkg.version },
      paths: {},
      components: { securitySchemes: SECURITY_SCHEME_SPEC },
      servers: [{ url: '/api' }]
    });

    this.setUpBindings();
  }
}

3. 验证配置

启动应用后访问服务地址的/metrics路径,即可看到服务暴露的各项API监控指标,Prometheus服务可直接通过该路径拉取监控数据。

你可以根据业务需求调整中间件的传入配置,比如添加自定义标签、过滤不需要采集的路径、调整指标统计粒度等,所有可用配置可直接参考包的TS类型定义调整。


内容的提问来源于stack exchange,提问作者Ami Ine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 02:18:04