: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(logs): open logs viewer modal from view logs button instead of dead link (#72241)
Jon McCallum218544d8334c
diff --git a/products/logs/frontend/components/LogsViewer/LogContextSelector/logContextUtils.ts b/products/logs/frontend/components/LogsViewer/LogContextSelector/logContextUtils.tsindex d0f5833bfab3..c4ba03d0e3b4 100644--- a/products/logs/frontend/components/LogsViewer/LogContextSelector/logContextUtils.ts+++ b/products/logs/frontend/components/LogsViewer/LogContextSelector/logContextUtils.ts@@ -1,10 +1,13 @@-import { dayjs } from 'lib/dayjs'-import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'import { ParsedLogMessage } from 'products/logs/frontend/types'-import { SessionIdMatch, getSessionIdWithKey } from 'products/logs/frontend/utils'+import {+ SESSION_LOGS_WINDOW_MINUTES,+ SessionIdMatch,+ buildDateRangeAround,+ getSessionIdWithKey,+} from 'products/logs/frontend/utils'export type LogContextType = 'surrounding_service' | 'surrounding_all' | 'trace' | 'session'@@ -16,7 +19,6 @@ export interface LogContextOption {const SURROUNDING_WINDOW_MINUTES = 1const TRACE_WINDOW_MINUTES = 5-const SESSION_WINDOW_MINUTES = 30function getServiceName(log: ParsedLogMessage): string | null {const resourceAttrs = log.resource_attributes as Record<string, unknown> | undefined@@ -28,14 +30,6 @@ function getSessionMatch(log: ParsedLogMessage, configuredKeys?: string[]): Sessreturn getSessionIdWithKey(log.attributes, log.resource_attributes, configuredKeys)}-function buildDateRangeAround(timestamp: string, windowMinutes: number): { date_from: string; date_to: string } {- const center = dayjs(timestamp)- return {- date_from: center.subtract(windowMinutes, 'minute').toISOString(),- date_to: center.add(windowMinutes, 'minute').toISOString(),- }-}-function buildFilterGroup(key: string, value: string, propertyType: PropertyFilterType): UniversalFiltersGroup {return {type: FilterLogicalOperator.And,@@ -129,7 +123,7 @@ export function buildContextFilters(const session = getSessionMatch(log, configuredKeys)return {...base,- dateRange: buildDateRangeAround(log.timestamp, SESSION_WINDOW_MINUTES),+ dateRange: buildDateRangeAround(log.timestamp, SESSION_LOGS_WINDOW_MINUTES),filterGroup: session? buildFilterGroup(session.key,diff --git a/products/logs/frontend/components/ViewLogsButton.tsx b/products/logs/frontend/components/ViewLogsButton.tsxindex 854778a47a22..dcc0af73f52a 100644--- a/products/logs/frontend/components/ViewLogsButton.tsx+++ b/products/logs/frontend/components/ViewLogsButton.tsx@@ -1,12 +1,13 @@-import { useValues } from 'kea'+import { useActions, useValues } from 'kea'import { IconLive } from '@posthog/icons'import { LemonButton, LemonButtonProps } from '@posthog/lemon-ui'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { logsViewerModalLogic } from 'products/logs/frontend/components/LogsViewer/LogsViewerModal/logsViewerModalLogic'import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'-import { buildLogsSessionUrl } from 'products/logs/frontend/utils'+import { buildLogsSessionFilters } from 'products/logs/frontend/utils'export interface ViewLogsButtonProps extends Pick<LemonButtonProps, 'size' | 'type' | 'className' | 'data-attr'> {sessionId: string | null | undefined@@ -15,7 +16,7 @@ export interface ViewLogsButtonProps extends Pick<LemonButtonProps, 'size' | 'tyiconOnly?: boolean}-// Links into the logs scene filtered to one session, using the team's configured+// Opens the logs viewer modal 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.@@ -26,6 +27,7 @@ export function ViewLogsButton({...buttonProps}: ViewLogsButtonProps): JSX.Element | null {const { configuredSessionIdKeys, logsConfigLoading } = useValues(logsConfigLogic)+ const { openLogsViewerModal } = useActions(logsViewerModalLogic)const enabled = useFeatureFlag('LOGS_IN_ERROR_TRACKING')if (!enabled) {@@ -33,16 +35,22 @@ export function ViewLogsButton({}// 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+ // Opening with the fallback key here would silently show logs filtered by the wrong+ // attribute for teams that configured a custom key, so hold the button in a loading state.+ const onClick =+ sessionId && !logsConfigLoading+ ? () =>+ openLogsViewerModal({+ id: `session-${sessionId}`,+ fullScreen: false,+ initialFilters: buildLogsSessionFilters(sessionId, configuredSessionIdKeys, timestamp),+ })+ : undefinedreturn (<LemonButtonicon={<IconLive />}- to={to}- targetBlank+ onClick={onClick}loading={logsConfigLoading}tooltip={iconOnly ? 'View logs from this session' : undefined}disabledReason={sessionId ? undefined : 'No session ID associated with this event'}diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.tsindex 8fedcd0a5d6f..b0d8d704f8f8 100644--- a/products/logs/frontend/utils.test.ts+++ b/products/logs/frontend/utils.test.ts@@ -1,5 +1,7 @@+import { UniversalFiltersGroup } from '~/types'+import {- buildLogsSessionUrl,+ buildLogsSessionFilters,formatFilterGroupValues,getFiltersSummaryLines,getSessionIdFromLogAttributes,@@ -149,22 +151,15 @@ describe('logs utils', () => {})})- describe('buildLogsSessionUrl', () => {- const parseUrl = (url: string): { path: string; params: URLSearchParams } => {- const [path, query] = url.split('?')- return { path, params: new URLSearchParams(query) }- }-+ describe('buildLogsSessionFilters', () => {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 filters = buildLogsSessionFilters('sess-1', configuredKeys)- const filterGroup = JSON.parse(params.get('filterGroup')!)- const innerGroup = filterGroup.values[0]+ const innerGroup = filters.filterGroup!.values[0] as UniversalFiltersGroupexpect(innerGroup.type).toBe('OR')expect(innerGroup.values).toEqual(expectedKeys.map((key) => ({@@ -174,13 +169,12 @@ describe('logs utils', () => {type: 'log_attribute',})))- expect(params.get('dateRange')).toBeNull()+ expect(filters.dateRange).toBeUndefined()})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({+ const filters = buildLogsSessionFilters('sess-1', undefined, '2026-03-24T12:00:00.000Z')+ expect(filters.dateRange).toEqual({date_from: '2026-03-24T11:30:00.000Z',date_to: '2026-03-24T12:30:00.000Z',})diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsxindex ee96efc3b4a6..4e30f5c2294a 100644--- a/products/logs/frontend/utils.tsx+++ b/products/logs/frontend/utils.tsx@@ -2,10 +2,10 @@ import { formatDateRangeLabel } from 'lib/components/DateFilter/DateRangePicker/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, FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'+import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'import { DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS } from 'products/logs/frontend/logsConfigLogic'export function formatFilterGroupValues(filterGroup: Record<string, any> | undefined): string[] {@@ -153,40 +153,45 @@ export function getSessionIdFromLogAttributes(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+// Wide enough to cover a session around a single event without drowning it in unrelated logs.+export const SESSION_LOGS_WINDOW_MINUTES = 30-// Builds a logs-scene URL filtered to one session, for linking in from other products+export function buildDateRangeAround(timestamp: string, windowMinutes: number): { date_from: string; date_to: string } {+ const center = dayjs(timestamp)+ return {+ date_from: center.subtract(windowMinutes, 'minute').toISOString(),+ date_to: center.add(windowMinutes, 'minute').toISOString(),+ }+}++// Builds logs viewer filters scoped to one session, for other products surfacing logs// (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 {+export function buildLogsSessionFilters(+ sessionId: string,+ configuredKeys?: string[],+ timestamp?: string+): Partial<LogsViewerFilters> {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 filters: Partial<LogsViewerFilters> = {+ 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(),- })- )+ filters.dateRange = buildDateRangeAround(timestamp, SESSION_LOGS_WINDOW_MINUTES)}- return `${urls.logs()}?${params.toString()}`+ return filters}