All files / src/common/services tracer.service.ts

34.48% Statements 10/29
23.07% Branches 3/13
0% Functions 0/3
29.62% Lines 8/27

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 6312x 12x 12x 12x 12x 12x 12x     12x                                                                                                          
import { Injectable, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NodeSDK } from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto';
import { resourceFromAttributes } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
 
@Injectable()
export class TracerService implements OnModuleInit, OnModuleDestroy {
  private sdk?: NodeSDK;
 
  constructor(private configService: ConfigService) {
    const serviceName = this.configService.get('SERVICE_NAME', '1uy-backend');
    const environment = this.configService.get('NODE_ENV', 'development');
 
    const resource = resourceFromAttributes({
      [SemanticResourceAttributes.SERVICE_NAME]: serviceName,
      [SemanticResourceAttributes.DEPLOYMENT_ENVIRONMENT]: environment,
    });
 
    const jaegerEndpoint = this.configService.get<string>('JAEGER_ENDPOINT');
    const otlpEndpoint = this.configService.get<string>('OTLP_TRACES_ENDPOINT');
 
    const derivedFromJaeger = jaegerEndpoint && jaegerEndpoint !== 'off'
      ? jaegerEndpoint
          .replace(':14268', ':4318')
          .replace('/api/traces', '/v1/traces')
      : undefined;
 
    const resolvedEndpoint = otlpEndpoint || derivedFromJaeger;
 
    const exporter = resolvedEndpoint
      ? new OTLPTraceExporter({ url: resolvedEndpoint })
      : undefined;
 
    Iif (exporter) {
      this.sdk = new NodeSDK({
        resource,
        traceExporter: exporter,
        instrumentations: [getNodeAutoInstrumentations()],
      });
    }
  }
 
  async onModuleInit() {
    try {
      await this.sdk?.start();
      console.log('Tracing initialized');
    } catch (error) {
      console.error('Error initializing tracing', error);
    }
  }
 
  async onModuleDestroy() {
    try {
      await this.sdk?.shutdown();
      console.log('Tracing terminated');
    } catch (error) {
      console.error('Error terminating tracing', error);
    }
  }
}