: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): add a surrounding logs tab to the exception card (#101334)
Jimmy Zhu1fcbc5c6843e
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 6dd10713fd4b..3ae52a56ad3d 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -2424,6 +2424,14 @@ snapshots:hash: v1.k794b7964.b80263f67c0d7d1e25bc2a91d738d80474ce40c97df64d2636bcc6a5dfa38e97.1uYHWbCS1ez7dIDtoz0c3GGZhBI3vHTN-1zaky50yqIerrortracking-exceptioncard--exception-card-header-widths-with-action--light:hash: v1.k794b7964.25974971fa0cf2dbe86348ce1144e8b8a0ff7c1a7e172ecc941e6b345144841f.dT_74I4ZqX-DFX_ayPWR8lutK4EVque9Zyjbci6Hj6I+ errortracking-exceptioncard--exception-card-logs--dark:+ hash: v1.k794b7964.1030bfe45ba31d3fe94873ce09cdaeda8f81e86c0f71072d64a6267c551c6242.0pD2zOgFDmK5w5r-MnEbEzSAtOGpgYFKzEI8oJ8gUcs+ errortracking-exceptioncard--exception-card-logs--light:+ hash: v1.k794b7964.c691f17c502c069287778c899ef298787ba804c2a2ce40f47e2ce7fffdcac348.SwdlNY656OF7LWj_IFuHcynkhxd0_yhTkfFFwRPO3gU+ errortracking-exceptioncard--exception-card-logs-without-session--dark:+ hash: v1.k794b7964.1c55aa5eb5758c9f5710a62fe92cccab572ef04501b69d7981a7e0964d6b09e3.59UJwC1G6msLdy-Nn_qOGijQsWoReclGYPWDGeM3kto+ errortracking-exceptioncard--exception-card-logs-without-session--light:+ hash: v1.k794b7964.036417710485b035128e3d9334c9ab22ea6c216c567ece5a1668af80de4e16ca.A9auY_Pt1XV2Gixl_rwuvhkMLFZFPlW5S0szuhtkHWQerrortracking-exceptioncard--exception-card-no-in-app--dark:hash: v1.k794b7964.0202a7987400a0f205709db94774e344cc90886efcc2e12d09f425567839d332.CXArdJgM3wO67eOHuvDr_4AFqGTOpB566tgl0bYYkFoerrortracking-exceptioncard--exception-card-no-in-app--light:diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsxindex 33548798bcb6..55f6c2663015 100644--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx@@ -9,14 +9,14 @@ import { FEATURE_FLAGS } from 'lib/constants'import { mswDecorator } from '~/mocks/browser'import type { Mocks } from '~/mocks/utils'-import { NodeKind } from '~/queries/schema/schema-general'+import { LogMessage, LogSeverityLevel, NodeKind } from '~/queries/schema/schema-general'import { TEST_EVENTS } from '../../__mocks__/events'import { results as batchGetResults } from '../../__mocks__/stack_frames/batch_get'import { ExceptionTag } from '../../hooks/use-error-tag-renderer'import { StyleVariables } from '../StyleVariables'import { ExceptionCard } from './ExceptionCard'-import { exceptionCardLogic } from './exceptionCardLogic'+import { ExceptionCardTab, exceptionCardLogic } from './exceptionCardLogic'const meta: Meta = {title: 'ErrorTracking/ExceptionCard',@@ -51,14 +51,14 @@ export function ExceptionCardBase(): JSX.Element {return (<div className="w-[1000px] h-[700px]"><BindLogic logic={exceptionCardLogic} props={{ issueId: 'issue-id', loading: false }}>- <OpenTimelineTab>+ <OpenTab tab="timeline"><ExceptionCardissueId="issue-id"issueName="Test Issue"loading={false}event={TEST_EVENTS['javascript_resolved'] as any}/>- </OpenTimelineTab>+ </OpenTab></BindLogic></div>)@@ -240,9 +240,9 @@ function ExceptionCardSessionTimelineStory({return (<div className={containerClassName}><BindLogic logic={exceptionCardLogic} props={{ issueId: 'issue-id', loading: false }}>- <OpenTimelineTab>+ <OpenTab tab="timeline"><ExceptionCard issueId="issue-id" issueName="Test Issue" loading={false} event={event} />- </OpenTimelineTab>+ </OpenTab></BindLogic></div>)@@ -553,12 +553,20 @@ function buildSessionTimelineEvent(}}-function OpenTimelineTab({ children, issueId = 'issue-id' }: { children: JSX.Element; issueId?: string }): JSX.Element {+function OpenTab({+ tab,+ children,+ issueId = 'issue-id',+}: {+ tab: ExceptionCardTab+ children: JSX.Element+ issueId?: string+}): JSX.Element {const { setCurrentTab } = useActions(exceptionCardLogic({ issueId, loading: false }))useEffect(() => {- setCurrentTab('timeline')- }, [setCurrentTab])+ setCurrentTab(tab)+ }, [setCurrentTab, tab])return children}@@ -652,14 +660,14 @@ export function ExceptionCardHeaderWidthsWithAction(): JSX.Element {return (<HeaderWidthMatrix widths={HEADER_WIDTHS.filter(({ width }) => width <= 576)}>{(width) => (- <OpenTimelineTab issueId={`header-action-${width}`}>+ <OpenTab tab="timeline" issueId={`header-action-${width}`}><ExceptionCardissueId={`header-action-${width}`}issueName="Test Issue"loading={false}event={event}/>- </OpenTimelineTab>+ </OpenTab>)}</HeaderWidthMatrix>)@@ -689,3 +697,91 @@ function headerActionParameters(): Record<string, unknown> {},}}++//////////////////// Logs tab++const LOGS_STORY_SESSION_ID = 'session-with-logs'++function buildStoryLogs(event: ErrorEventType): LogMessage[] {+ const center = new Date(event.timestamp).getTime()+ const at = (deltaMs: number): string => new Date(center + deltaMs).toISOString()++ const lines: { offsetMs: number; level: LogSeverityLevel; body: string }[] = [+ { offsetMs: -42000, level: 'info', body: 'GET /api/projects/7/dashboards 200 in 84ms' },+ { offsetMs: -21000, level: 'info', body: 'Loaded dashboard config for project 7' },+ { offsetMs: -4200, level: 'warn', body: 'Config request took 2841ms, above the 2000ms budget' },+ { offsetMs: -900, level: 'error', body: 'GET /api/projects/7/config 502 Bad Gateway' },+ { offsetMs: 0, level: 'error', body: 'Uncaught TypeError: cannot read properties of undefined' },+ { offsetMs: 3100, level: 'info', body: 'Retrying config request (attempt 1 of 3)' },+ { offsetMs: 9400, level: 'info', body: 'GET /api/projects/7/config 200 in 131ms' },+ ]++ return lines.map(({ offsetMs, level, body }, index) => ({+ uuid: `story-log-${index}`,+ trace_id: 'story-trace',+ span_id: `story-span-${index}`,+ resource_attributes: { 'service.name': 'posthog-web' },+ attributes: { sessionId: LOGS_STORY_SESSION_ID },+ body,+ timestamp: at(offsetMs),+ observed_timestamp: at(offsetMs),+ severity_text: level,+ severity_number: 13,+ level,+ instrumentation_scope: 'any',+ event_name: 'any',+ }))+}++function logsTabParameters(event: ErrorEventType): Record<string, unknown> {+ const logs = buildStoryLogs(event)++ return {+ featureFlags: [FEATURE_FLAGS.LOGS_IN_ERROR_TRACKING],+ msw: {+ mocks: {+ get: {+ 'api/projects/:team_id/logs_config/': {+ logs_distinct_id_attribute_key: 'posthogDistinctId',+ logs_distinct_id_attribute_keys: ['posthogDistinctId'],+ logs_session_id_attribute_keys: ['sessionId'],+ },+ },+ post: {+ '/api/environments/:team_id/logs/query': { results: logs, maxExportableLogs: 5000 },+ '/api/environments/:team_id/logs/sparkline': logs.map((log) => ({+ count: 1,+ level: log.severity_text,+ time: log.timestamp,+ })),+ '/api/projects/:team_id/logs/facet_values': { results: [] },+ '/api/projects/:team_id/logs/services': { results: [], sparkline: [], totalServices: 0 },+ },+ },+ },+ }+}++function logsStory(+ issueId: string,+ sessionId: string | null+): {+ (): JSX.Element+ parameters: Record<string, unknown>+} {+ const event = buildSessionTimelineEvent(undefined, { sessionId })++ const story = (): JSX.Element => (+ <div className="w-[1000px] h-[700px]">+ <OpenTab tab="logs" issueId={issueId}>+ <ExceptionCard issueId={issueId} issueName="Test Issue" loading={false} event={event} />+ </OpenTab>+ </div>+ )+ story.parameters = logsTabParameters(event)+ return story+}++export const ExceptionCardLogs = logsStory('issue-id', LOGS_STORY_SESSION_ID)++export const ExceptionCardLogsWithoutSession = logsStory('issue-no-session', null)diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsxindex a235721fb549..cca6d1fc74a2 100644--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.tsx@@ -7,12 +7,14 @@ import { LemonCard } from '@posthog/lemon-ui'import { ErrorPropertiesLogicProps, errorPropertiesLogic } from 'lib/components/Errors/errorPropertiesLogic'import { ErrorEventType } from 'lib/components/Errors/types'import type { TimelineMarkerColor } from 'lib/components/SessionTimeline/SessionTimeline'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { Tabs, TabsList, TabsTrigger } from 'lib/ui/quill'import { ViewLogsButton } from 'products/logs/frontend/components/ViewLogsButton'import { ExceptionCardFooter } from './ExceptionCardFooter'import { exceptionCardLogic } from './exceptionCardLogic'+import { LogsTab } from './Tabs/LogsTab/LogsTab'import { PropertiesTab } from './Tabs/PropertiesTab'import { SessionTab } from './Tabs/SessionTab'import { StackTraceTab } from './Tabs/StackTraceTab'@@ -78,6 +80,7 @@ function ExceptionCardContent({const { currentTab } = useValues(exceptionCardLogic)const { sessionId } = useValues(errorPropertiesLogic)const { setCurrentTab } = useActions(exceptionCardLogic)+ const logsEnabled = useFeatureFlag('LOGS_IN_ERROR_TRACKING')const headerRef = useRef<HTMLDivElement>(null)// Base UI scrolls the active tab into view on mount and on keyboard navigation, but not when the@@ -108,7 +111,8 @@ function ExceptionCardContent({value === 'stack_trace' ||value === 'properties' ||value === 'timeline' ||- value === 'recording'+ value === 'recording' ||+ value === 'logs') {setCurrentTab(value)}@@ -168,6 +172,15 @@ function ExceptionCardContent({>Recording</TabsTrigger>+ {logsEnabled && (+ <TabsTrigger+ value="logs"+ className="text-sm"+ style={{ '--background': 'transparent' } as CSSProperties}+ >+ Logs+ </TabsTrigger>+ )}</TabsList><div className="flex justify-end">{sessionId && (currentTab === 'timeline' || currentTab === 'recording') ? (@@ -184,6 +197,7 @@ function ExceptionCardContent({<StackTraceTab value="stack_trace" renderActions={renderStackTraceActions} className="flex-1 min-h-0" /><PropertiesTab value="properties" className="flex-1 min-h-0" /><SessionTab timestamp={timestamp} eventMarkerColor={eventMarkerColor} />+ {logsEnabled && <LogsTab timestamp={timestamp} />}<ExceptionCardFooter eventId={eventId} fingerprint={fingerprint} label={label} timestamp={timestamp} /></Tabs></LemonCard>diff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsx b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsxnew file mode 100644index 000000000000..fbc1b2f043c1--- /dev/null+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/LogsTab/LogsTab.tsx@@ -0,0 +1,93 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonSegmentedButton, Link } from '@posthog/lemon-ui'++import { errorPropertiesLogic } from 'lib/components/Errors/errorPropertiesLogic'+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 { SubHeader } from '../SubHeader'+import { TabSpinner } from '../TabSpinner'++export interface LogsTabProps {+ timestamp?: string+}++export function LogsTab({ timestamp }: LogsTabProps): JSX.Element {+ const { loading, issueId, logsScope } = useValues(exceptionCardLogic)+ const { setLogsScope } = useActions(exceptionCardLogic)+ const { sessionId } = 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.+ const { initialFilters } = useMemo(+ () => buildLogsSessionScope(undefined, timestamp, EXCEPTION_LOGS_WINDOW_MINUTES),+ [timestamp]+ )+ const scopedSessionId = sessionId && logsScope === 'session' ? sessionId : undefined++ return (+ <TabsContent value="logs" className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">+ {loading ? (+ <TabSpinner />+ ) : (+ <>+ {/* The caption wraps rather than truncates, because truncating it in a narrow+ pane cuts off the docs link the no-session 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 && (+ <>+ This exception has no session ID, so these are all logs in that window.{' '}+ <Link+ to="https://posthog.com/docs/logs/link-session-replay"+ target="_blank"+ className="text-xs"+ >+ Link your logs to sessions+ </Link>+ </>+ )}+ </span>+ {sessionId && (+ <LemonSegmentedButton+ size="xsmall"+ value={logsScope}+ 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',+ },+ ]}+ className="shrink-0"+ />+ )}+ </SubHeader>+ <div className="min-h-0 flex-1 overflow-hidden p-2">+ {/* Keyed by issue, so paging through its occurrences keeps the user's filters. */}+ <LogsViewer+ id={`error-tracking-issue-${issueId}`}+ sessionId={scopedSessionId}+ initialFilters={initialFilters}+ showFullScreenButton={false}+ defaultFacetRailCollapsed+ defaultSparklineCollapsed+ />+ </div>+ </>+ )}+ </TabsContent>+ )+}diff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsx b/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsxindex 6505ab098832..0f3366d8fd90 100644--- a/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsx@@ -2,7 +2,7 @@ import { BindLogic, useActions, useValues } from 'kea'import { useCallback, useEffect, useMemo, useRef } from 'react'import { P, match } from 'ts-pattern'-import { LemonBanner, Link, Spinner } from '@posthog/lemon-ui'+import { LemonBanner, Link } from '@posthog/lemon-ui'import { EmptyMessage } from 'lib/components/EmptyMessage/EmptyMessage'import { errorPropertiesLogic } from 'lib/components/Errors/errorPropertiesLogic'@@ -26,6 +26,7 @@ import { Dayjs, dayjs } from 'lib/dayjs'import { TabsContent } from 'lib/ui/quill'import { exceptionCardLogic } from '../../exceptionCardLogic'+import { TabSpinner } from '../TabSpinner'import { SessionRecordingTab } from './SessionRecordingTab'import { sessionTabLogic } from './sessionTabLogic'@@ -42,14 +43,10 @@ export function SessionTab({ timestamp, eventMarkerColor }: SessionTabProps): JS.with([true, P.any], () => (<><TabsContent value="timeline" className="min-h-0 min-w-0 flex-1 overflow-hidden text-sm">- <div className="flex justify-center items-center h-[300px]">- <Spinner />- </div>+ <TabSpinner /></TabsContent><TabsContent value="recording" className="min-h-0 min-w-0 flex-1 overflow-hidden">- <div className="flex justify-center items-center h-[300px]">- <Spinner />- </div>+ <TabSpinner /></TabsContent></>))diff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/TabSpinner.tsx b/products/error_tracking/frontend/components/ExceptionCard/Tabs/TabSpinner.tsxnew file mode 100644index 000000000000..6e444fe18b5a--- /dev/null+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/TabSpinner.tsx@@ -0,0 +1,9 @@+import { Spinner } from '@posthog/lemon-ui'++export function TabSpinner(): JSX.Element {+ return (+ <div className="flex h-[300px] items-center justify-center">+ <Spinner />+ </div>+ )+}diff --git a/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.ts b/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.tsindex b9fffe9afaa2..c8f10d7a2a82 100644--- a/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.ts+++ b/products/error_tracking/frontend/components/ExceptionCard/exceptionCardLogic.ts@@ -7,7 +7,9 @@ export type ExceptionCardLogicProps = {loading: boolean}-export type ExceptionCardTab = 'stack_trace' | 'properties' | 'timeline' | 'recording'+export type ExceptionCardTab = 'stack_trace' | 'properties' | 'timeline' | 'recording' | 'logs'++export type ExceptionLogsScope = 'session' | 'window'// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface exceptionCardLogicValues {@@ -15,6 +17,7 @@ export interface exceptionCardLogicValues {expandedFrameRawIds: Set<string>issueId: stringloading: boolean+ logsScope: ExceptionLogsScopepropertyNameFilter: stringshowJSONProperties: boolean}@@ -31,6 +34,9 @@ export interface exceptionCardLogicActions {expanded: booleanrawId: string}+ setLogsScope: (scope: ExceptionLogsScope) => {+ scope: ExceptionLogsScope+ }setPropertyNameFilter: (propertyNameFilter: string) => {propertyNameFilter: string}@@ -65,6 +71,7 @@ export const exceptionCardLogic = kea<exceptionCardLogicType>([setPropertyNameFilter: (propertyNameFilter: string) => ({ propertyNameFilter }),setCurrentTab: (tab: ExceptionCardTab) => ({ tab }),setFrameExpanded: (rawId: string, expanded: boolean) => ({ rawId, expanded }),+ setLogsScope: (scope: ExceptionLogsScope) => ({ scope }),}),reducers({@@ -104,6 +111,12 @@ export const exceptionCardLogic = kea<exceptionCardLogicType>([setCurrentTab: (_, { tab }) => tab,},],+ logsScope: [+ 'session' as ExceptionLogsScope,+ {+ setLogsScope: (_, { scope }) => scope,+ },+ ],}),selectors({diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.tsindex 4efbf9db5361..6d550a1f7e75 100644--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts@@ -142,10 +142,13 @@ export interface logsViewerFiltersLogicValues {id: stringopenFilterOnInsert: booleanpersonId: string | undefined+ personIdScope: stringpinnedFilters: UniversalFiltersGroup | undefinedqueryFilterGroup: UniversalFiltersGroup+ queryScopeKey: stringsearchTerm: LogsQuery['searchTerm']sessionId: string | undefined+ sessionIdScope: stringutcDateRange: {date_from: string | null | undefineddate_to: string | null | undefined@@ -211,6 +214,9 @@ export interface logsViewerFiltersLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {id: (id: string) => string+ personId: (personIdScope: string) => string | undefined+ queryScopeKey: (personIdScope: string, sessionIdScope: string) => string+ sessionId: (sessionIdScope: string) => string | undefinedfilters: (dateRange: DateRange,searchTerm: string | undefined,@@ -339,22 +345,31 @@ export const logsViewerFiltersLogic = kea<logsViewerFiltersLogicType>([setPinnedFilters: (_, { pinnedFilters }) => pinnedFilters,},],- personId: [- undefined as string | undefined,+ // A kea reducer cannot return undefined, so a cleared scope is held as an empty string and+ // mapped back by the selectors below.+ personIdScope: [+ '',{- setPersonId: (_, { personId }) => personId,+ setPersonId: (_, { personId }) => personId ?? '',},],- sessionId: [- undefined as string | undefined,+ sessionIdScope: [+ '',{- setSessionId: (_, { sessionId }) => sessionId,+ setSessionId: (_, { sessionId }) => sessionId ?? '',},],}),selectors({id: [(_, p) => [p.id], (id: string) => id],+ personId: [(s) => [s.personIdScope], (personIdScope: string): string | undefined => personIdScope || undefined],+ // One value the data logic can subscribe to that changes when either scope does.+ queryScopeKey: [(s) => [s.personIdScope, s.sessionIdScope], (p: string, sid: string) => `${p}|${sid}`],+ sessionId: [+ (s) => [s.sessionIdScope],+ (sessionIdScope: string): string | undefined => sessionIdScope || undefined,+ ],filters: [(s) => [s.dateRange, s.searchTerm, s.filterGroup],(diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsxindex 8fc53f61a2c1..7945822a82a6 100644--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx@@ -48,6 +48,8 @@ export interface LogsViewerProps {// Seed the facet/filter rail as collapsed on first mount for this id. Persisted per id,// so a user who expands it keeps that choice; the "Show filters" toggle still re-expands.defaultFacetRailCollapsed?: boolean+ // Same, for the volume chart. Panels embedded in a short pane start without it.+ defaultSparklineCollapsed?: boolean}export function LogsViewer({@@ -59,10 +61,14 @@ export function LogsViewer({personId,sessionId,defaultFacetRailCollapsed,+ defaultSparklineCollapsed,}: LogsViewerProps): JSX.Element {return (<BindLogic logic={logsViewerFiltersLogic} props={{ id, initialFilters, pinnedFilters, personId, sessionId }}>- <BindLogic logic={logsViewerConfigLogic} props={{ id, defaultFacetRailCollapsed }}>+ <BindLogic+ logic={logsViewerConfigLogic}+ props={{ id, defaultFacetRailCollapsed, defaultSparklineCollapsed }}+ ><BindLogic logic={logsViewerDataLogic} props={{ id }}><BindLogic logic={logDetailsModalLogic} props={{ id }}><BindLogic logic={logsViewerLogic} props={{ id }}>diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.tsindex 66c97fdcbf4b..af3b3f31cc5a 100644--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts@@ -50,6 +50,7 @@ export const MAX_GROUP_BY_DIMENSIONS = 4export interface LogsViewerConfigProps {id: stringdefaultFacetRailCollapsed?: boolean+ defaultSparklineCollapsed?: boolean}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -200,7 +201,7 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([},],sparklineCollapsed: [- false,+ props.defaultSparklineCollapsed ?? false,{ persist: true },{toggleSparklineCollapsed: (state) => !state,diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.tsindex 0ebb5d3ebfbd..b8bb3791f789 100644--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.test.ts@@ -397,12 +397,51 @@ describe('logsViewerDataLogic', () => {}).toNotHaveDispatchedActions([filtersLogic.actionCreators.bumpFacetRefresh()])})+ it.each([+ ['setSessionId', 'sess-1'],+ ['setPersonId', 'person-1'],+ ])('setting and clearing the scope via %s triggers runQuery', async (action, value) => {+ await expectLogic(logic, () => {+ ;(filtersLogic.actions as any)[action](value)+ }).toDispatchActions(['runQuery'])++ await expectLogic(logic, () => {+ ;(filtersLogic.actions as any)[action](undefined)+ }).toDispatchActions(['runQuery'])+ })+it('setFilters triggers runQuery', async () => {await expectLogic(logic, () => {filtersLogic.actions.setFilters({ searchTerm: 'new search' })}).toDispatchActions(['handleQueryChange', 'runQuery'])})+ it('mounting a scoped viewer runs one query, not one per scope prop', async () => {+ // Without the guard the mount firing of each scope subscription adds its own query.+ let queryCalls = 0+ useMocks({+ post: {+ '/api/environments/:team_id/logs/query/': () => {+ queryCalls += 1+ return [200, { results: [], maxExportableLogs: 5000 }]+ },+ '/api/environments/:team_id/logs/sparkline/': () => [200, []],+ },+ })++ const scopedFilters = logsViewerFiltersLogic({ id: 'scoped-tab', sessionId: 'sess-1' })+ const scoped = logsViewerDataLogic({ id: 'scoped-tab' })+ queryCalls = 0+ scopedFilters.mount()+ scoped.mount()+ await expectLogic(scoped).toFinishAllListeners()++ expect(queryCalls).toBe(1)++ scoped.unmount()+ scopedFilters.unmount()+ })+it('setOrderBy triggers runQuery', async () => {const configLogic = logsViewerConfigLogic({ id: 'test-tab' })configLogic.mount()diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.tsindex 1b2fca5eae85..6585ce2908fd 100644--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts@@ -140,6 +140,7 @@ export interface logsViewerDataLogicValues {filters: LogsViewerFilters // logsViewerFiltersLogicpersonId: string | undefined // logsViewerFiltersLogicqueryFilterGroup: UniversalFiltersGroup // logsViewerFiltersLogic+ queryScopeKey: string // logsViewerFiltersLogicsessionId: string | undefined // logsViewerFiltersLogicutcDateRange: {date_from: string | null | undefined@@ -482,7 +483,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([],values: [logsViewerFiltersLogic({ id }),- ['filters', 'utcDateRange', 'filterGroup', 'queryFilterGroup', 'personId', 'sessionId'],+ ['filters', 'utcDateRange', 'filterGroup', 'queryFilterGroup', 'personId', 'sessionId', 'queryScopeKey'],logsViewerConfigLogic({ id }),['orderBy', 'customColumns'],],@@ -974,7 +975,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([],}),- subscriptions(({ actions }) => ({+ subscriptions(({ actions, values }) => ({// Subscribe to the combined query view rather than the user-editable filterGroup// so the query reruns when pinned filters change (e.g. team `logs_distinct_id_attribute_keys`// resolves after mount), not just when the user edits filters.@@ -984,6 +985,14 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([}actions.handleQueryChange('attributes')},+ // The mount firing is skipped, but a scope change during the first query is not, because+ // that query already went out with the old scope.+ queryScopeKey: () => {+ if (!values.hasRunQuery && !values.logsLoading) {+ return+ }+ actions.runQuery()+ },})),listeners(({ actions, values, cache, props }) => ({diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.tsindex 07a8c259cc5c..9b510c7b1f77 100644--- a/products/logs/frontend/utils.test.ts+++ b/products/logs/frontend/utils.test.ts@@ -233,6 +233,21 @@ describe('logs utils', () => {it('leaves the range alone without a timestamp', () => {expect(buildLogsSessionScope('sess-1')).toEqual({ sessionId: 'sess-1', initialFilters: undefined })})++ it('narrows the range to a caller-supplied window', () => {+ expect(buildLogsSessionScope('sess-1', '2026-03-24T12:00:00.000Z', 5).initialFilters).toEqual({+ dateRange: { date_from: '2026-03-24T11:55:00.000Z', date_to: '2026-03-24T12:05:00.000Z' },+ })+ })++ it('keeps the window when there is no session to scope to', () => {+ expect(buildLogsSessionScope(undefined, '2026-03-24T12:00:00.000Z', 5)).toEqual({+ sessionId: undefined,+ initialFilters: {+ dateRange: { date_from: '2026-03-24T11:55:00.000Z', date_to: '2026-03-24T12:05:00.000Z' },+ },+ })+ })})const filterGroup = (diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsxindex 0c83b567f1ed..8a104fff1e34 100644--- a/products/logs/frontend/utils.tsx+++ b/products/logs/frontend/utils.tsx@@ -258,6 +258,10 @@ export const RELATED_ERRORS_WINDOW_HOURS = 6// Wide enough to cover a session around a single event without drowning it in unrelated logs.export const SESSION_LOGS_WINDOW_MINUTES = 30+// Tighter than SESSION_LOGS_WINDOW_MINUTES because the exception card's Logs tab can run unscoped,+// where the range is all that holds it off the project's whole log volume.+export const EXCEPTION_LOGS_WINDOW_MINUTES = 5+export function buildDateRangeAround(timestamp: string, windowMinutes: number): { date_from: string; date_to: string } {const center = dayjs(timestamp)return {@@ -270,16 +274,15 @@ export function buildDateRangeAround(timestamp: string, windowMinutes: number):// session replay). The session id goes to the server as a scope rather than a filter group: it// has to match across every configured and conventional key in both attribute maps, and the// query runner reads a filter group's inner group as an AND of its leaves, so a group could only-// ever express "every key holds this id at once". A timestamp scopes the date range to ±30-// minutes so old sessions aren't hidden by the default range.+// ever express "every key holds this id at once". A timestamp scopes the date range to+// windowMinutes either side, so old sessions aren't hidden by the viewer's default range.export function buildLogsSessionScope(- sessionId: string,- timestamp?: string-): { sessionId: string; initialFilters?: Partial<LogsViewerFilters> } {+ sessionId: string | undefined,+ timestamp?: string,+ windowMinutes: number = SESSION_LOGS_WINDOW_MINUTES+): { sessionId?: string; initialFilters?: Partial<LogsViewerFilters> } {return {sessionId,- initialFilters: timestamp- ? { dateRange: buildDateRangeAround(timestamp, SESSION_LOGS_WINDOW_MINUTES) }- : undefined,+ initialFilters: timestamp ? { dateRange: buildDateRangeAround(timestamp, windowMinutes) } : undefined,}}