|
| 1 | +const { DiagConsoleLogger, DiagLogLevel, diag } = require('@opentelemetry/api') |
| 2 | +const { getNodeAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-node') |
| 3 | + |
| 4 | +/** |
| 5 | + * Error: "@opentelemetry/instrumentation-grpc Module @grpc/grpc-js has |
| 6 | + * been loaded before @opentelemetry/instrumentation-grpc so it might not work, |
| 7 | + * please initialize it before requiring @grpc/grpc-js" |
| 8 | + * |
| 9 | + * Fix: "call getNodeAutoInstrumentations() before require('@opentelemetry/sdk-node');" |
| 10 | + */ |
| 11 | +// |
| 12 | + |
| 13 | +// Disable DNS instrumentation, because the instrumentation does not correctly patches `dns.lookup` function |
| 14 | +// if the function is converted to a promise-based method using `utils.promisify(dns.lookup)` |
| 15 | +// See: https://github.com/Joystream/joystream/pull/4779#discussion_r1262515887 |
| 16 | +const instrumentations = getNodeAutoInstrumentations({ |
| 17 | + '@opentelemetry/instrumentation-dns': { enabled: false }, |
| 18 | + '@opentelemetry/instrumentation-pg': { enhancedDatabaseReporting: true }, |
| 19 | +}) |
| 20 | + |
| 21 | +const { NodeSDK } = require('@opentelemetry/sdk-node') |
| 22 | +const { OTLPMetricExporter } = require('@opentelemetry/exporter-metrics-otlp-proto') |
| 23 | +const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-proto') |
| 24 | +const { PeriodicExportingMetricReader } = require('@opentelemetry/sdk-metrics') |
| 25 | +const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-node') |
| 26 | + |
| 27 | +const path = require('path') |
| 28 | +require('dotenv').config({ path: path.resolve(__dirname, `.env`) }) |
| 29 | + |
| 30 | +// For troubleshooting, set the log level to DiagLogLevel.DEBUG |
| 31 | +diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.INFO) |
| 32 | + |
| 33 | +function addInstrumentation() { |
| 34 | + const instrumentation = new NodeSDK({ |
| 35 | + spanProcessor: new BatchSpanProcessor(new OTLPTraceExporter(), { |
| 36 | + maxQueueSize: parseInt(process.env.OTEL_MAX_QUEUE_SIZE || '8192'), |
| 37 | + maxExportBatchSize: parseInt(process.env.OTEL_MAX_EXPORT_BATCH_SIZE || '1024'), |
| 38 | + }), |
| 39 | + metricReader: new PeriodicExportingMetricReader({ |
| 40 | + exporter: new OTLPMetricExporter(), |
| 41 | + }), |
| 42 | + instrumentations, |
| 43 | + }) |
| 44 | + |
| 45 | + // Start Opentelemetry NodeJS Instrumentation |
| 46 | + diag.info('Starting tracing...') |
| 47 | + instrumentation.start() |
| 48 | + |
| 49 | + // gracefully shut down the SDK on process exit |
| 50 | + process.on('SIGTERM', () => { |
| 51 | + instrumentation |
| 52 | + .shutdown() |
| 53 | + .then(() => console.log('Tracing terminated')) |
| 54 | + .catch((error) => console.log('Error terminating tracing', error)) |
| 55 | + .finally(() => process.exit(0)) |
| 56 | + }) |
| 57 | +} |
| 58 | + |
| 59 | +addInstrumentation() |
0 commit comments