|
| 1 | +import { type MeterProvider } from "@opentelemetry/sdk-metrics"; |
| 2 | +import { performance, monitorEventLoopDelay } from "node:perf_hooks"; |
| 3 | + |
| 4 | +export function startNodejsRuntimeMetrics(meterProvider: MeterProvider) { |
| 5 | + const meter = meterProvider.getMeter("nodejs-runtime", "1.0.0"); |
| 6 | + |
| 7 | + // Event loop utilization (diff between collection intervals) |
| 8 | + let lastElu = performance.eventLoopUtilization(); |
| 9 | + |
| 10 | + const eluGauge = meter.createObservableGauge("nodejs.event_loop.utilization", { |
| 11 | + description: "Event loop utilization over the last collection interval", |
| 12 | + unit: "1", |
| 13 | + }); |
| 14 | + |
| 15 | + // Event loop delay histogram (from perf_hooks) |
| 16 | + const eld = monitorEventLoopDelay({ resolution: 20 }); |
| 17 | + eld.enable(); |
| 18 | + |
| 19 | + const eldP50 = meter.createObservableGauge("nodejs.event_loop.delay.p50", { |
| 20 | + description: "Median event loop delay", |
| 21 | + unit: "s", |
| 22 | + }); |
| 23 | + const eldP99 = meter.createObservableGauge("nodejs.event_loop.delay.p99", { |
| 24 | + description: "p99 event loop delay", |
| 25 | + unit: "s", |
| 26 | + }); |
| 27 | + const eldMax = meter.createObservableGauge("nodejs.event_loop.delay.max", { |
| 28 | + description: "Max event loop delay", |
| 29 | + unit: "s", |
| 30 | + }); |
| 31 | + |
| 32 | + // Heap metrics |
| 33 | + const heapUsed = meter.createObservableGauge("nodejs.heap.used", { |
| 34 | + description: "V8 heap used", |
| 35 | + unit: "By", |
| 36 | + }); |
| 37 | + const heapTotal = meter.createObservableGauge("nodejs.heap.total", { |
| 38 | + description: "V8 heap total allocated", |
| 39 | + unit: "By", |
| 40 | + }); |
| 41 | + |
| 42 | + // Single batch callback for all metrics |
| 43 | + meter.addBatchObservableCallback( |
| 44 | + (obs) => { |
| 45 | + // ELU |
| 46 | + const currentElu = performance.eventLoopUtilization(); |
| 47 | + const diff = performance.eventLoopUtilization(currentElu, lastElu); |
| 48 | + lastElu = currentElu; |
| 49 | + obs.observe(eluGauge, diff.utilization); |
| 50 | + |
| 51 | + // Event loop delay (nanoseconds -> seconds) |
| 52 | + obs.observe(eldP50, eld.percentile(50) / 1e9); |
| 53 | + obs.observe(eldP99, eld.percentile(99) / 1e9); |
| 54 | + obs.observe(eldMax, eld.max / 1e9); |
| 55 | + eld.reset(); |
| 56 | + |
| 57 | + // Heap |
| 58 | + const mem = process.memoryUsage(); |
| 59 | + obs.observe(heapUsed, mem.heapUsed); |
| 60 | + obs.observe(heapTotal, mem.heapTotal); |
| 61 | + }, |
| 62 | + [eluGauge, eldP50, eldP99, eldMax, heapUsed, heapTotal] |
| 63 | + ); |
| 64 | +} |
0 commit comments