: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(nodejs): add active trace context to log records (#121900)
José Sequeira403acb1fd891
diff --git a/nodejs/src/common/utils/logger.test.ts b/nodejs/src/common/utils/logger.test.tsindex 9cb0dd96dc08..0e3727f05329 100644--- a/nodejs/src/common/utils/logger.test.ts+++ b/nodejs/src/common/utils/logger.test.ts@@ -1,3 +1,5 @@+import { TraceFlags, trace } from '@opentelemetry/api'+import { Logger } from './logger'describe('Logger', () => {@@ -61,6 +63,31 @@ describe('Logger', () => {`)})+ it('should add the active trace context', () => {+ const getActiveSpan = jest.spyOn(trace, 'getActiveSpan').mockReturnValue(+ trace.wrapSpanContext({+ traceId: '0af7651916cd43dd8448eb211c80319c',+ spanId: 'b7ad6b7169203331',+ traceFlags: TraceFlags.SAMPLED,+ })+ )+ try {+ logger.info('test', { extra: 'extra' })+ } finally {+ getActiveSpan.mockRestore()+ }+ expect(jest.mocked(logger['pino'].info).mock.lastCall).toMatchInlineSnapshot(`+ [+ {+ "extra": "extra",+ "msg": "[TEST] test",+ "span_id": "b7ad6b7169203331",+ "trace_id": "0af7651916cd43dd8448eb211c80319c",+ },+ ]+ `)+ })+// Entrypoints without plugin-server database env (e.g. the recording rasterizer)// import this module transitively. Guards against reintroducing a defaultConfig// import, which throws at module load when that env is missing. NODE_ENV must bediff --git a/nodejs/src/common/utils/logger.ts b/nodejs/src/common/utils/logger.tsindex 2332225f8894..b97e9dba0882 100644--- a/nodejs/src/common/utils/logger.ts+++ b/nodejs/src/common/utils/logger.ts@@ -1,3 +1,4 @@+import { isSpanContextValid, trace } from '@opentelemetry/api'import pino from 'pino'import type { LogLevel } from '~/types'@@ -9,6 +10,17 @@ import { isProdEnv, isTestEnv } from './env-utils'// rasterizer) reach this logger transitively.const logLevel: LogLevel = (process.env.LOG_LEVEL as LogLevel) || (isTestEnv() ? 'warn' : 'info')+// Correlate log lines with the active OTel trace, using the same `trace_id`/`span_id` keys as the+// Django logger so the log collector links them to their trace. Read at emit time so nested spans get+// the right span_id; a no-op when no valid span is in scope (e.g. tracing disabled).+function activeTraceContext(): { trace_id: string; span_id: string } | undefined {+ const spanContext = trace.getActiveSpan()?.spanContext()+ if (!spanContext || !isSpanContextValid(spanContext)) {+ return undefined+ }+ return { trace_id: spanContext.traceId, span_id: spanContext.spanId }+}+export class Logger {private pino: ReturnType<typeof pino>private prefix: string@@ -70,6 +82,7 @@ export class Logger {try {this.pino[level]({+ ...activeTraceContext(),...(extra || {}),msg,})