Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(logs): attach real trace exemplars to logs-ingestion pushed metrics (#70106)

Daniel Visca0a83bc389214
diff --git a/nodejs/src/common/metrics/exemplars.ts b/nodejs/src/common/metrics/exemplars.ts
new file mode 100644
index 000000000000..52565aae3408
--- /dev/null
+++ b/nodejs/src/common/metrics/exemplars.ts
@@ -0,0 +1,96 @@
+import { Attributes, Counter, Histogram, TraceFlags, isSpanContextValid, trace } from '@opentelemetry/api'
+
+/**
+ * Exemplar side-buffer for the OTLP metrics push.
+ *
+ * The upstream OTel JS SDK ships exemplar classes but never wires them into
+ * recording or export (as of sdk-metrics 2.7.1 nothing samples exemplars and
+ * otlp-transformer never serializes them), so metrics pushed through the SDK
+ * can never link to traces. Instead, the instrument wrappers below capture the
+ * active sampled span context at record time, keyed by series (instrument name
+ * + attributes), and OtlpJsonMetricExporter attaches the buffered exemplars to
+ * the matching data points at export time.
+ *
+ * One exemplar per series per export interval (last measurement wins) — the
+ * metric-to-trace pivot needs one representative trace, not every one.
+ */
+
+export interface BufferedExemplar {
+ value: number
+ timeUnixNano: string
+ traceId: string
+ spanId: string
+}
+
+// Bounds memory if a caller records against unexpectedly high-cardinality
+// attributes; new series beyond the cap just go exemplar-less until a drain.
+const MAX_BUFFERED_EXEMPLARS = 512
+
+let buffer = new Map<string, BufferedExemplar>()
+
+export function exemplarKey(instrumentName: string, attributes?: Attributes): string {
+ const sorted = Object.entries(attributes ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
+ return `${instrumentName}|${JSON.stringify(sorted)}`
+}
+
+export function offerExemplar(instrumentName: string, value: number, attributes?: Attributes): void {
+ const spanContext = trace.getActiveSpan()?.spanContext()
+ if (!spanContext || !isSpanContextValid(spanContext) || !(spanContext.traceFlags & TraceFlags.SAMPLED)) {
+ return
+ }
+ const key = exemplarKey(instrumentName, attributes)
+ if (!buffer.has(key) && buffer.size >= MAX_BUFFERED_EXEMPLARS) {
+ return
+ }
+ buffer.set(key, {
+ value,
+ timeUnixNano: (BigInt(Date.now()) * 1_000_000n).toString(),
+ traceId: spanContext.traceId,
+ spanId: spanContext.spanId,
+ })
+}
+
+/** Hands the current buffer to the exporter and starts a fresh interval. */
+export function drainExemplars(): Map<string, BufferedExemplar> {
+ const drained = buffer
+ buffer = new Map()
+ return drained
+}
+
+/**
+ * Puts drained exemplars back after a failed export so the next (cumulative)
+ * export can still carry them. Entries recorded since the drain are newer and win.
+ */
+export function restoreExemplars(drained: Map<string, BufferedExemplar>): void {
+ for (const [key, exemplar] of drained) {
+ if (buffer.size >= MAX_BUFFERED_EXEMPLARS) {
+ return
+ }
+ if (!buffer.has(key)) {
+ buffer.set(key, exemplar)
+ }
+ }
+}
+
+/** Same interface as the wrapped counter, so call sites don't change. */
+export function counterWithExemplars(instrumentName: string, counter: Counter): Counter {
+ return {
+ add: (value: number, attributes?: Attributes, ctx?: unknown): void => {
+ offerExemplar(instrumentName, value, attributes)
+ counter.add(value, attributes, ctx as never)
+ },
+ }
+}
+
+export function histogramWithExemplars(instrumentName: string, histogram: Histogram): Histogram {
+ return {
+ record: (value: number, attributes?: Attributes, ctx?: unknown): void => {
+ offerExemplar(instrumentName, value, attributes)
+ histogram.record(value, attributes, ctx as never)
+ },
+ }
+}
+
+export function resetExemplarsForTests(): void {
+ buffer = new Map()
+}
diff --git a/nodejs/src/common/metrics/otel-metrics.ts b/nodejs/src/common/metrics/otel-metrics.ts
index 9bf140563d5b..e79794ef2ed8 100644
--- a/nodejs/src/common/metrics/otel-metrics.ts
+++ b/nodejs/src/common/metrics/otel-metrics.ts
@@ -1,5 +1,4 @@
import { Counter, metrics as metricsApi } from '@opentelemetry/api'
-import { OTLPMetricExporter } from '@opentelemetry/exporter-metrics-otlp-http'
import { resourceFromAttributes } from '@opentelemetry/resources'
import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from '@opentelemetry/semantic-conventions'
@@ -9,6 +8,9 @@ import { defaultConfig } from '~/common/config/config'
import { logger } from '~/common/utils/logger'
import { registerShutdownHandler } from '~/lifecycle'
+import { counterWithExemplars } from './exemplars'
+import { OtlpJsonMetricExporter } from './otlp-json-exporter'
+
/**
* OTLP metrics push — the same OTel-SDK path customers use, pointed at our own
* ingest (capture-logs /v1/metrics). Complements tracing/otel.ts (spans) and the
@@ -43,7 +45,10 @@ export const initMetrics = (): void => {
}),
readers: [
new PeriodicExportingMetricReader({
- exporter: new OTLPMetricExporter({
+ // Not the stock OTLPMetricExporter: the upstream JS pipeline drops
+ // exemplars, and the metric-to-trace pivot needs them (see the
+ // exporter's docstring).
+ exporter: new OtlpJsonMetricExporter({
url: defaultConfig.OTEL_METRICS_EXPORT_URL,
headers: { Authorization: `Bearer ${defaultConfig.OTEL_METRICS_EXPORT_TOKEN}` },
}),
@@ -73,9 +78,12 @@ export function recordPiiReplacements(source: string, count: number): void {
return
}
if (piiReplacementsCounter === null) {
- piiReplacementsCounter = metricsApi.getMeter('logs-ingestion').createCounter('logs_pii_replacements_total', {
- description: 'PII values replaced by the ingest scrubber, by pipeline source (logs | traces).',
- })
+ piiReplacementsCounter = counterWithExemplars(
+ 'logs_pii_replacements_total',
+ metricsApi.getMeter('logs-ingestion').createCounter('logs_pii_replacements_total', {
+ description: 'PII values replaced by the ingest scrubber, by pipeline source (logs | traces).',
+ })
+ )
}
piiReplacementsCounter.add(count, { source })
}
diff --git a/nodejs/src/common/metrics/otlp-json-exporter.test.ts b/nodejs/src/common/metrics/otlp-json-exporter.test.ts
new file mode 100644
index 000000000000..a730ceb25bc1
--- /dev/null
+++ b/nodejs/src/common/metrics/otlp-json-exporter.test.ts
@@ -0,0 +1,174 @@
+import { context, propagation, trace } from '@opentelemetry/api'
+import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics'
+import { NodeTracerProvider } from '@opentelemetry/sdk-trace-node'
+
+import { parseJSON } from '~/common/utils/json-parse'
+import { internalFetch } from '~/common/utils/request'
+
+import { counterWithExemplars, histogramWithExemplars, resetExemplarsForTests } from './exemplars'
+import { OtlpJsonMetricExporter } from './otlp-json-exporter'
+
+jest.mock('~/common/utils/request', () => ({
+ ...jest.requireActual('~/common/utils/request'),
+ internalFetch: jest.fn(),
+}))
+
+// The upstream OTel JS pipeline silently drops exemplars end to end: the SDK never
+// samples them and otlp-transformer never serializes them. This exporter is the only
+// thing standing between us and exemplar-less metrics — these tests guard both the
+// exemplar attachment and the OTLP/JSON wire shape capture-logs parses (hex trace ids,
+// camelCase fields, stringified unix nanos).
+describe('OtlpJsonMetricExporter', () => {
+ let provider: MeterProvider
+ let reader: PeriodicExportingMetricReader
+ let tracerProvider: NodeTracerProvider
+ const fetchMock = jest.mocked(internalFetch)
+
+ beforeEach(() => {
+ resetExemplarsForTests()
+ fetchMock.mockReset().mockResolvedValue({ status: 200, dump: () => Promise.resolve() } as any)
+ reader = new PeriodicExportingMetricReader({
+ exporter: new OtlpJsonMetricExporter({
+ url: 'http://capture-logs.local/v1/metrics',
+ headers: { Authorization: 'Bearer phc_test' },
+ }),
+ exportIntervalMillis: 60_000,
+ })
+ provider = new MeterProvider({ readers: [reader] })
+ tracerProvider = new NodeTracerProvider()
+ tracerProvider.register()
+ })
+
+ afterEach(async () => {
+ await provider.shutdown()
+ await tracerProvider.shutdown()
+ trace.disable()
+ context.disable()
+ propagation.disable()
+ jest.restoreAllMocks()
+ })
+
+ const exportedBody = (): any => {
+ expect(fetchMock).toHaveBeenCalled()
+ const [url, init] = fetchMock.mock.calls[fetchMock.mock.calls.length - 1]
+ expect(url).toBe('http://capture-logs.local/v1/metrics')
+ expect(init?.headers).toMatchObject({
+ Authorization: 'Bearer phc_test',
+ 'Content-Type': 'application/json',
+ })
+ return parseJSON(init?.body as string)
+ }
+
+ const metricsByName = (body: any): Record<string, any> => {
+ const out: Record<string, any> = {}
+ for (const rm of body.resourceMetrics) {
+ for (const sm of rm.scopeMetrics) {
+ for (const metric of sm.metrics) {
+ out[metric.name] = metric
+ }
+ }
+ }
+ return out
+ }
+
+ it('serializes counters and histograms with exemplars from the active span', async () => {
+ const meter = provider.getMeter('test-meter')
+ const counter = counterWithExemplars('records_dropped_total', meter.createCounter('records_dropped_total'))
+ const histogram = histogramWithExemplars(
+ 'processing_seconds',
+ meter.createHistogram('processing_seconds', {
+ advice: { explicitBucketBoundaries: [0.01, 0.1, 1] },
+ })
+ )
+
+ let traceIdHex = ''
+ let spanIdHex = ''
+ trace.getTracer('test').startActiveSpan('handleEachBatch', (span) => {
+ traceIdHex = span.spanContext().traceId
+ spanIdHex = span.spanContext().spanId
+ counter.add(7, { team_id: '42' })
+ histogram.record(0.05, { codec: 'gzip' })
+ span.end()
+ })
+
+ await reader.forceFlush()
+ const metrics = metricsByName(exportedBody())
+
+ const sumPoint = metrics['records_dropped_total'].sum.dataPoints[0]
+ expect(metrics['records_dropped_total'].sum.isMonotonic).toBe(true)
+ expect(metrics['records_dropped_total'].sum.aggregationTemporality).toBe(2)
+ expect(sumPoint.asDouble).toBe(7)
+ expect(sumPoint.attributes).toEqual([{ key: 'team_id', value: { stringValue: '42' } }])
+ expect(sumPoint.timeUnixNano).toMatch(/^\d+$/)
+ expect(sumPoint.exemplars).toEqual([
+ expect.objectContaining({ asDouble: 7, traceId: traceIdHex, spanId: spanIdHex }),
+ ])
+
+ const histPoint = metrics['processing_seconds'].histogram.dataPoints[0]
+ expect(metrics['processing_seconds'].histogram.aggregationTemporality).toBe(2)
+ expect(histPoint.count).toBe(1)
+ expect(histPoint.sum).toBeCloseTo(0.05)
+ expect(histPoint.explicitBounds).toEqual([0.01, 0.1, 1])
+ expect(histPoint.bucketCounts).toEqual([0, 1, 0, 0])
+ expect(histPoint.exemplars).toEqual([
+ expect.objectContaining({ asDouble: 0.05, traceId: traceIdHex, spanId: spanIdHex }),
+ ])
+ })
+
+ it('omits exemplars for measurements recorded outside any span', async () => {
+ const meter = provider.getMeter('test-meter')
+ const counter = counterWithExemplars('records_received_total', meter.createCounter('records_received_total'))
+
+ counter.add(3)
+
+ await reader.forceFlush()
+ const metrics = metricsByName(exportedBody())
+ const point = metrics['records_received_total'].sum.dataPoints[0]
+ expect(point.asDouble).toBe(3)
+ expect(point.exemplars).toBeUndefined()
+ })
+
+ it.each([
+ ['a rejected request', () => fetchMock.mockRejectedValueOnce(new Error('connect ECONNREFUSED'))],
+ [
+ 'a non-2xx response',
+ () => fetchMock.mockResolvedValueOnce({ status: 503, dump: () => Promise.resolve() } as any),
+ ],
+ ])('re-buffers exemplars after %s so the next export still carries them', async (_name, primeFailure) => {
+ primeFailure()
+ const meter = provider.getMeter('test-meter')
+ const counter = counterWithExemplars('records_dropped_total', meter.createCounter('records_dropped_total'))
+
+ let traceIdHex = ''
+ trace.getTracer('test').startActiveSpan('batch', (span) => {
+ traceIdHex = span.spanContext().traceId
+ counter.add(5, { team_id: '42' })
+ span.end()
+ })
+
+ await reader.forceFlush().catch(() => {}) // failed export
+ await reader.forceFlush() // retried export succeeds
+
+ const metrics = metricsByName(exportedBody())
+ const point = metrics['records_dropped_total'].sum.dataPoints[0]
+ expect(point.exemplars).toEqual([expect.objectContaining({ asDouble: 5, traceId: traceIdHex })])
+ })
+
+ it('an exemplar matches only the data point series it was recorded against', async () => {
+ const meter = provider.getMeter('test-meter')
+ const counter = counterWithExemplars('records_dropped_total', meter.createCounter('records_dropped_total'))
+
+ counter.add(1, { team_id: '1' })
+ trace.getTracer('test').startActiveSpan('batch', (span) => {
+ counter.add(2, { team_id: '2' })
+ span.end()
+ })
+
+ await reader.forceFlush()
+ const metrics = metricsByName(exportedBody())
+ const points = metrics['records_dropped_total'].sum.dataPoints
+ const byTeam = Object.fromEntries(points.map((p: any) => [p.attributes[0].value.stringValue, p]))
+ expect(byTeam['1'].exemplars).toBeUndefined()
+ expect(byTeam['2'].exemplars).toHaveLength(1)
+ })
+})
diff --git a/nodejs/src/common/metrics/otlp-json-exporter.ts b/nodejs/src/common/metrics/otlp-json-exporter.ts
new file mode 100644
index 000000000000..44999314a511
--- /dev/null
+++ b/nodejs/src/common/metrics/otlp-json-exporter.ts
@@ -0,0 +1,230 @@
+import { Attributes, ValueType } from '@opentelemetry/api'
+import {
+ AggregationTemporality,
+ DataPoint,
+ DataPointType,
+ Histogram as HistogramValue,
+ MetricData,
+ PushMetricExporter,
+ ResourceMetrics,
+} from '@opentelemetry/sdk-metrics'
+
+import { logger } from '~/common/utils/logger'
+import { internalFetch } from '~/common/utils/request'
+
+import { BufferedExemplar, drainExemplars, exemplarKey, restoreExemplars } from './exemplars'
+
+/**
+ * OTLP/JSON metrics exporter that serializes exemplars.
+ *
+ * Exists because the upstream JS pipeline cannot carry exemplars at all:
+ * sdk-metrics never samples them and otlp-transformer's data-point transforms
+ * drop everything but the core fields, so OTLPMetricExporter physically cannot
+ * emit one. The SDK still does all aggregation; this class only replaces the
+ * wire encoding, merging in the exemplar side-buffer (see exemplars.ts).
+ *
+ * Wire shape follows the OTLP/JSON spec that capture-logs parses: camelCase
+ * fields, hex-encoded traceId/spanId, unix nanos as decimal strings.
+ */
+
+// OTLP proto enum values (AggregationTemporality); the SDK's own enum numbers differ.
+const OTLP_TEMPORALITY_DELTA = 1
+const OTLP_TEMPORALITY_CUMULATIVE = 2
+
+// Structural stand-in for @opentelemetry/core's ExportResult/ExportResultCode
+// (not a direct dependency of this workspace); the values are spec-stable.
+interface ExportResult {
+ code: number
+ error?: Error
+}
+const EXPORT_SUCCESS = 0
+const EXPORT_FAILED = 1
+
+interface OtlpJsonMetricExporterOptions {
+ url: string
+ headers?: Record<string, string>
+}
+
+const hrTimeToNanoString = (hrTime: [number, number]): string =>
+ (BigInt(hrTime[0]) * 1_000_000_000n + BigInt(hrTime[1])).toString()
+
+const toAnyValue = (value: unknown): Record<string, unknown> => {
+ if (typeof value === 'string') {
+ return { stringValue: value }
+ }
+ if (typeof value === 'boolean') {
+ return { boolValue: value }
+ }
+ if (typeof value === 'number') {
+ return Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
+ }
+ if (Array.isArray(value)) {
+ return { arrayValue: { values: value.map(toAnyValue) } }
+ }
+ return { stringValue: String(value) }
+}
+
+const toKeyValueList = (attributes: Attributes): Record<string, unknown>[] =>
+ Object.entries(attributes).map(([key, value]) => ({ key, value: toAnyValue(value) }))
+
+const toOtlpTemporality = (temporality: AggregationTemporality): number =>
+ temporality === AggregationTemporality.DELTA ? OTLP_TEMPORALITY_DELTA : OTLP_TEMPORALITY_CUMULATIVE
+
+const toExemplarJson = (exemplar: BufferedExemplar): Record<string, unknown> => ({
+ filteredAttributes: [],
+ timeUnixNano: exemplar.timeUnixNano,
+ asDouble: exemplar.value,
+ traceId: exemplar.traceId,
+ spanId: exemplar.spanId,
+})
+
+export class OtlpJsonMetricExporter implements PushMetricExporter {
+ constructor(private readonly options: OtlpJsonMetricExporterOptions) {}
+
+ selectAggregationTemporality(): AggregationTemporality {
+ return AggregationTemporality.CUMULATIVE
+ }
+
+ export(metrics: ResourceMetrics, resultCallback: (result: ExportResult) => void): void {
+ // Drained here (not in serialize) so a failed export can put them back;
+ // the metrics themselves are cumulative and survive a failed interval anyway.
+ const exemplars = drainExemplars()
+ const body = JSON.stringify(this.serialize(metrics, exemplars))
+ internalFetch(this.options.url, {
+ method: 'POST',
+ headers: { ...this.options.headers, 'Content-Type': 'application/json' },
+ body,
+ })
+ .then(async (response) => {
+ await response.dump()
+ if (response.status >= 200 && response.status < 300) {
+ resultCallback({ code: EXPORT_SUCCESS })
+ } else {
+ logger.warn('OTLP JSON metrics export rejected', { status: response.status })
+ restoreExemplars(exemplars)
+ resultCallback({ code: EXPORT_FAILED })
+ }
+ })
+ .catch((error) => {
+ logger.warn('OTLP JSON metrics export failed', { error: String(error) })
+ restoreExemplars(exemplars)
+ resultCallback({ code: EXPORT_FAILED, error })
+ })
+ }
+
+ forceFlush(): Promise<void> {
+ return Promise.resolve()
+ }
+
+ shutdown(): Promise<void> {
+ return Promise.resolve()
+ }
+
+ private serialize(metrics: ResourceMetrics, exemplars: Map<string, BufferedExemplar>): Record<string, unknown> {
+ return {
+ resourceMetrics: [
+ {
+ resource: { attributes: toKeyValueList(metrics.resource.attributes as Attributes) },
+ scopeMetrics: metrics.scopeMetrics.map((scopeMetrics) => ({
+ scope: {
+ name: scopeMetrics.scope.name,
+ ...(scopeMetrics.scope.version ? { version: scopeMetrics.scope.version } : {}),
+ },
+ metrics: scopeMetrics.metrics
+ .map((metricData) => this.serializeMetric(metricData, exemplars))
+ .filter((metric): metric is Record<string, unknown> => metric !== null),
+ })),
+ },
+ ],
+ }
+ }
+
+ private serializeMetric(
+ metricData: MetricData,
+ exemplars: Map<string, BufferedExemplar>
+ ): Record<string, unknown> | null {
+ const base = {
+ name: metricData.descriptor.name,
+ description: metricData.descriptor.description,
+ unit: metricData.descriptor.unit,
+ }
+ switch (metricData.dataPointType) {
+ case DataPointType.SUM:
+ return {
+ ...base,
+ sum: {
+ dataPoints: metricData.dataPoints.map((dp) =>
+ this.serializeNumberDataPoint(dp, metricData, exemplars)
+ ),
+ aggregationTemporality: toOtlpTemporality(metricData.aggregationTemporality),
+ isMonotonic: metricData.isMonotonic,
+ },
+ }
+ case DataPointType.GAUGE:
+ return {
+ ...base,
+ gauge: {
+ dataPoints: metricData.dataPoints.map((dp) =>
+ this.serializeNumberDataPoint(dp, metricData, exemplars)
+ ),
+ },
+ }
+ case DataPointType.HISTOGRAM:
+ return {
+ ...base,
+ histogram: {
+ dataPoints: metricData.dataPoints.map((dp) =>
+ this.serializeHistogramDataPoint(dp, metricData.descriptor.name, exemplars)
+ ),
+ aggregationTemporality: toOtlpTemporality(metricData.aggregationTemporality),
+ },
+ }
+ default:
+ // We create no exponential histograms; dropping beats sending a shape
+ // the ingest would reject.
+ logger.warn('OTLP JSON metrics export skipping unsupported data point type', {
+ name: metricData.descriptor.name,
+ dataPointType: metricData.dataPointType,
+ })
+ return null
+ }
+ }
+
+ private serializeNumberDataPoint(
+ dataPoint: DataPoint<number>,
+ metricData: MetricData,
+ exemplars: Map<string, BufferedExemplar>
+ ): Record<string, unknown> {
+ const exemplar = exemplars.get(exemplarKey(metricData.descriptor.name, dataPoint.attributes))
+ return {
+ attributes: toKeyValueList(dataPoint.attributes),
+ startTimeUnixNano: hrTimeToNanoString(dataPoint.startTime),
+ timeUnixNano: hrTimeToNanoString(dataPoint.endTime),
+ ...(metricData.descriptor.valueType === ValueType.INT
+ ? { asInt: dataPoint.value }
+ : { asDouble: dataPoint.value }),
+ ...(exemplar ? { exemplars: [toExemplarJson(exemplar)] } : {}),
+ }
+ }
+
+ private serializeHistogramDataPoint(
+ dataPoint: DataPoint<HistogramValue>,
+ metricName: string,
+ exemplars: Map<string, BufferedExemplar>
+ ): Record<string, unknown> {
+ const exemplar = exemplars.get(exemplarKey(metricName, dataPoint.attributes))
+ const histogram = dataPoint.value
+ return {
+ attributes: toKeyValueList(dataPoint.attributes),
+ startTimeUnixNano: hrTimeToNanoString(dataPoint.startTime),
+ timeUnixNano: hrTimeToNanoString(dataPoint.endTime),
+ count: histogram.count,
+ sum: histogram.sum,
+ bucketCounts: histogram.buckets.counts,
+ explicitBounds: histogram.buckets.boundaries,
+ ...(histogram.min !== undefined ? { min: histogram.min } : {}),
+ ...(histogram.max !== undefined ? { max: histogram.max } : {}),
+ ...(exemplar ? { exemplars: [toExemplarJson(exemplar)] } : {}),
+ }
+ }
+}
diff --git a/nodejs/src/logs/ingestion-otel-metrics.ts b/nodejs/src/logs/ingestion-otel-metrics.ts
index 2b027de419de..fd161d25a21c 100644
--- a/nodejs/src/logs/ingestion-otel-metrics.ts
+++ b/nodejs/src/logs/ingestion-otel-metrics.ts
@@ -1,4 +1,6 @@
-import { Attributes, Counter, Histogram, metrics as metricsApi } from '@opentelemetry/api'
+import { Attributes, Counter, Histogram, Meter, MetricOptions, metrics as metricsApi } from '@opentelemetry/api'
+
+import { counterWithExemplars, histogramWithExemplars } from '~/common/metrics/exemplars'
/**
* OTLP-pushed twins of the core logs-ingestion prom counters. The prom side keeps
@@ -30,38 +32,45 @@ const PROCESSING_DURATION_BOUNDARIES = [0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1]
let instruments: LogsIngestionInstruments | null = null
+// The wrappers buffer an exemplar (active span context) per record, which the
+// OTLP JSON exporter attaches at export — the upstream SDK path can't do this.
+const createCounter = (meter: Meter, name: string, options?: MetricOptions): Counter =>
+ counterWithExemplars(name, meter.createCounter(name, options))
+const createHistogram = (meter: Meter, name: string, options?: MetricOptions): Histogram =>
+ histogramWithExemplars(name, meter.createHistogram(name, options))
+
function getInstruments(): LogsIngestionInstruments {
if (instruments === null) {
const meter = metricsApi.getMeter('logs-ingestion')
instruments = {
- bytesReceived: meter.createCounter('logs_ingestion_bytes_received_total', {
+ bytesReceived: createCounter(meter, 'logs_ingestion_bytes_received_total', {
description: 'Total uncompressed bytes received for logs ingestion',
unit: 'By',
}),
- recordsReceived: meter.createCounter('logs_ingestion_records_received_total', {
+ recordsReceived: createCounter(meter, 'logs_ingestion_records_received_total', {
description: 'Total log records received',
}),
- bytesAllowed: meter.createCounter('logs_ingestion_bytes_allowed_total', {
+ bytesAllowed: createCounter(meter, 'logs_ingestion_bytes_allowed_total', {
description: 'Total uncompressed bytes allowed through quota and rate limiting',
unit: 'By',
}),
- recordsAllowed: meter.createCounter('logs_ingestion_records_allowed_total', {
+ recordsAllowed: createCounter(meter, 'logs_ingestion_records_allowed_total', {
description: 'Total log records allowed through quota and rate limiting',
}),
- bytesDropped: meter.createCounter('logs_ingestion_bytes_dropped_total', {
+ bytesDropped: createCounter(meter, 'logs_ingestion_bytes_dropped_total', {
description: 'Total uncompressed bytes dropped due to quota or rate limiting',
unit: 'By',
}),
- recordsDropped: meter.createCounter('logs_ingestion_records_dropped_total', {
+ recordsDropped: createCounter(meter, 'logs_ingestion_records_dropped_total', {
description: 'Total log records dropped due to quota or rate limiting',
}),
- messagesDropped: meter.createCounter('logs_ingestion_message_dropped_count', {
+ messagesDropped: createCounter(meter, 'logs_ingestion_message_dropped_count', {
description: 'The number of logs ingestion messages dropped',
}),
- messagesDlq: meter.createCounter('logs_ingestion_message_dlq_count', {
+ messagesDlq: createCounter(meter, 'logs_ingestion_message_dlq_count', {
description: 'The number of logs ingestion messages sent to DLQ',
}),
- processingDuration: meter.createHistogram('logs_ingestion_processing_duration_seconds', {
+ processingDuration: createHistogram(meter, 'logs_ingestion_processing_duration_seconds', {
description: 'Time spent processing log messages (AVRO decode/encode cycle)',
unit: 's',
advice: { explicitBucketBoundaries: PROCESSING_DURATION_BOUNDARIES },
diff --git a/rust/capture-logs/tests/metrics_test.rs b/rust/capture-logs/tests/metrics_test.rs
index 460f0908e4c9..37acfa5fb1ad 100644
--- a/rust/capture-logs/tests/metrics_test.rs
+++ b/rust/capture-logs/tests/metrics_test.rs
@@ -437,6 +437,91 @@ fn edge_expo_with_minimal_fields_only() {
assert_eq!(eh.data_points.len(), 1);
}
+/// Contract test for the nodejs OtlpJsonMetricExporter (nodejs/src/common/metrics/
+/// otlp-json-exporter.ts): its exact wire shape — camelCase fields, hex trace/span
+/// ids, string unix nanos, exemplars on sum and histogram data points — must parse
+/// and flatten into rows carrying the exemplar's trace context. If either side
+/// drifts, the metric-to-trace pivot silently loses its links.
+#[test]
+fn nodejs_otlp_json_exporter_exemplars_flatten_into_rows() {
+ let json = r#"{
+ "resourceMetrics":[{
+ "resource":{"attributes":[{"key":"service.name","value":{"stringValue":"logs-ingestion"}}]},
+ "scopeMetrics":[{
+ "scope":{"name":"logs-ingestion"},
+ "metrics":[
+ {"name":"logs_ingestion_records_dropped_total","description":"","unit":"","sum":{
+ "dataPoints":[{
+ "attributes":[{"key":"team_id","value":{"stringValue":"42"}}],
+ "startTimeUnixNano":"1700000000000000000",
+ "timeUnixNano":"1700000060000000000",
+ "asDouble":7,
+ "exemplars":[{
+ "filteredAttributes":[],
+ "timeUnixNano":"1700000030000000000",
+ "asDouble":7,
+ "traceId":"0102030405060708090a0b0c0d0e0f10",
+ "spanId":"0102030405060708"
+ }]
+ }],
+ "aggregationTemporality":2,
+ "isMonotonic":true
+ }},
+ {"name":"logs_ingestion_processing_duration_seconds","description":"","unit":"s","histogram":{
+ "dataPoints":[{
+ "attributes":[],
+ "startTimeUnixNano":"1700000000000000000",
+ "timeUnixNano":"1700000060000000000",
+ "count":1,
+ "sum":0.05,
+ "bucketCounts":[0,1,0,0],
+ "explicitBounds":[0.01,0.1,1],
+ "min":0.05,
+ "max":0.05,
+ "exemplars":[{
+ "filteredAttributes":[],
+ "timeUnixNano":"1700000030000000000",
+ "asDouble":0.05,
+ "traceId":"0102030405060708090a0b0c0d0e0f10",
+ "spanId":"0102030405060708"
+ }]
+ }],
+ "aggregationTemporality":2
+ }}
+ ]
+ }]
+ }]
+ }"#;
+
+ let request = parse_otel_metrics_message(&Bytes::from(json)).expect("parse ok");
+ let resource_metrics = &request.resource_metrics[0];
+ let scope_metrics = &resource_metrics.scope_metrics[0];
+
+ // base64 of the raw exemplar id bytes — the encoding KafkaMetricRow stores.
+ let expected_trace_id = "AQIDBAUGBwgJCgsMDQ4PEA==";
+ let expected_span_id = "AQIDBAUGBwg=";
+
+ for metric in &scope_metrics.metrics {
+ let (rows, _) = capture_logs::metric_record::flatten_metric(
+ metric.clone(),
+ resource_metrics.resource.as_ref(),
+ scope_metrics.scope.as_ref(),
+ )
+ .expect("flatten ok");
+ assert_eq!(rows.len(), 1, "one row per data point for {}", metric.name);
+ assert_eq!(
+ rows[0].trace_id, expected_trace_id,
+ "exemplar trace id must survive into the row for {}",
+ metric.name
+ );
+ assert_eq!(
+ rows[0].span_id, expected_span_id,
+ "exemplar span id must survive into the row for {}",
+ metric.name
+ );
+ }
+}
+
/// Same as above for summary: required-by-serde fields (sum is non-Option!)
/// must be defaulted when the client omits them, or the metric silently drops.
#[test]