: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(logs): add patterns mode to the logs viewer (#66341)
Jon McCallumb7d94b5a93c0
diff --git a/products/logs/frontend/LogsScene.tsx b/products/logs/frontend/LogsScene.tsxindex be784a0aacff..4e3e1142fba5 100644--- a/products/logs/frontend/LogsScene.tsx+++ b/products/logs/frontend/LogsScene.tsx@@ -15,7 +15,6 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'import { ProductKey } from '~/queries/schema/schema-general'import { LogsAlertingSection } from 'products/logs/frontend/components/LogsAlerting/LogsAlertingSection'-import { LogsPatterns } from 'products/logs/frontend/components/LogsPatterns/LogsPatterns'import { LogsServices } from 'products/logs/frontend/components/LogsServices/LogsServices'import { LogsSqlEditor } from 'products/logs/frontend/components/LogsSqlEditor/LogsSqlEditor'import { LogsViewer } from 'products/logs/frontend/components/LogsViewer'@@ -91,14 +90,12 @@ const LogsSceneTabbedContent = (): JSX.Element => {const { activeTab } = useValues(logsSceneLogic)const { setActiveTab } = useActions(logsSceneLogic)const { hasLogs, teamHasLogsCheckFailed } = useValues(logsIngestionLogic)- const showPatternsView = useFeatureFlag('LOGS_PATTERNS_VIEW')const showServicesView = useFeatureFlag('LOGS_SERVICES_VIEW')const showAlerting = useFeatureFlag('LOGS_ALERTING')const showSqlView = useFeatureFlag('LOGS_SQL_VIEW')const tabs: { key: LogsSceneActiveTab; label: string }[] = [{ key: 'viewer', label: 'Viewer' },- ...(showPatternsView ? [{ key: 'patterns' as const, label: 'Patterns' }] : []),...(showServicesView ? [{ key: 'services' as const, label: 'Services' }] : []),...(showAlerting ? [{ key: 'alerts' as const, label: 'Alerts' }] : []),...(showSqlView ? [{ key: 'sql' as const, label: 'SQL' }] : []),@@ -145,7 +142,6 @@ const LogsSceneTabbedContent = (): JSX.Element => {</div></LogsSetupPrompt>)}- {activeTab === 'patterns' && showPatternsView && <LogsPatterns />}{activeTab === 'services' && showServicesView && (<><LogsServices />diff --git a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsxindex f8ac95ea75c1..f308c79346d5 100644--- a/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx+++ b/products/logs/frontend/components/LogsPatterns/LogsPatterns.tsx@@ -1,9 +1,98 @@-export function LogsPatterns(): JSX.Element {- // Scaffold only — the mined-patterns table and its logic land in a follow-up.+import { useValues } from 'kea'++import { LemonTable, LemonTag } from '@posthog/lemon-ui'+import type { LemonTableColumns } from '@posthog/lemon-ui'++import { TZLabel } from 'lib/components/TZLabel'+import { humanFriendlyNumber } from 'lib/utils/numbers'++import type { _LogPatternApi } from 'products/logs/frontend/generated/api.schemas'++import { logsPatternsLogic } from './logsPatternsLogic'++// Highlight Drain's `<*>` wildcard and the masking placeholders (`<ip>`, `<num>`, `<uuid>`,+// `<hex>`, …) the runner emits — see _MASKING_INSTRUCTIONS in+// products/logs/backend/log_patterns.py for the authoritative token vocabulary.+const PATTERN_TOKEN = String.raw`<\*>|<[a-z][a-z0-9]*>`+const PATTERN_TOKEN_SPLIT = new RegExp(`(${PATTERN_TOKEN})`, 'g')+const PATTERN_TOKEN_MATCH = new RegExp(`^(${PATTERN_TOKEN})$`)++function renderPatternTemplate(pattern: string): JSX.Element {return (- <div className="flex flex-col gap-2 py-2 flex-1 min-h-0" data-attr="logs-patterns">- <h3 className="m-0">Patterns</h3>- <p className="text-muted m-0">Log pattern mining will appear here.</p>+ <span className="font-mono text-xs break-all">+ {pattern.split(PATTERN_TOKEN_SPLIT).map((part, i) => (+ <span key={i} className={PATTERN_TOKEN_MATCH.test(part) ? 'text-accent font-semibold' : undefined}>+ {part}+ </span>+ ))}+ </span>+ )+}++export function LogsPatterns({ id }: { id: string }): JSX.Element {+ const { patterns, patternsResponseLoading } = useValues(logsPatternsLogic({ id }))++ const columns: LemonTableColumns<_LogPatternApi> = [+ {+ title: 'Pattern',+ dataIndex: 'pattern',+ render: (_, row) => renderPatternTemplate(row.pattern),+ },+ {+ title: 'Count',+ dataIndex: 'count',+ render: (_, row) => humanFriendlyNumber(row.count),+ sorter: (a, b) => a.count - b.count,+ align: 'right',+ },+ {+ title: 'Share',+ dataIndex: 'volume_share_pct',+ render: (_, row) => `${row.volume_share_pct.toFixed(1)}%`,+ sorter: (a, b) => a.volume_share_pct - b.volume_share_pct,+ align: 'right',+ },+ {+ title: 'Errors',+ dataIndex: 'error_count',+ render: (_, row) =>+ row.error_count > 0 ? (+ <LemonTag type="danger">{humanFriendlyNumber(row.error_count)}</LemonTag>+ ) : (+ <span className="text-muted">0</span>+ ),+ sorter: (a, b) => a.error_count - b.error_count,+ align: 'right',+ },+ {+ title: 'Services',+ key: 'services',+ render: (_, row) =>+ row.services.length ? (+ <span className="text-muted">{row.services.join(', ')}</span>+ ) : (+ <span className="text-muted">-</span>+ ),+ },+ {+ title: 'Last seen',+ dataIndex: 'last_seen',+ render: (_, row) => <TZLabel time={row.last_seen} />,+ sorter: (a, b) => (a.last_seen < b.last_seen ? -1 : a.last_seen > b.last_seen ? 1 : 0),+ },+ ]++ return (+ <div className="flex-1 min-h-0 overflow-auto" data-attr="logs-patterns">+ <LemonTable+ columns={columns}+ dataSource={patterns}+ loading={patternsResponseLoading}+ defaultSorting={{ columnKey: 'count', order: -1 }}+ emptyState="No patterns found for the current filters"+ rowKey="pattern"+ size="small"+ /></div>)}diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.tsnew file mode 100644index 000000000000..5b774fc2e4cf--- /dev/null+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts@@ -0,0 +1,114 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'+import { FilterLogicalOperator, PropertyFilterType, PropertyOperator, UniversalFiltersGroup } from '~/types'++import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'+import { logsPatternsCreate } from 'products/logs/frontend/generated/api'+import type { _LogsPatternsResponseApi } from 'products/logs/frontend/generated/api.schemas'++import { logsPatternsLogic } from './logsPatternsLogic'++jest.mock('products/logs/frontend/generated/api', () => ({+ __esModule: true,+ logsPatternsCreate: jest.fn(),+}))++const mockCreate = logsPatternsCreate as jest.MockedFunction<typeof logsPatternsCreate>++const ID = 'test-viewer'++const RESPONSE: _LogsPatternsResponseApi = {+ patterns: [+ {+ pattern: 'User <*> not found',+ count: 3,+ volume_share_pct: 75,+ error_count: 3,+ first_seen: '2026-06-23T12:00:00+00:00',+ last_seen: '2026-06-23T12:05:00+00:00',+ examples: [],+ services: ['auth'],+ },+ ],+ scanned_count: 3,+ total_count: 3,+ sampled: false,+}++describe('logsPatternsLogic', () => {+ let logic: ReturnType<typeof logsPatternsLogic.build>+ let filtersLogic: ReturnType<typeof logsViewerFiltersLogic.build>++ beforeEach(() => {+ initKeaTests()+ jest.clearAllMocks()+ mockCreate.mockResolvedValue(RESPONSE)+ filtersLogic = logsViewerFiltersLogic({ id: ID })+ filtersLogic.mount()+ logic = logsPatternsLogic({ id: ID })+ })++ it('loads patterns on mount from the shared viewer filters', async () => {+ logic.mount()++ await expectLogic(logic)+ .toDispatchActions(['loadPatterns', 'loadPatternsSuccess'])+ .toMatchValues({ patterns: RESPONSE.patterns })++ expect(mockCreate).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ query: expect.objectContaining({ severityLevels: [], serviceNames: [] }),+ })+ )+ })++ it('reloads when a shared filter changes', async () => {+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadPatternsSuccess'])+ mockCreate.mockClear()++ await expectLogic(logic, () => {+ filtersLogic.actions.setSeverityLevels(['error'])+ }).toDispatchActions(['setSeverityLevels', 'loadPatterns', 'loadPatternsSuccess'])++ expect(mockCreate).toHaveBeenLastCalledWith(+ expect.any(String),+ expect.objectContaining({ query: expect.objectContaining({ severityLevels: ['error'] }) })+ )+ })++ it('scopes mining to the embedding viewer pinned filters', async () => {+ // A scoped embedded viewer (e.g. person/trace logs) pins a filter so Patterns mode+ // can't mine project-wide logs — assert it reaches the query via `queryFilterGroup`.+ const pinnedFilters: UniversalFiltersGroup = {+ type: FilterLogicalOperator.And,+ values: [+ {+ key: 'distinct_id',+ value: ['user-123'],+ operator: PropertyOperator.Exact,+ type: PropertyFilterType.LogAttribute,+ },+ ],+ }+ const scopedFiltersLogic = logsViewerFiltersLogic({ id: 'scoped-viewer', pinnedFilters })+ scopedFiltersLogic.mount()+ const scopedLogic = logsPatternsLogic({ id: 'scoped-viewer' })+ scopedLogic.mount()++ await expectLogic(scopedLogic).toDispatchActions(['loadPatternsSuccess'])++ expect(mockCreate).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ query: expect.objectContaining({+ filterGroup: expect.objectContaining({+ values: [expect.objectContaining({ values: pinnedFilters.values })],+ }),+ }),+ })+ )+ })+})diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.tsnew file mode 100644index 000000000000..44265a2c4f8b--- /dev/null+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.ts@@ -0,0 +1,106 @@+import { afterMount, connect, kea, key, listeners, path, props, selectors } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'+import { logsPatternsCreate } from 'products/logs/frontend/generated/api'+import type {+ _LogPatternApi,+ _LogPropertyFilterApi,+ _LogsPatternsResponseApi,+} from 'products/logs/frontend/generated/api.schemas'++import type { logsPatternsLogicType } from './logsPatternsLogicType'++export interface LogsPatternsLogicProps {+ id: string+}++const EMPTY_RESPONSE: _LogsPatternsResponseApi = {+ patterns: [],+ scanned_count: 0,+ total_count: 0,+ sampled: false,+}++// Keyed by the Viewer's `id`: the logic mounts only while the Patterns mode is active (the+// Viewer conditionally renders <LogsPatterns/>), so loading on mount + reloading on the+// shared filter actions never runs the heavier patterns query while the user is in Logs mode.+export const logsPatternsLogic = kea<logsPatternsLogicType>([+ props({ id: 'default' } as LogsPatternsLogicProps),+ key((props) => props.id),+ path((key) => ['products', 'logs', 'frontend', 'components', 'LogsPatterns', 'logsPatternsLogic', key]),++ connect((props: LogsPatternsLogicProps) => ({+ values: [+ teamLogic,+ ['currentTeamId'],+ logsViewerFiltersLogic({ id: props.id }),+ ['filters', 'utcDateRange', 'queryFilterGroup'],+ ],+ actions: [+ logsViewerFiltersLogic({ id: props.id }),+ [+ 'setDateRange',+ 'zoomDateRange',+ 'setSeverityLevels',+ 'setServiceNames',+ 'setSearchTerm',+ 'setFilters',+ 'setFilterGroup',+ 'setPinnedFilters',+ ],+ ],+ })),++ loaders(({ values }) => ({+ patternsResponse: [+ EMPTY_RESPONSE,+ {+ loadPatterns: async (debounceMs: number = 0, breakpoint) => {+ await breakpoint(debounceMs)+ return await logsPatternsCreate(String(values.currentTeamId), {+ query: {+ dateRange: values.utcDateRange,+ severityLevels: values.filters.severityLevels,+ serviceNames: values.filters.serviceNames,+ searchTerm: values.filters.searchTerm || undefined,+ // Scope mining to the same filters the Logs/sparkline queries use —+ // `queryFilterGroup` folds in any pinned filters from an embedded viewer+ // (person/trace logs), so a scoped viewer can't mine project-wide patterns.+ filterGroup: values.queryFilterGroup as unknown as _LogPropertyFilterApi[],+ },+ })+ },+ },+ ],+ })),++ selectors({+ patterns: [+ (s) => [s.patternsResponse],+ (response: _LogsPatternsResponseApi): _LogPatternApi[] => response.patterns,+ ],+ }),++ listeners(({ actions }) => {+ // Debounced so a multi-filter change or search typing collapses into one request —+ // kea's breakpoint cancels superseded loads before the fetch fires.+ const reload = (): void => actions.loadPatterns(300)+ return {+ setDateRange: reload,+ zoomDateRange: reload,+ setSeverityLevels: reload,+ setServiceNames: reload,+ setSearchTerm: reload,+ setFilters: reload,+ setFilterGroup: reload,+ setPinnedFilters: reload,+ }+ }),++ afterMount(({ actions }) => {+ actions.loadPatterns()+ }),+])diff --git a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx b/products/logs/frontend/components/LogsViewer/LogsViewer.tsxindex dd90f197edcc..cd9aca725114 100644--- a/products/logs/frontend/components/LogsViewer/LogsViewer.tsx+++ b/products/logs/frontend/components/LogsViewer/LogsViewer.tsx@@ -1,6 +1,8 @@import { BindLogic, useActions, useValues } from 'kea'import { useCallback, useEffect, useRef } from 'react'+import { LemonSegmentedButton } from '@posthog/lemon-ui'+import { TZLabelProps } from 'lib/components/TZLabel'import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'@@ -8,6 +10,7 @@ import { useKeyboardHotkeys } from 'lib/hooks/useKeyboardHotkeys'import { SceneDivider } from '~/layout/scenes/components/SceneDivider'import { UniversalFiltersGroup } from '~/types'+import { LogsPatterns } from 'products/logs/frontend/components/LogsPatterns/LogsPatterns'import { logsViewerConfigLogic } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic'@@ -107,14 +110,17 @@ function LogsViewerContent({clearSelection,togglePrettifyLog,} = useActions(logsViewerLogic)- const { orderBy, sparklineBreakdownBy, sparklineCollapsed, facetRailCollapsed } = useValues(logsViewerConfigLogic)- const { setOrderBy, setSparklineBreakdownBy, toggleSparklineCollapsed } = useActions(logsViewerConfigLogic)+ const { orderBy, sparklineBreakdownBy, sparklineCollapsed, facetRailCollapsed, viewMode } =+ useValues(logsViewerConfigLogic)+ const { setOrderBy, setSparklineBreakdownBy, toggleSparklineCollapsed, setViewMode } =+ useActions(logsViewerConfigLogic)const { logsLoading, parsedLogs, sparklineData, sparklineLoading, hasMoreLogsToLoad, totalLogsMatchingFilters } =useValues(logsViewerDataLogic)const { runQuery, fetchNextLogsPage } = useActions(logsViewerDataLogic)const { setDateRange, zoomDateRange } = useActions(logsViewerFiltersLogic)const { openLogsViewerModal } = useActions(logsViewerModalLogic)const showFacetRail = useFeatureFlag('LOGS_FACET_RAIL')+ const showPatternsView = useFeatureFlag('LOGS_PATTERNS_VIEW')const { cellScrollLefts } = useValues(virtualizedLogsListLogic({ id }))const { setCellScrollLeft } = useActions(virtualizedLogsListLogic({ id }))const messageScrollLeft = cellScrollLefts['message'] ?? 0@@ -340,6 +346,35 @@ function LogsViewerContent({</>)+ // Patterns is a mode of the Viewer, not a separate tab: it swaps only the results region+ // and reuses the same filter bar / FacetRail / date range (shared via logsViewerFiltersLogic).+ // Gate on the flag too, so the patterns query stays unreachable when the flag is off regardless+ // of the (non-persisted) viewMode state.+ const inPatternsMode = showPatternsView && viewMode === 'patterns'+ const resultsRegion = inPatternsMode ? <LogsPatterns id={id} /> : logList++ const modeToggle = showPatternsView ? (+ <LemonSegmentedButton+ size="small"+ value={viewMode}+ onChange={setViewMode}+ options={[+ { value: 'logs', label: 'Logs' },+ { value: 'patterns', label: 'Patterns' },+ ]}+ />+ ) : null++ // Both layouts share the same results column; only the bar above it differs. Keeping the+ // mode toggle + "patterns hides the bar" rule in one place avoids drift between the branches.+ const resultsColumn = (bar: JSX.Element): JSX.Element => (+ <>+ {modeToggle}+ {!inPatternsMode && bar}+ {resultsRegion}+ </>+ )+if (showFacetRail) {// Three-tier layout: query bar (ask a question) above the sparkline, the sparkline, then a// row of [facet rail | display bar (operate on the data) + the log lists].@@ -350,8 +385,7 @@ function LogsViewerContent({<div className="flex flex-row gap-2 flex-1 min-h-0">{!facetRailCollapsed && <FacetRail id={id} />}<div className="flex flex-col gap-2 flex-1 min-w-0">- <LogsDisplayBar {...toolbarProps} />- {logList}+ {resultsColumn(<LogsDisplayBar {...toolbarProps} />)}</div></div><LogDetailsModal timezone={timezone} />@@ -363,8 +397,7 @@ function LogsViewerContent({<div className="flex flex-col gap-2 h-full" data-attr="logs-viewer">{sparklineSection}{filterBar}- <LogsViewerToolbar {...toolbarProps} />- {logList}+ {resultsColumn(<LogsViewerToolbar {...toolbarProps} />)}<LogDetailsModal timezone={timezone} /></div>)diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.tsindex 5cd70b7a4e2d..34e3ce5fc813 100644--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts@@ -22,6 +22,9 @@ export const DEFAULT_SPARKLINE_BREAKDOWN_BY: LogsSparklineBreakdownBy = 'severitexport const DEFAULT_ORDER_BY: LogsOrderBy = 'latest'+export type LogsViewerViewMode = 'logs' | 'patterns'+export const DEFAULT_VIEW_MODE: LogsViewerViewMode = 'logs'+export interface LogsViewerConfigProps {id: string}@@ -41,6 +44,7 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([setOrderBy: (orderBy: LogsOrderBy, source: 'header' | 'toolbar' = 'toolbar') => ({ orderBy, source }),toggleSparklineCollapsed: true,setFacetRailCollapsed: (facetRailCollapsed: boolean) => ({ facetRailCollapsed }),+ setViewMode: (viewMode: LogsViewerViewMode) => ({ viewMode }),}),reducers({@@ -81,6 +85,13 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([setOrderBy: (_, { orderBy }) => orderBy,},],+ // Not persisted — the Viewer always opens in Logs mode; Patterns is an explicit switch.+ viewMode: [+ DEFAULT_VIEW_MODE as LogsViewerViewMode,+ {+ setViewMode: (_, { viewMode }) => viewMode,+ },+ ],}),selectors({diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsxindex f44333581ebd..ee1f328150bc 100644--- a/products/logs/frontend/logsSceneLogic.tsx+++ b/products/logs/frontend/logsSceneLogic.tsx@@ -40,8 +40,8 @@ export const getLogsSqlEditorTabId = (id: string): string => `logs-sql-editor-${// A static id would persist across projects in the same browser, leaking one project's pinned log payloads into another.export const LOGS_SCENE_VIEWER_ID = `logs-scene-${window.POSTHOG_APP_CONTEXT?.current_team?.id ?? 'unknown'}`-export type LogsSceneActiveTab = 'viewer' | 'patterns' | 'services' | 'alerts' | 'sql' | 'configuration'-const VALID_ACTIVE_TABS: LogsSceneActiveTab[] = ['viewer', 'patterns', 'services', 'alerts', 'sql', 'configuration']+export type LogsSceneActiveTab = 'viewer' | 'services' | 'alerts' | 'sql' | 'configuration'+const VALID_ACTIVE_TABS: LogsSceneActiveTab[] = ['viewer', 'services', 'alerts', 'sql', 'configuration']export const DEFAULT_ACTIVE_TAB: LogsSceneActiveTab = 'viewer'const resolveActiveTabFromParams = (params: Params): LogsSceneActiveTab | null => {