opentelemetry-js-contrib: Hi, I am not able to trace the mongodb in opentelemetry

I have integrated OpenTelemetry in Nestjs with Jaeger and it’s working fine, but i am not able to trace the MongoDB interaction. I am using below code

const sdk = new opentelemetry.NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: 'demo-service',
  }),

  instrumentations: [getNodeAutoInstrumentations({
    "@opentelemetry/instrumentation-mongodb":{
        enhancedDatabaseReporting: true
        }
        }),
    
    ],
  spanProcessor: new BatchSpanProcessor(new JaegerExporter(options))
});

I tried without MongoDB instrument also

instrumentations: [getNodeAutoInstrumentations()],
  spanProcessor: new BatchSpanProcessor(new JaegerExporter(options))
});

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 3
  • Comments: 20 (9 by maintainers)

Most upvoted comments

@eharaj1 I don’t know why you don’t get mongo spans. I just want to mention you might be able to use the mongoose instrumentation.

@Flarna Ok let me share the whole code,

tracing.ts


/* tracing.js */

import { JaegerExporter } from "@opentelemetry/exporter-jaeger";
const { BatchSpanProcessor } = require("@opentelemetry/tracing");
import  * as process from "process"
import { Resource } from '@opentelemetry/resources';
import { SemanticResourceAttributes } from '@opentelemetry/semantic-conventions';
// Require dependencies
import * as opentelemetry  from "@opentelemetry/sdk-node";
//const prometheusExporter = new PrometheusExporter();
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";

const options =  {
  tags: [], // optional
  // You can use the default UDPSender
  host:'localhost', // optional
  port: 6832, // optional
  // OR you can use the HTTPSender as follows
  //endpoint: 'http://localhost:4317',
  maxPacketSize: 65000 // optional
}
const sdk = new opentelemetry.NodeSDK({
  resource: new Resource({
    [SemanticResourceAttributes.SERVICE_NAME]: process.env.JAEGER_SERVICE_NAME,
  }),
  //traceExporter: new opentelemetry.tracing.ConsoleSpanExporter(),
  //metricExporter: prometheusExporter,
  instrumentations: [getNodeAutoInstrumentations()],
  spanProcessor: new BatchSpanProcessor(new JaegerExporter(options))
});


process.on("SIGTERM", () => {
  sdk
    .shutdown()
    .then(
      () => console.log("SDK shut down successfully"),
      (err) => console.log("Error shutting down SDK", err)
    )
    .finally(() => process.exit(0));
});

export default sdk;

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './modules/app/app.module';
import sdk from './tracing';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

 await sdk.start();

  await app.listen(process.env.PORT || 3001);
}
bootstrap();

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { CatsModule } from '../cats/cats.module';
import { ConfigModule } from '@nestjs/config';
import { MongooseModule } from '@nestjs/mongoose';

/// Mongo Connection /////////
const mongooseModule  = MongooseModule.forRoot(process.env.MONGO_URL || 'mongodb://localhost:27017/demo');


@Module({
  imports: [
      CatsModule, 
     mongooseModule,
      ConfigModule.forRoot({
        isGlobal: true,
      })
    ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

cats.module.ts

import { Module } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { CatsSchema } from '../schemas/cats.scheme';
import { CatsController } from './cats.controller';
import { CatsService } from './cats.service';

@Module({
    imports : [
        MongooseModule.forFeature([{
            name: 'Cats',
            schema: CatsSchema,
          }])
        ],
  controllers: [CatsController],
  providers: [CatsService],
})
export class CatsModule {}

cats.controller.ts

import { Controller, Get,  Query, Post, Body, HttpException, HttpStatus, Param, UseFilters } from '@nestjs/common';
import {CatCreateValidator} from '../dto/validator.dto'
import {CatsService} from './cats.service';

@Controller('cats')
export class CatsController {

constructor(private readonly catsService: CatsService, private readonly redis: RedisService) {}

  @Get()
  async findAll() {
    try{
        return this.catsService.getAll();
    }catch(error){
        throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
    }
    
  }


  @Get("/:id")
 async getCat(@Param('id') cat_id: string){
   
    try{
        return await this.catsService.getCat(cat_id);
    }catch(error){
        throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
    }
  }
  
  @Post()
  async insertCat(@Body() body: CatCreateValidator){
      try{
        return await this.catsService.insertCat(body);
      }catch(error){
        throw new HttpException(error.message, HttpStatus.INTERNAL_SERVER_ERROR)
      }
    
  }
}

cats.service.ts

import { Injectable } from '@nestjs/common';
import { ResponseDTO } from '../dto/response.dto';
import  {CATS_MESSAGES}  from 'src/shared/constants';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { ICats } from '../interfaces/cats.interface';
@Injectable()
export class CatsService {

    constructor(
        @InjectModel('Cats') private readonly catsModel: Model<ICats>
        ) {}
  

     async getAll(): Promise<any> {
        const resDTO = new ResponseDTO();
        const cats = await this.catsModel.find();
        resDTO.success = true;
        resDTO.data = cats;
        return resDTO;
      
    }

     async getCat(cat_id: string): Promise<any> {
        const resDTO = new ResponseDTO();
        const cat = await this.catsModel.findById(cat_id)
        if(cat){
            resDTO.success = true;
            resDTO.data = cat; 
        }else{
            resDTO.success = false;
            resDTO.message = CATS_MESSAGES.CAT_NOTFOUND;
        }
        return resDTO;
    }
    insertCat(cat: any): ResponseDTO{
        const resDTO = new ResponseDTO();
        this.catsModel.create(cat);
        resDTO.success = true;
        resDTO.data = cat;
        resDTO.message = CATS_MESSAGES.CAT_CREATED;
        return resDTO;
    }
  }

I hope this is enough to reproduce and check the code.