: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(tracing): correlate logs in the span inspector (#63016)
Jon McCallum7ae8904b5562
diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsxindex 9777c49d3f5c..a99ddf8b7453 100644--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx@@ -35,6 +35,9 @@ export interface LogsViewerProps {// Filters enforced by the embedding scene. Merged into the user-editable filterGroup// and rendered without an X so users can't accidentally drop the scope.pinnedFilters?: UniversalFiltersGroup+ // Hide the filter bar (levels/services/search/date range) entirely. For embeds where the+ // scope is fixed by `pinnedFilters` and editing filters in place isn't wanted. @default true+ showFilterBar?: boolean}export function LogsViewer({@@ -43,6 +46,7 @@ export function LogsViewer({showSavedViewsButton = false,initialFilters,pinnedFilters,+ showFilterBar = true,}: LogsViewerProps): JSX.Element {return (<BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters }}>@@ -55,6 +59,7 @@ export function LogsViewer({<LogsViewerContentshowFullScreenButton={showFullScreenButton}showSavedViewsButton={showSavedViewsButton}+ showFilterBar={showFilterBar}/></BindLogic></BindLogic>@@ -69,9 +74,11 @@ export function LogsViewer({function LogsViewerContent({showFullScreenButton,showSavedViewsButton,+ showFilterBar,}: {showFullScreenButton: booleanshowSavedViewsButton: boolean+ showFilterBar: boolean}): JSX.Element {const {id,@@ -283,7 +290,7 @@ function LogsViewerContent({onToggleCollapse={toggleSparklineCollapsed}/><SceneDivider />- <LogsFilterBar showSavedViewsButton={showSavedViewsButton} />+ {showFilterBar && <LogsFilterBar showSavedViewsButton={showSavedViewsButton} />}<LogsViewerToolbartotalLogsCount={sparklineLoading ? undefined : totalLogsMatchingFilters}orderBy={orderBy}diff --git a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsx b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsxnew file mode 100644index 000000000000..f3e8289d748e--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.test.tsx@@ -0,0 +1,40 @@+import { render } from '@testing-library/react'++import type { Span } from '../../types'+import { SpanLogsTab } from './SpanLogsTab'++// Capture the props the embedded LogsViewer receives. The logsViewerFiltersLogic compares+// `initialFilters` by IDENTITY (propsChanged uses `!==`), so a fresh object each render re-applies+// setFilters → re-query. A drawer resize re-renders this component on every mousemove, so the prop+// objects must be referentially stable across re-renders with the same span.+const capturedProps: { pinnedFilters: unknown; initialFilters: unknown }[] = []+jest.mock('products/logs/frontend/components/LogsViewer/LogsViewer', () => ({+ LogsViewer: (props: { pinnedFilters: unknown; initialFilters: unknown }) => {+ capturedProps.push({ pinnedFilters: props.pinnedFilters, initialFilters: props.initialFilters })+ return null+ },+}))++const span = {+ trace_id: 'trace-abc',+ span_id: 'span-xyz',+ timestamp: '2026-06-11T08:00:00.000Z',+} as Span++describe('SpanLogsTab', () => {+ beforeEach(() => {+ capturedProps.length = 0+ })++ it('passes referentially stable pinnedFilters/initialFilters across re-renders (no re-query on resize)', () => {+ const { rerender } = render(<SpanLogsTab span={span} />)+ const first = capturedProps[capturedProps.length - 1]++ // Re-render with the same span (mirrors a parent re-render from a resize drag).+ rerender(<SpanLogsTab span={span} />)+ const second = capturedProps[capturedProps.length - 1]++ expect(second.pinnedFilters).toBe(first.pinnedFilters)+ expect(second.initialFilters).toBe(first.initialFilters)+ })+})diff --git a/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsxnew file mode 100644index 000000000000..b035b088d1ad--- /dev/null+++ b/products/tracing/frontend/components/TraceDrawer/SpanLogsTab.tsx@@ -0,0 +1,80 @@+import { useMemo, useState } from 'react'++import { IconExternal } from '@posthog/icons'+import { LemonButton, LemonSegmentedButton } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'++import { traceLookupDateRange } from '../../traceLinks'+import { buildLogScopeFilter, logsDeepLinkUrl, type TraceLogScope } from '../../traceLogScope'+import type { Span } from '../../types'++// Logs correlated to the inspected span (default) or the whole trace, via the embedded LogsViewer+// pinned to a trace_id/span_id filter. Span scope keeps the tab coherent with the rest of the+// inspector; the toggle rescues the common case where a span emitted no logs of its own. The+// viewer's own filter bar is hidden (showFilterBar={false}) — the scope is fixed by the pinned+// filter, and this toggle is the visible scope control.+export function SpanLogsTab({ span }: { span: Span }): JSX.Element {+ const [scope, setScope] = useState<TraceLogScope>('span')++ // `initialFilters` (the date range) is stable across scope changes — recompute only when the+ // span timestamp changes. Otherwise a scope toggle would mint a fresh `initialFilters` object;+ // logsViewerFiltersLogic compares it by identity and would call setFilters, resetting the date+ // range and discarding any sparkline zoom the user applied. (Memoizing also keeps resize-drag+ // re-renders from handing the viewer fresh objects and re-querying every frame.)+ const { dateRange, initialFilters } = useMemo(() => {+ const dateRange = dayjs(span.timestamp).isValid() ? traceLookupDateRange(span.timestamp) : { date_from: '-24h' }+ return { dateRange, initialFilters: { dateRange } }+ }, [span.timestamp])++ // Scope-sensitive values recompute when scope or the span identity changes.+ const ids = useMemo(() => ({ traceId: span.trace_id, spanId: span.span_id }), [span.trace_id, span.span_id])+ const { pinnedFilters, deepLink } = useMemo(+ () => ({+ pinnedFilters: buildLogScopeFilter(scope, ids),+ deepLink: logsDeepLinkUrl(scope, ids, dateRange),+ }),+ [scope, ids, dateRange]+ )++ return (+ <div className="flex flex-col gap-2 h-[60vh] min-h-80">+ <div className="flex items-center justify-between gap-2">+ <LemonSegmentedButton+ size="xsmall"+ value={scope}+ onChange={setScope}+ options={[+ { value: 'span', label: 'This span' },+ { value: 'trace', label: 'Whole trace' },+ ]}+ data-attr="tracing-logs-scope"+ />+ <LemonButton+ size="xsmall"+ type="secondary"+ icon={<IconExternal />}+ to={deepLink}+ data-attr="tracing-logs-open-in-logs"+ >+ Open in Logs+ </LemonButton>+ </div>+ {/* Keyed by trace so it's one instance per trace; flipping scope or selecting another+ span changes pinnedFilters and re-queries in place. */}+ <LogsViewer+ id={`tracing-logs-${span.trace_id}`}+ pinnedFilters={pinnedFilters}+ initialFilters={initialFilters}+ showFilterBar={false}+ // Full-screen is off (like PersonLogsTab): the shared modal can't carry pinnedFilters,+ // so it would open unscoped and clear this viewer's scope. "Open in Logs" preserves+ // the scope via the URL filterGroup instead.+ showFullScreenButton={false}+ showSavedViewsButton={false}+ />+ </div>+ )+}diff --git a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsxindex f3ce2b03f3eb..5b47d6fcbce1 100644--- a/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx+++ b/products/tracing/frontend/components/TraceDrawer/TraceDrawer.tsx@@ -1,7 +1,7 @@import { useValues } from 'kea'-import { useMemo, useRef } from 'react'+import { useMemo, useRef, useState } from 'react'-import { LemonButton, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'+import { LemonButton, LemonTabs, LemonTag, SpinnerOverlay } from '@posthog/lemon-ui'import { Resizer } from 'lib/components/Resizer/Resizer'import { type ResizerLogicProps, resizerLogic } from 'lib/components/Resizer/resizerLogic'@@ -15,6 +15,9 @@ import { absoluteTraceUrl } from '../../traceLinks'import { formatDuration, TraceWaterfallView } from '../../TraceWaterfallView'import type { Span } from '../../types'import { ExpandedSpanContent } from '../VirtualizedSpanList/ExpandedSpanContent'+import { SpanLogsTab } from './SpanLogsTab'++type InspectorTab = 'attributes' | 'logs'// Below this the inspector's content (the attribute KVP tables) stops being readable; clamp so a// drag can't crush it. The max is a flex `max-w` so a too-wide drag can't starve the waterfall.@@ -33,9 +36,9 @@ export interface TraceDrawerProps {}// Master-detail split: waterfall on the left drives the span inspector on the right — the same-// list→detail relationship the span list has with this drawer, one level down. Tabs were-// deliberately rejected: they'd hide the waterfall while reading a span's attributes, breaking-// the click-through-spans-and-compare loop.+// list→detail relationship the span list has with this drawer, one level down. Tabs live *inside*+// the inspector (Attributes / Logs), not at the drawer level — so the waterfall stays visible while+// you read a span's attributes or its correlated logs.export function TraceDrawer({isOpen,traceId,@@ -57,6 +60,7 @@ export function TraceDrawer({persistent: true,}const { desiredSize: inspectorWidth } = useValues(resizerLogic(inspectorResizerProps))+ const [inspectorTab, setInspectorTab] = useState<InspectorTab>('attributes')// Resolve the inspected span outside render churn: a resize drag re-renders this component on// every mousemove, and these scans are O(spans) — memoize so they only run when data/selection change.@@ -128,7 +132,26 @@ export function TraceDrawer({><Resizer {...inspectorResizerProps} />{inspectedSpan ? (- <ExpandedSpanContent span={inspectedSpan} />+ <LemonTabs+ activeKey={inspectorTab}+ onChange={setInspectorTab}+ data-attr="tracing-inspector-tabs"+ tabs={[+ {+ key: 'attributes',+ label: 'Attributes',+ content: <ExpandedSpanContent span={inspectedSpan} />,+ },+ {+ key: 'logs',+ label: 'Logs',+ // Not keyed by span: the embedded viewer (keyed by trace_id) and the memoized+ // pinned filter re-query in place when the selected span changes, so a remount+ // would only churn its logics and lose scroll.+ content: <SpanLogsTab span={inspectedSpan} />,+ },+ ]}+ />) : (<div className="text-muted p-4">No spans in this trace</div>)}diff --git a/products/tracing/frontend/traceLogScope.test.ts b/products/tracing/frontend/traceLogScope.test.tsnew file mode 100644index 000000000000..347b5e392242--- /dev/null+++ b/products/tracing/frontend/traceLogScope.test.ts@@ -0,0 +1,42 @@+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'++import { buildLogScopeFilter, logsDeepLinkUrl, type TraceLogScope } from './traceLogScope'++const ids = { traceId: 'trace-abc', spanId: 'span-xyz' }+const dateRange = { date_from: '2026-06-11T07:00:00.000Z', date_to: '2026-06-11T09:00:00.000Z' }++describe('traceLogScope', () => {+ it.each<[TraceLogScope, string, string]>([+ ['span', 'span_id', 'span-xyz'],+ ['trace', 'trace_id', 'trace-abc'],+ ])('pins the embedded viewer for scope=%s to %s=%s', (scope, key, value) => {+ expect(buildLogScopeFilter(scope, ids)).toEqual({+ type: FilterLogicalOperator.And,+ values: [{ key, type: PropertyFilterType.Log, operator: PropertyOperator.Exact, value: [value] }],+ })+ })++ it('builds a Logs deep link with a two-level filter group and the time window', () => {+ const url = logsDeepLinkUrl('trace', ids, dateRange)+ expect(url.startsWith('/logs?')).toBe(true)++ const params = new URLSearchParams(url.slice(url.indexOf('?') + 1))+ expect(JSON.parse(params.get('filterGroup')!)).toEqual({+ type: 'AND',+ values: [+ {+ type: 'AND',+ values: [+ {+ key: 'trace_id',+ type: 'log',+ operator: 'exact',+ value: ['trace-abc'],+ },+ ],+ },+ ],+ })+ expect(JSON.parse(params.get('dateRange')!)).toEqual(dateRange)+ })+})diff --git a/products/tracing/frontend/traceLogScope.ts b/products/tracing/frontend/traceLogScope.tsnew file mode 100644index 000000000000..9131dfdeefe9--- /dev/null+++ b/products/tracing/frontend/traceLogScope.ts@@ -0,0 +1,56 @@+// Correlate logs to a trace/span (JON-30). OTel logs carry native `trace_id`/`span_id` columns+// (products/logs/backend/schema.sql), so scoping the embedded LogsViewer to a span or the whole+// trace is just a `trace_id`/`span_id` equality filter — no tracing-side backend needed.++import { urls } from 'scenes/urls'++import type { DateRange } from '~/queries/schema/schema-general'+import { FilterLogicalOperator, type LogPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'+import type { UniversalFiltersGroup } from '~/types'++export type TraceLogScope = 'span' | 'trace'++export interface TraceSpanIds {+ traceId: string+ spanId: string+}++function scopeFilter(scope: TraceLogScope, { traceId, spanId }: TraceSpanIds): LogPropertyFilter {+ // trace_id/span_id are native log columns; the logs query runner accepts hex and converts to+ // the stored base64 form, so we pass the hex ids the trace UI already has.+ return {+ key: scope === 'span' ? 'span_id' : 'trace_id',+ type: PropertyFilterType.Log,+ operator: PropertyOperator.Exact,+ value: [scope === 'span' ? spanId : traceId],+ } as LogPropertyFilter+}++/**+ * Read-only `pinnedFilters` for the embedded LogsViewer — locks it to this span's (or trace's)+ * logs. Single-level group shape, matching how PersonLogsTab pins its scope.+ */+export function buildLogScopeFilter(scope: TraceLogScope, ids: TraceSpanIds): UniversalFiltersGroup {+ return {+ type: FilterLogicalOperator.And,+ values: [scopeFilter(scope, ids)],+ }+}++/**+ * Deep link into the full Logs product, pre-scoped to this span/trace and time window. Two-level+ * group + JSON-encoded params, matching the format the logs scene's urlToAction decodes (see+ * ItemLog's logs link).+ */+export function logsDeepLinkUrl(scope: TraceLogScope, ids: TraceSpanIds, dateRange: DateRange): string {+ // The logs scene decodes an outer group of inner groups, so wrap the pinned group one level.+ const filterGroup = {+ type: FilterLogicalOperator.And,+ values: [buildLogScopeFilter(scope, ids)],+ }+ const params = new URLSearchParams({+ filterGroup: JSON.stringify(filterGroup),+ dateRange: JSON.stringify(dateRange),+ })+ return `${urls.logs()}?${params.toString()}`+}