: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
feat(error-tracking): correlate exception logs by trace (#102234)
Hugues Pouillotd48bc8c4a53c
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex cfa18e9e278c..a89fa3c1765f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2440,8 +2440,16 @@ snapshots:hash: v1.k794b7964.1030bfe45ba31d3fe94873ce09cdaeda8f81e86c0f71072d64a6267c551c6242.0pD2zOgFDmK5w5r-MnEbEzSAtOGpgYFKzEI8oJ8gUcserrortracking-exceptioncard--exception-card-logs--light:hash: v1.k794b7964.c691f17c502c069287778c899ef298787ba804c2a2ce40f47e2ce7fffdcac348.SwdlNY656OF7LWj_IFuHcynkhxd0_yhTkfFFwRPO3gU+ errortracking-exceptioncard--exception-card-logs-with-session-only--dark:+ hash: v1.k794b7964.5bd0ad8b67ae58b27062a16c1a1ebb0680acbd1b5c80f2a55db66c040561c090.sfXIy31iHEXoyLQzR6UugSfwFTceEDkzDhKJa9FTTF0+ errortracking-exceptioncard--exception-card-logs-with-session-only--light:+ hash: v1.k794b7964.35ec7d6a2911530552a6e2943bff6398f5a228aefcfe80b92b8533ad9ca37393.X9IqNWtb6dRuoz_Qt0KuN72wJH4_V38-sX_tC96o66U+ errortracking-exceptioncard--exception-card-logs-with-trace-only--dark:+ hash: v1.k794b7964.a6175cdf02a385b48a39e93883c6f399051d0a47754145322f85ff546f4c68b9.dFOA4sl5dE--49Gdw_bZ7qIa8q64tCMm1iqbk2yfN9I+ errortracking-exceptioncard--exception-card-logs-with-trace-only--light:+ hash: v1.k794b7964.59092739b11c0f25d7d3358f393659aa44b1b2ff575dea689be61f7812893951.bRcmx48NZLYMzT1L9Q5ePERt8aVXPyXIC9c0ZlWpLzEerrortracking-exceptioncard--exception-card-logs-without-session--dark:- hash: v1.k794b7964.1c55aa5eb5758c9f5710a62fe92cccab572ef04501b69d7981a7e0964d6b09e3.59UJwC1G6msLdy-Nn_qOGijQsWoReclGYPWDGeM3kto+ hash: v1.k794b7964.c29d713699bbbdaaad8a3f5d7697c5ef8d453f18a63c9a661894370b4521a658.9WjMf2zGXEiWpaxY3IYj28PMe5FOoYFsFqBkzjBWhjserrortracking-exceptioncard--exception-card-logs-without-session--light:hash: v1.k794b7964.036417710485b035128e3d9334c9ab22ea6c216c567ece5a1668af80de4e16ca.A9auY_Pt1XV2Gixl_rwuvhkMLFZFPlW5S0szuhtkHWQerrortracking-exceptioncard--exception-card-no-in-app--dark:diff --git a/frontend/src/lib/components/Errors/errorPropertiesLogic.ts b/frontend/src/lib/components/Errors/errorPropertiesLogic.tsindex d37d7abcd2d5..830b589a8950 100644--- a/frontend/src/lib/components/Errors/errorPropertiesLogic.ts+++ b/frontend/src/lib/components/Errors/errorPropertiesLogic.ts@@ -17,6 +17,8 @@ import {getFingerprintRecords,getRecordingStatus,getSessionId,+ getSpanId,+ getTraceId,isReleaseIdMissingFromSDK,} from 'lib/components/Errors/utils'import { dayjs } from 'lib/dayjs'@@ -54,6 +56,8 @@ export interface errorPropertiesLogicValues {release: ErrorTrackingRelease | null | undefinedreleaseIdMissingFromSDK: booleansessionId: string | undefined+ spanId: string | undefined+ traceId: string | undefineduuid: string}@@ -79,6 +83,8 @@ export interface errorPropertiesLogicMeta {fingerprintRecords: (properties: Record<string, any>) => FingerprintRecordPart[]hasStacktrace: (exceptionList: ErrorTrackingException[]) => booleansessionId: (properties: Record<string, any>) => string | undefined+ traceId: (properties: Record<string, any>) => string | undefined+ spanId: (properties: Record<string, any>) => string | undefinedrecordingStatus: (properties: Record<string, any>) => string | undefinedgetExceptionFingerprint: (fingerprintRecords: FingerprintRecordPart[]@@ -155,6 +161,14 @@ export const errorPropertiesLogic = kea<errorPropertiesLogicType>([(s) => [s.properties],(properties: ErrorEventProperties) => (properties ? getSessionId(properties) : undefined),],+ traceId: [+ (s) => [s.properties],+ (properties: ErrorEventProperties) => (properties ? getTraceId(properties) : undefined),+ ],+ spanId: [+ (s) => [s.properties],+ (properties: ErrorEventProperties) => (properties ? getSpanId(properties) : undefined),+ ],recordingStatus: [(s) => [s.properties],(properties: ErrorEventProperties) => (properties ? getRecordingStatus(properties) : undefined),diff --git a/frontend/src/lib/components/Errors/utils.test.ts b/frontend/src/lib/components/Errors/utils.test.tsindex 994fe0c53d72..26a0c6a0c77b 100644--- a/frontend/src/lib/components/Errors/utils.test.ts+++ b/frontend/src/lib/components/Errors/utils.test.ts@@ -11,6 +11,8 @@ import {getInstructionAddress,getRuntimeFromLib,getSessionId,+ getSpanId,+ getTraceId,isReleaseIdMissingFromSDK,} from './utils'@@ -230,6 +232,15 @@ describe('Error Display', () => {expect(getSessionId(properties as ErrorEventProperties)).toEqual(expected)})+ it.each([+ ['trace ID', getTraceId, '$trace_id'],+ ['span ID', getSpanId, '$span_id'],+ ] as const)('normalizes the exception %s', (_name, getId, property) => {+ expect(getId({ [property]: 'correlation-id' })).toEqual('correlation-id')+ expect(getId({ [property]: 42 })).toBeUndefined()+ expect(getId({ [property]: '' })).toBeUndefined()+ })+it('normalizes the singular exception release property', () => {const release = getExceptionRelease({$exception_release: {diff --git a/frontend/src/lib/components/Errors/utils.ts b/frontend/src/lib/components/Errors/utils.tsindex 7e58c968cf07..2ce87559b503 100644--- a/frontend/src/lib/components/Errors/utils.ts+++ b/frontend/src/lib/components/Errors/utils.ts@@ -220,11 +220,23 @@ export function getAdditionalProperties()}+function getStringProperty(properties: ErrorEventProperties, key: string): string | undefined {+ const value = properties[key]+ return typeof value === 'string' && value.length > 0 ? value : undefined+}+export function getSessionId(properties: ErrorEventProperties): string | undefined {- const sessionId = properties['$session_id']// $session_id can arrive malformed (e.g. a numeric timestamp) from misbehaving SDKs.// Only a non-empty string is a usable session id; anything else means "no session".- return typeof sessionId === 'string' && sessionId.length > 0 ? sessionId : undefined+ return getStringProperty(properties, '$session_id')+}++export function getTraceId(properties: ErrorEventProperties): string | undefined {+ return getStringProperty(properties, '$trace_id')+}++export function getSpanId(properties: ErrorEventProperties): string | undefined {+ return getStringProperty(properties, '$span_id')}export function getRecordingStatus(properties: ErrorEventProperties): string | undefined {diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsxindex 55f6c2663015..5b9dfcf776a5 100644--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx@@ -701,6 +701,8 @@ function headerActionParameters(): Record<string, unknown> {//////////////////// Logs tabconst LOGS_STORY_SESSION_ID = 'session-with-logs'+const LOGS_STORY_TRACE_ID = 'story-trace'+const LOGS_STORY_SPAN_ID = 'story-span-4'function buildStoryLogs(event: ErrorEventType): LogMessage[] {const center = new Date(event.timestamp).getTime()@@ -718,7 +720,7 @@ function buildStoryLogs(event: ErrorEventType): LogMessage[] {return lines.map(({ offsetMs, level, body }, index) => ({uuid: `story-log-${index}`,- trace_id: 'story-trace',+ trace_id: LOGS_STORY_TRACE_ID,span_id: `story-span-${index}`,resource_attributes: { 'service.name': 'posthog-web' },attributes: { sessionId: LOGS_STORY_SESSION_ID },@@ -764,12 +766,17 @@ function logsTabParameters(event: ErrorEventType): Record<string, unknown> {function logsStory(issueId: string,- sessionId: string | null+ { sessionId, spanId, traceId }: { sessionId: string | null; spanId?: string; traceId?: string }): {(): JSX.Elementparameters: Record<string, unknown>} {const event = buildSessionTimelineEvent(undefined, { sessionId })+ event.properties = {+ ...event.properties,+ ...(traceId ? { $trace_id: traceId } : {}),+ ...(spanId ? { $span_id: spanId } : {}),+ }const story = (): JSX.Element => (<div className="w-[1000px] h-[700px]">@@ -782,6 +789,19 @@ function logsStory(return story}-export const ExceptionCardLogs = logsStory('issue-id', LOGS_STORY_SESSION_ID)+export const ExceptionCardLogs = logsStory('issue-id', {+ sessionId: LOGS_STORY_SESSION_ID,+ traceId: LOGS_STORY_TRACE_ID,+ spanId: LOGS_STORY_SPAN_ID,+})++export const ExceptionCardLogsWithTraceOnly = logsStory('issue-trace-only', {+ sessionId: null,+ traceId: LOGS_STORY_TRACE_ID,+})++export const ExceptionCardLogsWithSessionOnly = logsStory('issue-session-only', {+ sessionId: LOGS_STORY_SESSION_ID,+})-export const ExceptionCardLogsWithoutSession = logsStory('issue-no-session', null)+export const ExceptionCardLogsWithoutSession = logsStory('issue-no-session', { sessionId: null })diff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsx b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsxindex fbc1b2f043c1..aade52c61b67 100644--- a/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsx@@ -1,7 +1,7 @@import { useActions, useValues } from 'kea'-import { useMemo } from 'react'+import { useEffect, useMemo } from 'react'-import { LemonSegmentedButton, Link } from '@posthog/lemon-ui'+import { LemonSelect, Link } from '@posthog/lemon-ui'import { errorPropertiesLogic } from 'lib/components/Errors/errorPropertiesLogic'import { TabsContent } from 'lib/ui/quill'@@ -9,9 +9,21 @@ import { TabsContent } from 'lib/ui/quill'import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'import { EXCEPTION_LOGS_WINDOW_MINUTES, buildLogsSessionScope } from 'products/logs/frontend/utils'-import { exceptionCardLogic } from '../../exceptionCardLogic'+import { exceptionCardLogic, type ExceptionLogsScope } from '../../exceptionCardLogic'import { SubHeader } from '../SubHeader'import { TabSpinner } from '../TabSpinner'+import {+ buildExceptionLogPinnedFilters,+ getAvailableExceptionLogScopes,+ getEffectiveExceptionLogScope,+} from './logScope'++const LOG_SCOPE_LABELS: Record<ExceptionLogsScope, string> = {+ trace: 'Whole trace',+ span: 'This span',+ session: 'This session',+ window: 'All logs',+}export interface LogsTabProps {timestamp?: string@@ -20,7 +32,7 @@ export interface LogsTabProps {export function LogsTab({ timestamp }: LogsTabProps): JSX.Element {const { loading, issueId, logsScope } = useValues(exceptionCardLogic)const { setLogsScope } = useActions(exceptionCardLogic)- const { sessionId } = useValues(errorPropertiesLogic)+ const { sessionId, spanId, traceId } = useValues(errorPropertiesLogic)// logsViewerFiltersLogic re-applies `initialFilters` whenever the object identity changes, which// resets the date range the user set, so the window depends on the occurrence and not the scope.@@ -28,7 +40,25 @@ export function LogsTab({ timestamp }: LogsTabProps): JSX.Element {() => buildLogsSessionScope(undefined, timestamp, EXCEPTION_LOGS_WINDOW_MINUTES),[timestamp])- const scopedSessionId = sessionId && logsScope === 'session' ? sessionId : undefined+ const { availableScopes, effectiveScope, pinnedFilters } = useMemo(() => {+ const correlationIds = { sessionId, spanId, traceId }+ const nextAvailableScopes = getAvailableExceptionLogScopes(correlationIds)+ const nextEffectiveScope = getEffectiveExceptionLogScope(logsScope, nextAvailableScopes)++ return {+ availableScopes: nextAvailableScopes,+ effectiveScope: nextEffectiveScope,+ pinnedFilters: buildExceptionLogPinnedFilters(nextEffectiveScope, correlationIds),+ }+ }, [logsScope, sessionId, spanId, traceId])+ const scopedSessionId = effectiveScope === 'session' ? sessionId : undefined+ const hasCorrelationScope = availableScopes.length > 1++ useEffect(() => {+ if (!loading && logsScope !== effectiveScope) {+ setLogsScope(effectiveScope)+ }+ }, [effectiveScope, loading, logsScope, setLogsScope])return (<TabsContent value="logs" className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">@@ -37,13 +67,13 @@ export function LogsTab({ timestamp }: LogsTabProps): JSX.Element {) : (<>{/* The caption wraps rather than truncates, because truncating it in a narrow- pane cuts off the docs link the no-session case depends on. */}+ pane cuts off the docs link the no-correlation case depends on. */}<SubHeader className="h-auto min-h-9 justify-between gap-2 py-1"><span className="min-w-0 text-xs text-secondary">Logs from {EXCEPTION_LOGS_WINDOW_MINUTES} minutes before and after this exception.{' '}- {!sessionId && (+ {!hasCorrelationScope && (<>- This exception has no session ID, so these are all logs in that window.{' '}+ This exception has no trace or session ID, so these are all logs in that window.{' '}<Linkto="https://posthog.com/docs/logs/link-session-replay"target="_blank"@@ -54,24 +84,20 @@ export function LogsTab({ timestamp }: LogsTabProps): JSX.Element {</>)}</span>- {sessionId && (- <LemonSegmentedButton+ {hasCorrelationScope && (+ <LemonSelect<ExceptionLogsScope>+ aria-label="Log scope"size="xsmall"- value={logsScope}+ value={effectiveScope}onChange={setLogsScope}- options={[- {- value: 'session',- label: 'This session',- 'data-attr': 'error-tracking-logs-scope-session',- },- {- value: 'window',- label: 'All logs',- 'data-attr': 'error-tracking-logs-scope-window',- },- ]}+ options={availableScopes.map((scope) => ({+ value: scope,+ label: LOG_SCOPE_LABELS[scope],+ 'data-attr': `error-tracking-logs-scope-${scope}`,+ }))}+ data-attr="error-tracking-logs-scope"className="shrink-0"+ dropdownPlacement="bottom-end"/>)}</SubHeader>@@ -80,6 +106,7 @@ export function LogsTab({ timestamp }: LogsTabProps): JSX.Element {<LogsViewerid={`error-tracking-issue-${issueId}`}sessionId={scopedSessionId}+ pinnedFilters={pinnedFilters}initialFilters={initialFilters}showFullScreenButton={false}defaultFacetRailCollapseddiff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/logScope.test.ts b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/logScope.test.tsnew file mode 100644index 000000000000..17cbc3a8561d--- /dev/null+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/logScope.test.ts@@ -0,0 +1,65 @@+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'++import type { ExceptionLogsScope } from '../../exceptionCardLogic'+import {+ buildExceptionLogPinnedFilters,+ getAvailableExceptionLogScopes,+ getEffectiveExceptionLogScope,+} from './logScope'++const ids = { traceId: 'trace-abc', spanId: 'span-xyz', sessionId: 'session-123' }++describe('exception log scope', () => {+ it.each([+ [ids, ['trace', 'span', 'session', 'window']],+ [{ sessionId: ids.sessionId }, ['session', 'window']],+ [{ spanId: ids.spanId }, ['window']],+ ] as const)('offers only the correlation scopes supported by %o', (correlationIds, expectedScopes) => {+ expect(getAvailableExceptionLogScopes(correlationIds)).toEqual(expectedScopes)+ })++ it.each<[string, ExceptionLogsScope, Partial<typeof ids>, ExceptionLogsScope]>([+ ['keeps an available selection', 'span', ids, 'span'],+ ['defaults to the trace', 'span', { traceId: ids.traceId, sessionId: ids.sessionId }, 'trace'],+ ['falls back to the session', 'trace', { sessionId: ids.sessionId }, 'session'],+ ['falls back to the time window', 'trace', {}, 'window'],+ ])('%s', (_label, selectedScope, correlationIds, expectedScope) => {+ const availableScopes = getAvailableExceptionLogScopes(correlationIds)++ expect(getEffectiveExceptionLogScope(selectedScope, availableScopes)).toBe(expectedScope)+ })++ it('pins a trace scope to the native trace ID column', () => {+ expect(buildExceptionLogPinnedFilters('trace', ids)).toEqual({+ type: FilterLogicalOperator.And,+ values: [+ {+ key: 'trace_id',+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: ['trace-abc'],+ },+ ],+ })+ })++ it('pins a span scope to both the trace and span ID columns', () => {+ expect(buildExceptionLogPinnedFilters('span', ids)).toEqual({+ type: FilterLogicalOperator.And,+ values: [+ {+ key: 'trace_id',+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: ['trace-abc'],+ },+ {+ key: 'span_id',+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: ['span-xyz'],+ },+ ],+ })+ })+})diff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/logScope.ts b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/logScope.tsnew file mode 100644index 000000000000..587b0d5b91e8--- /dev/null+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/logScope.ts@@ -0,0 +1,71 @@+import {+ FilterLogicalOperator,+ type LogPropertyFilter,+ PropertyFilterType,+ PropertyOperator,+ type UniversalFiltersGroup,+} from '~/types'++import type { ExceptionLogsScope } from '../../exceptionCardLogic'++export interface ExceptionLogCorrelationIds {+ sessionId?: string+ spanId?: string+ traceId?: string+}++function logIdFilter(key: 'span_id' | 'trace_id', value: string): LogPropertyFilter {+ return {+ key,+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: [value],+ } as LogPropertyFilter+}++export function getAvailableExceptionLogScopes({+ sessionId,+ spanId,+ traceId,+}: ExceptionLogCorrelationIds): ExceptionLogsScope[] {+ const scopes: ExceptionLogsScope[] = []+ if (traceId) {+ scopes.push('trace')+ }+ if (traceId && spanId) {+ scopes.push('span')+ }+ if (sessionId) {+ scopes.push('session')+ }+ scopes.push('window')+ return scopes+}++export function getEffectiveExceptionLogScope(+ selectedScope: ExceptionLogsScope,+ availableScopes: ExceptionLogsScope[]+): ExceptionLogsScope {+ return availableScopes.includes(selectedScope) ? selectedScope : (availableScopes[0] ?? 'window')+}++export function buildExceptionLogPinnedFilters(+ scope: ExceptionLogsScope,+ { spanId, traceId }: ExceptionLogCorrelationIds+): UniversalFiltersGroup | undefined {+ if (scope === 'trace' && traceId) {+ return {+ type: FilterLogicalOperator.And,+ values: [logIdFilter('trace_id', traceId)],+ }+ }++ if (scope === 'span' && traceId && spanId) {+ return {+ type: FilterLogicalOperator.And,+ values: [logIdFilter('trace_id', traceId), logIdFilter('span_id', spanId)],+ }+ }++ return undefined+}diff --git a/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.ts b/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.tsindex c8f10d7a2a82..e75694a4efc6 100644--- a/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.ts+++ b/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.ts@@ -9,7 +9,7 @@ export type ExceptionCardLogicProps = {export type ExceptionCardTab = 'stack_trace' | 'properties' | 'timeline' | 'recording' | 'logs'-export type ExceptionLogsScope = 'session' | 'window'+export type ExceptionLogsScope = 'trace' | 'span' | 'session' | 'window'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface exceptionCardLogicValues {@@ -112,7 +112,7 @@ export const exceptionCardLogic = kea<exceptionCardLogicType>([},],logsScope: [- 'session' as ExceptionLogsScope,+ 'trace' as ExceptionLogsScope,{setLogsScope: (_, { scope }) => scope,},diff --git a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsx b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsxindex 39f0aee341ab..7e36b2197b54 100644--- a/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsx+++ b/products/logs/frontend/components/LogsViewer/Filters/LogsFilterBar/LogsQueryBar.tsx@@ -28,7 +28,7 @@ export const LogsQueryBar = ({return (<LogsFilterGroup>- <div className="flex flex-col gap-2 w-full bg-primary">+ <div className="flex flex-col gap-2 w-full"><div className="flex gap-2 flex-wrap w-full justify-between"><div className="flex shrink-0 flex-1 gap-1.5"><div className="flex-1 min-w-[300px]">