telemetry with next.js and opentelemetry

Viewed 17

is there any way to deploy OpenTelemetry in next.js without having to create a custom server?

what I found would boil down to the following codes:

  • tracing.js:
'use strict'
 
const opentelemetry = require('@opentelemetry/sdk-node');
const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-otlp-grpc');
 
 
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
 
// custom nextjs server
const { startServer } = require('./server');
 
// configure the SDK to export telemetry data to the console
// enable all auto-instrumentations from the meta package
const exporterOptions = {
 url: 'http://localhost:4317',
}
const traceExporter = new OTLPTraceExporter(exporterOptions);
const sdk = new opentelemetry.NodeSDK({
 resource: new Resource({
   [SemanticResourceAttributes.SERVICE_NAME]: 'SigNoz-Nextjs-Example'
 }),
 traceExporter,
 instrumentations: [getNodeAutoInstrumentations()]
});
 
// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk.start()
 .then(() => console.log('Tracing initialized'))
 .then(() => startServer())
 .catch((error) => console.log('Error initializing tracing', error));
 
// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
 sdk.shutdown()
   .then(() => console.log('Tracing terminated'))
   .catch((error) => console.log('Error terminating tracing', error))
   .finally(() => process.exit(0));
});
 
module.exports = sdk
  • server.js:
const { createServer } = require("http")
const { parse } = require("url")
const next = require("next")

const dev = process.env.NODE_ENV !== "production"
const app = next({ dev })
const handle = app.getRequestHandler()

module.exports = {
  startServer: async function startServer() {
    return app.prepare().then(() => {
      createServer((req, res) => {
        const parsedUrl = parse(req.url, true)
        handle(req, res, parsedUrl)
      }).listen(8080, (err) => {
        if (err) throw err
        console.log("> Ready on http://localhost:8080")
      })
    })
  },
}

this comes from this link.

I don't think it's a right and "clean" approach. How do I implant in a less "invasive" way?

0 Answers
Related