File

tbl/src/common/metrics.service.ts

Index

Properties
Methods

Constructor

constructor(gamesTotalCounter: Counter, gamesActiveGauge: Gauge, liveGamesCreatedCounter: Counter, liveGamesStartedCounter: Counter, liveGamesFinishedCounter: Counter)
Parameters :
Name Type Optional
gamesTotalCounter Counter<string> No
gamesActiveGauge Gauge<string> No
liveGamesCreatedCounter Counter<string> No
liveGamesStartedCounter Counter<string> No
liveGamesFinishedCounter Counter<string> No

Methods

incrementGamesTotal
incrementGamesTotal()
Returns : void
incrementLiveGamesCreated
incrementLiveGamesCreated()
Returns : void
incrementLiveGamesFinished
incrementLiveGamesFinished()
Returns : void
incrementLiveGamesStarted
incrementLiveGamesStarted()
Returns : void
Async pushMetrics
pushMetrics()
Returns : any
Async scheduledMetricsPush
scheduledMetricsPush()
Decorators :
@Cron('*/10 * * * *')
Returns : any
setGamesActive
setGamesActive(value: number)
Parameters :
Name Type Optional
value number No
Returns : void

Properties

Private Readonly instanceLabel
Type : string
Private Readonly logger
Default value : new Logger(MetricsService.name)
Private Readonly pushgateway
Type : Pushgateway<RegistryContentType>
import { Injectable, Logger } from '@nestjs/common';
import { InjectMetric } from '@willsoto/nestjs-prometheus';
import {
  Counter,
  Gauge,
  Pushgateway,
  RegistryContentType,
  register,
} from 'prom-client';
import { Cron } from '@nestjs/schedule';

@Injectable()
export class MetricsService {
  private readonly pushgateway: Pushgateway<RegistryContentType>;
  private readonly logger = new Logger(MetricsService.name);
  private readonly instanceLabel: string;

  constructor(
    @InjectMetric('tbl_games_total')
    private readonly gamesTotalCounter: Counter<string>,
    @InjectMetric('tbl_games_active')
    private readonly gamesActiveGauge: Gauge<string>,
    @InjectMetric('live_games_created_total')
    private readonly liveGamesCreatedCounter: Counter<string>,
    @InjectMetric('live_games_started_total')
    private readonly liveGamesStartedCounter: Counter<string>,
    @InjectMetric('live_games_finished_total')
    private readonly liveGamesFinishedCounter: Counter<string>,
  ) {
    const pushgatewayUrl =
      process.env.PROMETHEUS_PUSHGATEWAY_URL ||
      'http://prometheus-pushgateway.monitoring:9091';
    this.logger.log(`Initializing Pushgateway with URL: ${pushgatewayUrl}`);

    this.instanceLabel = process.env.HOSTNAME || 'unknown';
    this.logger.log(`Using instance label: ${this.instanceLabel}`);

    // Use the default registry that @willsoto/nestjs-prometheus uses
    this.pushgateway = new Pushgateway<RegistryContentType>(
      pushgatewayUrl,
      {},
      register,
    );

    // Log initial metric values
    this.logger.log('Initial metric values:', {
      gamesTotal: this.gamesTotalCounter.get(),
      gamesActive: this.gamesActiveGauge.get(),
      liveGamesCreated: this.liveGamesCreatedCounter.get(),
      liveGamesStarted: this.liveGamesStartedCounter.get(),
      liveGamesFinished: this.liveGamesFinishedCounter.get(),
    });
  }

  incrementGamesTotal() {
    this.gamesTotalCounter.inc({ instance: this.instanceLabel });
  }

  setGamesActive(value: number) {
    this.gamesActiveGauge.set({ instance: this.instanceLabel }, value);
  }

  incrementLiveGamesCreated() {
    this.liveGamesCreatedCounter.inc({ instance: this.instanceLabel });
  }

  incrementLiveGamesStarted() {
    this.liveGamesStartedCounter.inc({ instance: this.instanceLabel });
  }

  incrementLiveGamesFinished() {
    this.liveGamesFinishedCounter.inc({ instance: this.instanceLabel });
  }

  @Cron('*/10 * * * *') // Run every 10 minutes
  async scheduledMetricsPush() {
    try {
      await this.pushMetrics();
      this.logger.log('Successfully pushed metrics to Pushgateway');
    } catch (error) {
      this.logger.error('Failed to push metrics:', error);
    }
  }

  // Push metrics to Pushgateway
  async pushMetrics() {
    try {
      const result = await this.pushgateway.push({
        jobName: 'tbl-metrics-service',
        groupings: {
          instance: this.instanceLabel,
        },
      });
      this.logger.log('Pushgateway response:', result);
    } catch (error) {
      this.logger.error('Failed to push metrics to Pushgateway:', error);
    }
  }
}

results matching ""

    No results matching ""