Skip to content

: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.

feat(logs): badge log rows whose session hit errors (#95432)

Jimmy Zhu6da14f3665bc
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 5640fbc672ac..d3360f0e9953 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7984,6 +7984,14 @@ snapshots:
hash: v1.k794b7964.35d3511b15e9d3aae36c5b8c134fd2fd0984883b2436459dabba605c6b75e6e3.y0RVoMB5HmmmOQv5GD99RYB9APZEnVLqIRKtob_Utw0
scenes-app-logs-logsimpactcounts--sessions-only--light:
hash: v1.k794b7964.4677a4785f1b026a7ee46ab105b05e4862768c39a41c84c41fc192523a5237ae.7NPAF-5cgNNIGaM6yavgjc990AB-UAplqFK_6V4eTes
+ scenes-app-logs-sessionerrorsbadge--one-error--dark:
+ hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.Zoa3-_zRiDxW2DVeBYD64fV80BWOtlngAzOqnRjMam8
+ scenes-app-logs-sessionerrorsbadge--one-error--light:
+ hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.UYQnUZ6SNr2i9-ef8xVE28d2dkzuTsguIKBcFeRtXR0
+ scenes-app-logs-sessionerrorsbadge--several-errors--dark:
+ hash: v1.k794b7964.e0e79a77be55d932e351dd624093d0107d0fc1737ad2377ff59625f8c9d2919f.RmzBOXeIfu6YtXX5xWbtQ-LBgX6Vffw7nsiC9tqy6Nk
+ scenes-app-logs-sessionerrorsbadge--several-errors--light:
+ hash: v1.k794b7964.b816e38267a9feb005f365b0826180703192d0d7e1775020b201aa4b9c4a1832.cBNgS9GhMzI2LlBJ1nlaPLzWNdYY5Xr1P9FhiLoYbFw
scenes-app-logs-sparkline--volume-by-severity--dark:
hash: v1.k794b7964.0342a42ad3e96fb82282914a3c60aedb873de9f8dfc94c850b22b3f7f17d56a0.c_sYZ1aNex35E-5hGq0aHwwV1MQCROpZBvMfAznRPoY
scenes-app-logs-sparkline--volume-by-severity--light:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index fc40a5dc5019..aa884731785f 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -373,6 +373,7 @@ export const FEATURE_FLAGS = {
LOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logs
LOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logs
LOGS_SERVICES_VIEW_V2: 'logs-services-view-v2', // owner: #team-logs
+ LOGS_SESSION_ERROR_BADGES: 'logs-session-error-badges', // owner: #team-logs
LOGS_SETTINGS_JSON: 'logs-settings-json', // owner: #team-logs
LOGS_SETTINGS_PII_SCRUB: 'logs-settings-pii-scrub', // owner: #team-logs
LOGS_SETTINGS_RETENTION_RULES: 'logs-settings-retention-rules', // owner: #team-logs
diff --git a/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/relatedErrorsLogic.ts b/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/relatedErrorsLogic.ts
index 83f741868b22..a85070c87ee1 100644
--- a/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/relatedErrorsLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/LogDetailsModal/Tabs/RelatedErrors/relatedErrorsLogic.ts
@@ -2,12 +2,13 @@ import { MakeLogicType, afterMount, kea, key, path, props, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
-import { dayjs } from 'lib/dayjs'
import { MaxErrorTrackingIssuePreview } from '~/queries/schema/schema-assistant-error-tracking'
import { ErrorTrackingIssue, ErrorTrackingQuery, NodeKind } from '~/queries/schema/schema-general'
import { FilterLogicalOperator, PropertyFilterType, PropertyOperator } from '~/types'
+import { RELATED_ERRORS_WINDOW_HOURS, parseLogTimestamp } from 'products/logs/frontend/utils'
+
export interface RelatedErrorsLogicProps {
logUuid: string
logTimestamp: string
@@ -72,16 +73,14 @@ export const relatedErrorsLogic = kea<relatedErrorsLogicType>([
relatedIssues: {
__default: [] as MaxErrorTrackingIssuePreview[],
loadRelatedIssues: async (): Promise<MaxErrorTrackingIssuePreview[]> => {
- // Handle both ISO strings and epoch timestamps (seconds or milliseconds)
- const parsed = Number(props.logTimestamp)
- const timestamp = Number.isNaN(parsed) ? dayjs(props.logTimestamp) : dayjs(parsed)
+ const timestamp = parseLogTimestamp(props.logTimestamp)
const query: ErrorTrackingQuery = {
kind: NodeKind.ErrorTrackingQuery,
orderBy: 'last_seen',
dateRange: {
- date_from: timestamp.subtract(6, 'hours').toISOString(),
- date_to: timestamp.add(6, 'hours').toISOString(),
+ date_from: timestamp.subtract(RELATED_ERRORS_WINDOW_HOURS, 'hours').toISOString(),
+ date_to: timestamp.add(RELATED_ERRORS_WINDOW_HOURS, 'hours').toISOString(),
},
filterGroup: {
type: FilterLogicalOperator.And,
diff --git a/products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic.test.ts b/products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic.test.ts
new file mode 100644
index 000000000000..9ed02da8d7f7
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic.test.ts
@@ -0,0 +1,129 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { LogMessage } from '~/queries/schema/schema-general'
+import { initKeaTests } from '~/test/init'
+
+import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'
+import { logsSessionErrorsLogic } from 'products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic'
+
+const VIEWER_ID = 'test-viewer'
+
+// Only uuid, attributes and timestamp are read; the rest satisfies the schema.
+const BASE_LOG: LogMessage = {
+ uuid: '',
+ trace_id: '',
+ span_id: '',
+ body: 'something happened',
+ attributes: {},
+ timestamp: '2026-09-03T12:00:00.000Z',
+ observed_timestamp: '2026-09-03T12:00:00.000Z',
+ severity_text: 'info',
+ severity_number: 9,
+ level: 'info',
+ resource_attributes: {},
+ instrumentation_scope: '',
+ event_name: '',
+}
+
+function makeLog(uuid: string, sessionId: string | null): LogMessage {
+ return { ...BASE_LOG, uuid, attributes: sessionId ? { sessionId } : {} }
+}
+
+describe('logsSessionErrorsLogic', () => {
+ let logic: ReturnType<typeof logsSessionErrorsLogic.build>
+ let dataLogic: ReturnType<typeof logsViewerDataLogic.build>
+ let queryBodies: any[]
+ let pageResults: LogMessage[]
+
+ // Loads a page the way the viewer does, through a landing logs query. That path carries the
+ // short debounce; going through setLogs instead would pay the live-tail one in every test.
+ const loadPage = async (logs: LogMessage[]): Promise<void> => {
+ pageResults = logs
+ dataLogic.actions.fetchLogs()
+ await expectLogic(logic).toFinishAllListeners()
+ }
+
+ beforeEach(() => {
+ queryBodies = []
+ pageResults = []
+ useMocks({
+ post: {
+ '/api/environments/:team_id/logs/query/': () => [
+ 200,
+ { results: pageResults, maxExportableLogs: 5000 },
+ ],
+ '/api/environments/:team_id/query/HogQLQuery': async ({ request }) => {
+ queryBodies.push(await request.json())
+ return [200, { results: [['session-a', 3]] }]
+ },
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([], { [FEATURE_FLAGS.LOGS_SESSION_ERROR_BADGES]: true })
+ dataLogic = logsViewerDataLogic({ id: VIEWER_ID, autoLoad: false })
+ dataLogic.mount()
+ logic = logsSessionErrorsLogic({ id: VIEWER_ID })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ dataLogic.unmount()
+ })
+
+ it('records a zero for every session it looked up, so the next page only asks about new ones', async () => {
+ await loadPage([makeLog('log-1', 'session-a'), makeLog('log-2', 'session-b')])
+
+ expect(logic.values.sessionErrorCounts).toEqual({ 'session-a': 3, 'session-b': 0 })
+
+ // A live-tail poll that adds one session must not re-ask about the two already answered.
+ dataLogic.actions.setLogs([
+ makeLog('log-1', 'session-a'),
+ makeLog('log-2', 'session-b'),
+ makeLog('log-3', 'session-c'),
+ ])
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(queryBodies).toHaveLength(2)
+ expect(queryBodies[1].query.query).toContain("'session-c'")
+ expect(queryBodies[1].query.query).not.toContain("'session-a'")
+ })
+
+ it('deduplicates the sessions on the page', async () => {
+ await loadPage([makeLog('log-1', 'session-a'), makeLog('log-2', 'session-a'), makeLog('log-3', null)])
+
+ expect(logic.values.sessionIdsInView).toEqual(['session-a'])
+ expect(queryBodies[0].query.query.match(/'session-a'/g)).toHaveLength(1)
+ })
+
+ it('still builds a window when timestamps arrive as epoch numbers', async () => {
+ await loadPage([
+ { ...BASE_LOG, uuid: 'log-1', attributes: { sessionId: 'session-a' }, timestamp: '1788474031592' },
+ ])
+
+ expect(logic.values.sessionErrorCounts).toEqual({ 'session-a': 3 })
+ expect(queryBodies[0].query.query).toContain('2026-')
+ })
+
+ it('queries nothing while the feature flag is off', async () => {
+ featureFlagLogic.actions.setFeatureFlags([], {})
+ await loadPage([makeLog('log-1', 'session-a')])
+
+ expect(queryBodies).toHaveLength(0)
+ expect(logic.values.sessionErrorCounts).toEqual({})
+ })
+
+ it('drops counts from the previous filters when a fresh query lands', async () => {
+ await loadPage([makeLog('log-1', 'session-a')])
+ expect(logic.values.sessionErrorCounts).toEqual({ 'session-a': 3 })
+
+ await loadPage([])
+
+ expect(logic.values.sessionErrorCounts).toEqual({})
+ })
+})
diff --git a/products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic.ts b/products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic.ts
new file mode 100644
index 000000000000..14c647fcf5fd
--- /dev/null
+++ b/products/logs/frontend/components/LogsViewer/logsSessionErrorsLogic.ts
@@ -0,0 +1,254 @@
+import { MakeLogicType, connect, kea, key, listeners, path, props, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import api from 'lib/api'
+import { FEATURE_FLAGS } from 'lib/constants'
+import { dayjs } from 'lib/dayjs'
+import { type FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { hogql } from '~/queries/utils'
+
+import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'
+import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
+import { ParsedLogMessage } from 'products/logs/frontend/types'
+import {
+ RELATED_ERRORS_WINDOW_HOURS,
+ getSessionIdFromLogAttributes,
+ parseLogTimestamp,
+} from 'products/logs/frontend/utils'
+
+// One page of logs can carry hundreds of distinct sessions. The lookup is a single query either
+// way, but the IN list ends up in the query text, so cap what a runaway page can put there.
+const MAX_SESSIONS_PER_LOOKUP = 200
+
+// A fresh page should badge quickly. A live-tail poll lands about once a second, so its
+// incremental lookups wait longer, which stops a busy stream queueing a query per tick.
+const FIRST_LOOKUP_DEBOUNCE_MS = 300
+const INCREMENTAL_LOOKUP_DEBOUNCE_MS = 2000
+
+export interface LogsSessionErrorsLogicProps {
+ id: string
+}
+
+interface SessionErrorsWindow {
+ from: string
+ to: string
+}
+
+// The union of every loaded row's Related errors window. That union is the range that can hold an
+// exception the tab lists for any row on the page, so a wide page reads a wide range. Null when no
+// row carries a timestamp the parser understands, because there is then no range to ask about.
+function pageLookupWindow(logs: ParsedLogMessage[]): SessionErrorsWindow | null {
+ let earliest = Number.POSITIVE_INFINITY
+ let latest = Number.NEGATIVE_INFINITY
+ for (const log of logs) {
+ const timestamp = parseLogTimestamp(log.timestamp).valueOf()
+ if (Number.isNaN(timestamp)) {
+ continue
+ }
+ if (timestamp < earliest) {
+ earliest = timestamp
+ }
+ if (timestamp > latest) {
+ latest = timestamp
+ }
+ }
+ if (!Number.isFinite(earliest) || !Number.isFinite(latest)) {
+ return null
+ }
+ return {
+ from: dayjs(earliest).subtract(RELATED_ERRORS_WINDOW_HOURS, 'hours').toISOString(),
+ to: dayjs(latest).add(RELATED_ERRORS_WINDOW_HOURS, 'hours').toISOString(),
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsSessionErrorsLogicValues {
+ featureFlags: FeatureFlagsSet // featureFlagLogic
+ configuredSessionIdKeys: string[] | undefined // logsConfigLogic
+ logs: ParsedLogMessage[] // logsViewerDataLogic
+ sessionErrorCounts: Record<string, number>
+ sessionErrorCountsLoading: boolean
+ sessionIdsInView: string[]
+ showSessionErrors: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsSessionErrorsLogicActions {
+ fetchLogsSuccess: (
+ logs: import('~/queries/schema').LogMessage[],
+ payload?: any
+ ) => {
+ logs: import('~/queries/schema').LogMessage[]
+ payload?: any
+ } // logsViewerDataLogic
+ fetchNextLogsPageSuccess: (
+ logs: import('~/queries/schema').LogMessage[],
+ payload?:
+ | {
+ limit: number | undefined
+ }
+ | undefined
+ ) => {
+ logs: import('~/queries/schema').LogMessage[]
+ payload?: {
+ limit: number | undefined
+ }
+ } // logsViewerDataLogic
+ setLogsSuccess: (
+ logs: import('~/queries/schema').LogMessage[],
+ payload?:
+ | {
+ logs: import('~/queries/schema').LogMessage[]
+ }
+ | undefined
+ ) => {
+ logs: import('~/queries/schema').LogMessage[]
+ payload?: {
+ logs: import('~/queries/schema').LogMessage[]
+ }
+ } // logsViewerDataLogic
+ loadSessionErrorCounts: ({ reset }: { reset: boolean }) => {
+ reset: boolean
+ }
+ loadSessionErrorCountsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadSessionErrorCountsSuccess: (
+ sessionErrorCounts: Record<string, number>,
+ payload?: {
+ reset: boolean
+ }
+ ) => {
+ sessionErrorCounts: Record<string, number>
+ payload?: {
+ reset: boolean
+ }
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsSessionErrorsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ showSessionErrors: (featureFlags: FeatureFlagsSet) => boolean
+ sessionIdsInView: (logs: ParsedLogMessage[], configuredSessionIdKeys: string[] | undefined) => string[]
+ }
+}
+
+export type logsSessionErrorsLogicType = MakeLogicType<
+ logsSessionErrorsLogicValues,
+ logsSessionErrorsLogicActions,
+ LogsSessionErrorsLogicProps,
+ logsSessionErrorsLogicMeta
+>
+
+// How many exceptions each session on the current page hit, so a log row can say "this session hit
+// errors" without the user opening the row's Related errors tab first. The count answers the
+// session, not the log line: an exception in the same session is co-occurring evidence, not a cause.
+//
+// The count comes from raw `$exception` events, while the tab it opens resolves them into Error
+// Tracking issues. So the badge counts events the tab may group, suppress, or filter out, and the
+// two can disagree on the number.
+export const logsSessionErrorsLogic = kea<logsSessionErrorsLogicType>([
+ props({} as LogsSessionErrorsLogicProps),
+ key((props) => props.id),
+ path((key) => ['products', 'logs', 'frontend', 'components', 'LogsViewer', 'logsSessionErrorsLogic', key]),
+
+ connect(({ id }: LogsSessionErrorsLogicProps) => ({
+ values: [
+ logsViewerDataLogic({ id }),
+ ['parsedLogs as logs'],
+ logsConfigLogic,
+ ['configuredSessionIdKeys'],
+ featureFlagLogic,
+ ['featureFlags'],
+ ],
+ actions: [logsViewerDataLogic({ id }), ['fetchLogsSuccess', 'fetchNextLogsPageSuccess', 'setLogsSuccess']],
+ })),
+
+ loaders(({ values }) => ({
+ sessionErrorCounts: [
+ {} as Record<string, number>,
+ {
+ loadSessionErrorCounts: async (
+ { reset }: { reset: boolean },
+ breakpoint
+ ): Promise<Record<string, number>> => {
+ // A fresh query replaces the result set, so drop what the previous filters answered.
+ const known = reset ? {} : values.sessionErrorCounts
+ // hasOwn, not `in`: `in` walks the prototype chain, so a session id that
+ // collides with an Object member would read as already answered.
+ const sessionIds = values.sessionIdsInView.filter((sessionId) => !Object.hasOwn(known, sessionId))
+ // Read the range off the same snapshot the ids came from, before the debounce,
+ // so a page that empties mid-wait cannot leave the two disagreeing.
+ const range = pageLookupWindow(values.logs)
+ if (sessionIds.length === 0 || !range) {
+ return known
+ }
+ await breakpoint(reset ? FIRST_LOOKUP_DEBOUNCE_MS : INCREMENTAL_LOOKUP_DEBOUNCE_MS)
+
+ const response = await api.queryHogQL(
+ hogql`
+ SELECT properties.$session_id AS session_id, count() AS exceptions
+ FROM events
+ WHERE event = '$exception'
+ AND timestamp >= ${range.from}
+ AND timestamp <= ${range.to}
+ AND properties.$session_id IN ${sessionIds}
+ GROUP BY session_id
+ `,
+ { scene: 'Logs', productKey: 'logs', name: 'logs_session_error_counts' }
+ )
+ breakpoint()
+
+ // Every session looked up gets an entry, including the ones with no exceptions.
+ // That is what stops the next page re-asking about sessions already answered.
+ const counts: Record<string, number> = Object.fromEntries(
+ sessionIds.map((sessionId) => [sessionId, 0])
+ )
+ for (const [sessionId, exceptions] of (response.results ?? []) as [string, number][]) {
+ counts[sessionId] = Number(exceptions)
+ }
+ return { ...known, ...counts }
+ },
+ },
+ ],
+ })),
+
+ selectors({
+ showSessionErrors: [
+ (s) => [s.featureFlags],
+ (featureFlags: FeatureFlagsSet): boolean => !!featureFlags[FEATURE_FLAGS.LOGS_SESSION_ERROR_BADGES],
+ ],
+
+ sessionIdsInView: [
+ (s) => [s.logs, s.configuredSessionIdKeys],
+ (logs: ParsedLogMessage[], configuredSessionIdKeys: string[] | undefined): string[] => {
+ const sessionIds = logs
+ .map((log) =>
+ getSessionIdFromLogAttributes(log.attributes, log.resource_attributes, configuredSessionIdKeys)
+ )
+ .filter((sessionId): sessionId is string => !!sessionId)
+ return Array.from(new Set(sessionIds)).slice(0, MAX_SESSIONS_PER_LOOKUP)
+ },
+ ],
+ }),
+
+ listeners(({ actions, values }) => {
+ const lookUpNewSessions = (reset: boolean) => (): void => {
+ if (values.showSessionErrors) {
+ actions.loadSessionErrorCounts({ reset })
+ }
+ }
+ return {
+ fetchLogsSuccess: lookUpNewSessions(true),
+ fetchNextLogsPageSuccess: lookUpNewSessions(false),
+ setLogsSuccess: lookUpNewSessions(false),
+ }
+ }),
+])
diff --git a/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts b/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts
index baa0e7f86330..cae9a79f0cce 100644
--- a/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts
@@ -17,6 +17,7 @@ import type { PropertyFilterType, PropertyOperator } from '../../../../../fronte
import { LogsOrderBy, ParsedLogMessage } from '../../types'
import { attributeLookupExpression, LogsColumnConfig } from './config/columns'
import { logDetailsModalLogic } from './LogDetailsModal/logDetailsModalLogic'
+import { logsSessionErrorsLogic } from './logsSessionErrorsLogic'
import { logsViewerSettingsLogic } from './logsViewerSettingsLogic'
export interface VisibleLogsTimeRange {
@@ -65,6 +66,8 @@ function tryOpenLinkedLog(
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsViewerLogicValues {
isLogDetailsOpen: boolean // logDetailsModalLogic
+ sessionErrorCounts: Record<string, number> // logsSessionErrorsLogic
+ showSessionErrors: boolean // logsSessionErrorsLogic
columns: LogsColumnConfig[] // logsViewerConfigLogic
customColumns: string[] | undefined // logsViewerConfigLogic
orderBy: LogsOrderBy // logsViewerConfigLogic
@@ -286,6 +289,8 @@ export const logsViewerLogic = kea<logsViewerLogicType>([
['parsedLogs as logs', 'logsLoading'],
logsViewerConfigLogic({ id }),
['orderBy', 'columns', 'customColumns'],
+ logsSessionErrorsLogic({ id }),
+ ['sessionErrorCounts', 'showSessionErrors'],
],
actions: [
logsViewerSettingsLogic,
diff --git a/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx b/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx
index b10ee4f3bf83..ee50823b4d97 100644
--- a/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx
+++ b/products/logs/frontend/components/VirtualizedLogsList/VirtualizedLogsList.tsx
@@ -168,6 +168,7 @@ export function VirtualizedLogsList({
columns: columnConfigs,
selectedLogIds,
prettifiedLogIds,
+ showSessionErrors,
} = useValues(logsViewerLogic)
const {
togglePinLog,
@@ -224,7 +225,7 @@ export function VirtualizedLogsList({
// Move bounds range over movable columns only — pinned columns sort last and never swap
const movable = columnConfigs.filter((config) => !isPinnedColumn(config))
return [
- createControlsColumn({ dataSourceRef }),
+ createControlsColumn({ dataSourceRef, showSessionErrors }),
...columnConfigs.map((config) =>
createConfiguredColumn({
config,
@@ -247,6 +248,7 @@ export function VirtualizedLogsList({
moveColumn,
wrapBody,
prettifyJson,
+ showSessionErrors,
])
const minRowWidth = useMemo(() => getColumnsMinRowWidth(columns), [columns])
diff --git a/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge.stories.tsx b/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge.stories.tsx
new file mode 100644
index 000000000000..aa9bc14c9148
--- /dev/null
+++ b/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge.stories.tsx
@@ -0,0 +1,26 @@
+import { Meta, StoryObj } from '@storybook/react'
+
+import { SessionErrorsBadge } from './SessionErrorsBadge'
+
+const meta: Meta<typeof SessionErrorsBadge> = {
+ title: 'Scenes-App/Logs/SessionErrorsBadge',
+ component: SessionErrorsBadge,
+ args: {
+ errorCount: 3,
+ onClick: () => {},
+ },
+ parameters: {
+ layout: 'padded',
+ viewMode: 'story',
+ },
+ tags: ['autodocs'],
+}
+export default meta
+
+type Story = StoryObj<typeof SessionErrorsBadge>
+
+export const SeveralErrors: Story = {}
+
+export const OneError: Story = {
+ args: { errorCount: 1 },
+}
diff --git a/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge.tsx b/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge.tsx
new file mode 100644
index 000000000000..30ca8df9444e
--- /dev/null
+++ b/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge.tsx
@@ -0,0 +1,28 @@
+import { IconWarning } from '@posthog/icons'
+import { LemonButton, Tooltip } from '@posthog/lemon-ui'
+
+import { pluralize } from 'lib/utils/strings'
+
+export interface SessionErrorsBadgeProps {
+ errorCount: number
+ onClick: () => void
+}
+
+// The count answers the session, not the log line it sits on, so the copy says "in this session"
+// rather than implying the log caused the errors.
+export function SessionErrorsBadge({ errorCount, onClick }: SessionErrorsBadgeProps): JSX.Element {
+ return (
+ <Tooltip title={`${pluralize(errorCount, 'error')} in this session. Click to see them.`}>
+ <LemonButton
+ size="xsmall"
+ icon={<IconWarning className="text-danger" />}
+ data-attr="logs-row-session-errors"
+ onMouseDown={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation()
+ onClick()
+ }}
+ />
+ </Tooltip>
+ )
+}
diff --git a/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsCell.tsx b/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsCell.tsx
new file mode 100644
index 000000000000..d182a18c9ad6
--- /dev/null
+++ b/products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsCell.tsx
@@ -0,0 +1,38 @@
+import { useActions, useValues } from 'kea'
+
+import { logDetailsModalLogic } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/logDetailsModalLogic'
+import { logsViewerLogic } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'
+import { SessionErrorsBadge } from 'products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsBadge'
+import { SESSION_ERRORS_WIDTH } from 'products/logs/frontend/components/VirtualizedLogsList/layoutUtils'
+import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
+import { ParsedLogMessage } from 'products/logs/frontend/types'
+import { getSessionIdFromLogAttributes } from 'products/logs/frontend/utils'
+
+// The slot keeps its width on rows with no errors so the columns beside it stay aligned down the
+// page as counts arrive.
+export function SessionErrorsCell({ log }: { log: ParsedLogMessage }): JSX.Element {
+ const { sessionErrorCounts } = useValues(logsViewerLogic)
+ const { openLogDetails, setActiveTab } = useActions(logDetailsModalLogic)
+ const { configuredSessionIdKeys } = useValues(logsConfigLogic)
+
+ const sessionId = getSessionIdFromLogAttributes(log.attributes, log.resource_attributes, configuredSessionIdKeys)
+ // hasOwn, not a plain lookup: a session id that collides with an Object member would
+ // otherwise read back an inherited function instead of a count.
+ const errorCount = sessionId && Object.hasOwn(sessionErrorCounts, sessionId) ? sessionErrorCounts[sessionId] : 0
+
+ return (
+ <div className="flex items-center justify-center shrink-0" style={{ width: SESSION_ERRORS_WIDTH }}>
+ {errorCount > 0 && (
+ <SessionErrorsBadge
+ errorCount={errorCount}
+ onClick={() => {
+ // openLogDetails resets the drawer to its Details tab, so the tab selection
+ // has to follow it.
+ openLogDetails(log)
+ setActiveTab('related-errors')
+ }}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/products/logs/frontend/components/VirtualizedLogsList/columnDefinitions.tsx b/products/logs/frontend/components/VirtualizedLogsList/columnDefinitions.tsx
index bdd4167de9c5..c0a4fa1ec651 100644
--- a/products/logs/frontend/components/VirtualizedLogsList/columnDefinitions.tsx
+++ b/products/logs/frontend/components/VirtualizedLogsList/columnDefinitions.tsx
@@ -21,6 +21,7 @@ import {
import { logsViewerLogic } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'
import { AttributeCell } from 'products/logs/frontend/components/VirtualizedLogsList/cells/AttributeCell'
import { MessageCell } from 'products/logs/frontend/components/VirtualizedLogsList/cells/MessageCell'
+import { SessionErrorsCell } from 'products/logs/frontend/components/VirtualizedLogsList/cells/SessionErrorsCell'
import {
CHECKBOX_WIDTH,
DEFAULT_ATTRIBUTE_COLUMN_WIDTH,
@@ -31,6 +32,7 @@ import {
PATTERN_WIDTH,
PERSON_WIDTH,
RESIZER_HANDLE_WIDTH,
+ SESSION_ERRORS_WIDTH,
SESSION_WIDTH,
SEVERITY_WIDTH,
TIMESTAMP_WIDTH,
@@ -57,7 +59,7 @@ export const SEVERITY_BAR_COLORS: Record<LogMessage['severity_text'], string> =
// Cell components that read per-row state from kea — avoids baking
// frequently-changing state into column closures.
-function ControlsCell({ log }: { log: ParsedLogMessage }): JSX.Element {
+function ControlsCell({ log, showSessionErrors }: { log: ParsedLogMessage; showSessionErrors: boolean }): JSX.Element {
const { selectedLogIds, expandedLogIds } = useValues(logsViewerLogic)
const { toggleSelectLog, toggleExpandLog } = useActions(logsViewerLogic)
@@ -94,11 +96,18 @@ function ControlsCell({ log }: { log: ParsedLogMessage }): JSX.Element {
onClick={(e) => e.stopPropagation()}
/>
</div>
+ {showSessionErrors && <SessionErrorsCell log={log} />}
</div>
)
}
-function ControlsHeader({ dataSourceRef }: { dataSourceRef: RefObject<ParsedLogMessage[]> }): JSX.Element {
+function ControlsHeader({
+ dataSourceRef,
+ showSessionErrors,
+}: {
+ dataSourceRef: RefObject<ParsedLogMessage[]>
+ showSessionErrors: boolean
+}): JSX.Element {
const { selectedCount } = useValues(logsViewerLogic)
const { selectAll, clearSelection } = useActions(logsViewerLogic)
@@ -117,6 +126,7 @@ function ControlsHeader({ dataSourceRef }: { dataSourceRef: RefObject<ParsedLogM
/>
</div>
<div style={{ width: EXPAND_WIDTH, flexShrink: 0 }} />
+ {showSessionErrors && <div style={{ width: SESSION_ERRORS_WIDTH, flexShrink: 0 }} />}
</div>
)
}
@@ -196,12 +206,19 @@ function MessageColumnCell({
export function createControlsColumn(params: {
dataSourceRef: RefObject<ParsedLogMessage[]>
+ showSessionErrors: boolean
}): VirtualizedTableColumn<ParsedLogMessage> {
return {
key: 'controls',
- sizing: { type: 'fixed', width: SEVERITY_WIDTH + CHECKBOX_WIDTH + EXPAND_WIDTH },
- render: (log) => <ControlsCell log={log} />,
- renderHeader: () => <ControlsHeader dataSourceRef={params.dataSourceRef} />,
+ sizing: {
+ type: 'fixed',
+ width:
+ SEVERITY_WIDTH + CHECKBOX_WIDTH + EXPAND_WIDTH + (params.showSessionErrors ? SESSION_ERRORS_WIDTH : 0),
+ },
+ render: (log) => <ControlsCell log={log} showSessionErrors={params.showSessionErrors} />,
+ renderHeader: () => (
+ <ControlsHeader dataSourceRef={params.dataSourceRef} showSessionErrors={params.showSessionErrors} />
+ ),
}
}
diff --git a/products/logs/frontend/components/VirtualizedLogsList/layoutUtils.ts b/products/logs/frontend/components/VirtualizedLogsList/layoutUtils.ts
index e1cf354104f8..b64b6c5ada65 100644
--- a/products/logs/frontend/components/VirtualizedLogsList/layoutUtils.ts
+++ b/products/logs/frontend/components/VirtualizedLogsList/layoutUtils.ts
@@ -14,6 +14,7 @@ export const RESIZER_HANDLE_WIDTH = 16
export const SEVERITY_WIDTH = 8
export const CHECKBOX_WIDTH = 28
export const EXPAND_WIDTH = 28
+export const SESSION_ERRORS_WIDTH = 24
export const TIMESTAMP_WIDTH = 180
// A pattern is a whole message line with its variable parts masked, so it starts much wider
// than an attribute value.
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index 2a3560814d75..0c83b567f1ed 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -244,6 +244,17 @@ export function getSessionIdFromLogAttributes(
return getSessionIdWithKey(attributes, resourceAttributes, configuredKeys)?.value ?? null
}
+// Log timestamps are ISO strings, but some pipelines send epoch numbers instead. Shared so every
+// surface reading `LogMessage.timestamp` parses it the same way.
+export function parseLogTimestamp(timestamp: string): dayjs.Dayjs {
+ const epoch = Number(timestamp)
+ return Number.isNaN(epoch) ? dayjs(timestamp) : dayjs(epoch)
+}
+
+// How far either side of a log the Related errors lookup searches for exceptions in the same
+// session. Shared so the drawer's tab and the row badge that opens it agree on the range.
+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