digikare / nestjs-prom

A prometheus module for nestjs
160 stars 54 forks source link

how to use custom controller when withDefaultController: false #49

Open darrenjennings opened 3 years ago

darrenjennings commented 3 years ago

@digikare/nestjs-prom version: 0.2.5

I am trying to remove the /api/metrics from the autogenerated swagger spec.

const MyPromModule = PromModule.forRoot({
  defaultLabels: {
    app: 'my-api'
  },
  withDefaultsMetrics: true,
  withDefaultController: false, // set to false so custom controller is used
  useHttpCounterMiddleware: true
})
MyPromModule.controllers = [PromController.forRoot('api/metrics')]

and then PromController is a copy paste from source(but with @ApiExcludeEndpoint)

import { Controller, Get, Header } from "@nestjs/common";
import * as client from 'prom-client';
import { PATH_METADATA } from '@nestjs/common/constants';
import { ApiExcludeEndpoint } from "@nestjs/swagger";

@Controller()
export class PromController {
  @Get()
  @ApiExcludeEndpoint()
  @Header('Content-Type', client.register.contentType)
  index() {
    console.log('test')

    return client.register.metrics();
  }

  public static forRoot(path = 'metrics') {
    Reflect.defineMetadata(PATH_METADATA, path, PromController);

    return PromController;
  }
}

When I hit /api/metrics, client.register.metrics(); always returns empty string.

arinaspektor commented 3 years ago

I did it this way:

import { Registry } from '@digikare/nestjs-prom';
import { Header } from '@nestjs/common';
import { Controller, Get } from '@nestjs/common/';
import * as client from 'prom-client';

 @Controller('metrics')
export class PromController {
  private readonly _registry: Registry;

  constructor(
    private readonly promService: PromService,
  ) {
    this._registry = this.promService.getDefaultRegistry();
  }

  @Get()
  @Header('Content-Type', client.register.contentType)
  public async index() {
    return this._registry.metrics();
  }
}
timakhalaya commented 6 months ago
import {ApiTags} from "@nestjs/swagger";
import {PromController, PromModule} from "@digikare/nestjs-prom";

ApiTags('example')(PromController);
...