: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 view logs link from exception surfaces (#70751)
Jon McCallum3c6ec10be2ec
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 6508d16714da..f6cc019f5005 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -355,6 +355,7 @@ export const FEATURE_FLAGS = {LOGS_ALERTING: 'logs-alerting', // owner: #team-logsLOGS_COLUMN_CONFIGURATION: 'logs-column-configuration', // owner: #team-logsLOGS_GROUP_BY: 'logs-group-by', // owner: #team-logs+ LOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logsLOGS_PATTERNS_VIEW: 'logs-patterns-view', // owner: #team-logsLOGS_SAVED_VIEWS: 'logs-saved-views', // owner: #team-logsLOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logsdiff --git a/products/error_tracking/frontend/components/EventsTable/EventsTable.tsx b/products/error_tracking/frontend/components/EventsTable/EventsTable.tsxindex 5c07e857b320..2f180a86bafe 100644--- a/products/error_tracking/frontend/components/EventsTable/EventsTable.tsx+++ b/products/error_tracking/frontend/components/EventsTable/EventsTable.tsx@@ -17,6 +17,8 @@ import { urls } from 'scenes/urls'import { EventsQuery } from '~/queries/schema/schema-general'+import { ViewLogsButton } from 'products/logs/frontend/components/ViewLogsButton'+import { useErrorTagRenderer } from '../../hooks/use-error-tag-renderer'import { cancelEvent } from '../../utils'import { DataSourceTable, DataSourceTableColumn } from '../DataSourceTable'@@ -137,6 +139,16 @@ const Actions = (record: ErrorEventType): JSX.Element => {iconOnly/></div>+ <div className="flex justify-end align-middle items-center" onClick={(event) => cancelEvent(event)}>+ <ViewLogsButton+ type="secondary"+ sessionId={sessionId}+ timestamp={record.timestamp}+ size="xsmall"+ data-attr="error-tracking-view-logs"+ iconOnly+ />+ </div>{record.properties.$ai_trace_id && (<LemonButtonsize="small"diff --git a/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsx b/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsxindex 73fe202cd9e8..efcaab309c2d 100644--- a/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsx+++ b/products/error_tracking/frontend/components/ExceptionCard/Tabs/SessionTab/index.tsx@@ -28,6 +28,8 @@ import {} from 'lib/ui/TabsPrimitive/TabsPrimitive'import { cn } from 'lib/utils/css-classes'+import { ViewLogsButton } from 'products/logs/frontend/components/ViewLogsButton'+import { exceptionCardLogic } from '../../exceptionCardLogic'import { SubHeader } from '../SubHeader'import { SessionRecordingTab } from './SessionRecordingTab'@@ -66,6 +68,14 @@ export function SessionTab({ timestamp, className, ...props }: SessionTabProps):<TabsPrimitiveTrigger className="px-2 h-full" value="recording">Recording</TabsPrimitiveTrigger>+ <div className="ml-auto pr-1">+ <ViewLogsButton+ sessionId={sessionId}+ timestamp={timestamp}+ size="xsmall"+ data-attr="error-tracking-session-view-logs"+ />+ </div></TabsPrimitiveList></SubHeader><SessionTimelineTab />diff --git a/products/logs/frontend/components/ViewLogsButton.tsx b/products/logs/frontend/components/ViewLogsButton.tsxnew file mode 100644index 000000000000..854778a47a22--- /dev/null+++ b/products/logs/frontend/components/ViewLogsButton.tsx@@ -0,0 +1,54 @@+import { useValues } from 'kea'++import { IconLive } from '@posthog/icons'+import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'++import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'++import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'+import { buildLogsSessionUrl } from 'products/logs/frontend/utils'++export interface ViewLogsButtonProps extends Pick<LemonButtonProps, 'size' | 'type' | 'className' | 'data-attr'> {+ sessionId: string | null | undefined+ /** Scopes the logs date range around this time, so old sessions aren't hidden by the default range. */+ timestamp?: string+ iconOnly?: boolean+}++// Links into the logs scene filtered to one session, using the team's configured+// session ID attribute keys. The session-replay / error-tracking counterpart of+// logs' own ViewRecordingButton usage. Gated here rather than at call sites so+// every surface of the logs-in-error-tracking rollout toggles with one flag.+export function ViewLogsButton({+ sessionId,+ timestamp,+ iconOnly,+ ...buttonProps+}: ViewLogsButtonProps): JSX.Element | null {+ const { configuredSessionIdKeys, logsConfigLoading } = useValues(logsConfigLogic)+ const enabled = useFeatureFlag('LOGS_IN_ERROR_TRACKING')++ if (!enabled) {+ return null+ }++ // Until the team's logs config resolves we don't know which session-ID keys to filter on.+ // Linking with the fallback key here would silently open logs filtered by the wrong+ // attribute for teams that configured a custom key, so hold the link in a loading state.+ const to =+ sessionId && !logsConfigLoading ? buildLogsSessionUrl(sessionId, configuredSessionIdKeys, timestamp) : undefined++ return (+ <LemonButton+ icon={<IconLive />}+ to={to}+ targetBlank+ loading={logsConfigLoading}+ tooltip={iconOnly ? 'View logs from this session' : undefined}+ disabledReason={sessionId ? undefined : 'No session ID associated with this event'}+ {...buttonProps}+ >+ {iconOnly ? null : 'View logs'}+ </LemonButton>+ )+}diff --git a/products/logs/frontend/logsSceneLogic.test.ts b/products/logs/frontend/logsSceneLogic.test.tsindex 9b8db97b8dfe..4b12912d1dc1 100644--- a/products/logs/frontend/logsSceneLogic.test.ts+++ b/products/logs/frontend/logsSceneLogic.test.ts@@ -115,6 +115,27 @@ describe('logsSceneLogic', () => {expect(logic.values.filters.severityLevels).toEqual(expected)})++ it('parses a stringified filterGroup from the URL (e.g. a cross-product session link)', async () => {+ const filterGroup = {+ type: 'AND',+ values: [{ type: 'OR', values: [{ key: 'posthogSessionId', value: ['sess-1'], operator: 'exact' }] }],+ }+ await expectLogic(logic, () => {+ router.actions.push('/logs', { filterGroup: JSON.stringify(filterGroup) })+ }).toFinishAllListeners()++ expect(logic.values.filters.filterGroup).toEqual(filterGroup)+ })++ it('ignores a malformed filterGroup in the URL', async () => {+ const before = logic.values.filters.filterGroup+ await expectLogic(logic, () => {+ router.actions.push('/logs', { filterGroup: '{not valid json' })+ }).toFinishAllListeners()++ expect(logic.values.filters.filterGroup).toEqual(before)+ })})describe('activeTab URL sync', () => {diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsxindex 05752483bfc9..5d35bb614fb3 100644--- a/products/logs/frontend/logsSceneLogic.tsx+++ b/products/logs/frontend/logsSceneLogic.tsx@@ -116,9 +116,15 @@ export const logsSceneLogic = kea<logsSceneLogicType>([}}if (params.filterGroup) {- if (!equal(params.filterGroup, values.filters.filterGroup)) {- filtersFromUrl.filterGroup = params.filterGroup- hasFilterChanges = true+ try {+ const filterGroup =+ typeof params.filterGroup === 'string' ? JSON.parse(params.filterGroup) : params.filterGroup+ if (!equal(filterGroup, values.filters.filterGroup)) {+ filtersFromUrl.filterGroup = filterGroup+ hasFilterChanges = true+ }+ } catch {+ // Ignore malformed filterGroup JSON in URL}} else if (!equal(DEFAULT_UNIVERSAL_GROUP_FILTER, values.filters.filterGroup)) {filtersFromUrl.filterGroup = DEFAULT_UNIVERSAL_GROUP_FILTERdiff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.tsindex 0a162db69204..8fedcd0a5d6f 100644--- a/products/logs/frontend/utils.test.ts+++ b/products/logs/frontend/utils.test.ts@@ -1,4 +1,5 @@import {+ buildLogsSessionUrl,formatFilterGroupValues,getFiltersSummaryLines,getSessionIdFromLogAttributes,@@ -148,6 +149,44 @@ describe('logs utils', () => {})})+ describe('buildLogsSessionUrl', () => {+ const parseUrl = (url: string): { path: string; params: URLSearchParams } => {+ const [path, query] = url.split('?')+ return { path, params: new URLSearchParams(query) }+ }++ it.each([+ ['defaults to the SDK convention key', undefined, ['posthogSessionId']],+ ['uses configured keys in order', ['session.id', 'custom.key'], ['session.id', 'custom.key']],+ ['empty configured list falls back to default', [], ['posthogSessionId']],+ ])('%s', (_, configuredKeys, expectedKeys) => {+ const { path, params } = parseUrl(buildLogsSessionUrl('sess-1', configuredKeys))+ expect(path).toBe('/logs')++ const filterGroup = JSON.parse(params.get('filterGroup')!)+ const innerGroup = filterGroup.values[0]+ expect(innerGroup.type).toBe('OR')+ expect(innerGroup.values).toEqual(+ expectedKeys.map((key) => ({+ key,+ value: ['sess-1'],+ operator: 'exact',+ type: 'log_attribute',+ }))+ )+ expect(params.get('dateRange')).toBeNull()+ })++ it('scopes the date range around the timestamp', () => {+ const { params } = parseUrl(buildLogsSessionUrl('sess-1', undefined, '2026-03-24T12:00:00.000Z'))+ const dateRange = JSON.parse(params.get('dateRange')!)+ expect(dateRange).toEqual({+ date_from: '2026-03-24T11:30:00.000Z',+ date_to: '2026-03-24T12:30:00.000Z',+ })+ })+ })+const filterGroup = (...filters: Array<{ key: string; value: any; type?: string; operator?: string }>): Record<string, any> => ({diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsxindex 759c7c0509cf..ee96efc3b4a6 100644--- a/products/logs/frontend/utils.tsx+++ b/products/logs/frontend/utils.tsx@@ -1,8 +1,12 @@import { formatDateRangeLabel } from 'lib/components/DateFilter/DateRangePicker/utils'import { isValidPropertyFilter } from 'lib/components/PropertyFilters/utils'+import { dayjs } from 'lib/dayjs'import { capitalizeFirstLetter } from 'lib/utils/strings'+import { urls } from 'scenes/urls'-import { AnyPropertyFilter } from '~/types'+import { AnyPropertyFilter, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'++import { DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS } from 'products/logs/frontend/logsConfigLogic'export function formatFilterGroupValues(filterGroup: Record<string, any> | undefined): string[] {const group = filterGroup?.values?.[0]@@ -148,3 +152,41 @@ export function getSessionIdFromLogAttributes(): string | null {return getSessionIdWithKey(attributes, resourceAttributes, configuredKeys)?.value ?? null}++// Matches SESSION_WINDOW_MINUTES in logContextUtils — wide enough to cover a session+// around a single event without drowning it in unrelated logs.+const SESSION_LOGS_WINDOW_MINUTES = 30++// Builds a logs-scene URL filtered to one session, for linking in from other products+// (error tracking, session replay). Filters on the team's configured session ID keys+// (OR across keys, exact match), defaulting to the SDK convention; a timestamp scopes+// the date range to ±30 minutes so old sessions aren't hidden by the default range.+export function buildLogsSessionUrl(sessionId: string, configuredKeys?: string[], timestamp?: string): string {+ const keys = configuredKeys?.length ? configuredKeys : DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS+ const filterGroup = {+ type: FilterLogicalOperator.And,+ values: [+ {+ type: FilterLogicalOperator.Or,+ values: keys.map((key) => ({+ key,+ value: [sessionId],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.LogAttribute,+ })),+ },+ ],+ }+ const params = new URLSearchParams({ filterGroup: JSON.stringify(filterGroup) })+ if (timestamp) {+ const center = dayjs(timestamp)+ params.set(+ 'dateRange',+ JSON.stringify({+ date_from: center.subtract(SESSION_LOGS_WINDOW_MINUTES, 'minute').toISOString(),+ date_to: center.add(SESSION_LOGS_WINDOW_MINUTES, 'minute').toISOString(),+ })+ )+ }+ return `${urls.logs()}?${params.toString()}`+}