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): default patterns compare to preceding period and sync to url (#119438)

Jon McCallum96e790b5c419
diff --git a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
index 71c8f8d9de48..16c929658fbc 100644
--- a/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
+++ b/products/logs/frontend/components/LogsPatterns/logsPatternsLogic.test.ts
@@ -223,10 +223,7 @@ describe('logsPatternsLogic', () => {
logic.actions.setCompareEnabled(true)
}).toDispatchActions(['loadDiff', 'loadDiffSuccess'])
- expect(mockDiffCreate).toHaveBeenCalledWith(expect.any(String), {
- query: minedQuery,
- baselineDateRange: undefined, // 'lastWeek' delegates the -7d default to the backend
- })
+ expect(mockDiffCreate).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ query: minedQuery }))
expect(logic.values.diffResponse).toEqual(DIFF_RESPONSE)
mockDiffCreate.mockClear()
@@ -237,7 +234,7 @@ describe('logsPatternsLogic', () => {
expect(mockCreate).toHaveBeenCalledTimes(1) // only the original mount load
})
- it('preceding baseline is the same-length window ending where the current one starts', async () => {
+ it('defaults to the preceding baseline: the same-length window ending where the current one starts', async () => {
// Locks the window arithmetic: a drift here (wrong length, overlap, or gap) makes the
// "vs. preceding period" comparison silently wrong while still returning results.
mockDiffCreate.mockResolvedValue(DIFF_RESPONSE)
@@ -250,13 +247,6 @@ describe('logsPatternsLogic', () => {
})
logic.actions.setCompareEnabled(true)
await expectLogic(logic).toDispatchActions(['loadDiffSuccess'])
- expect(mockDiffCreate).toHaveBeenLastCalledWith(
- expect.any(String),
- expect.objectContaining({ baselineDateRange: undefined })
- )
-
- logic.actions.setBaselineMode('preceding')
- await expectLogic(logic).toDispatchActions(['loadDiffSuccess'])
expect(mockDiffCreate).toHaveBeenLastCalledWith(
expect.any(String),
expect.objectContaining({
@@ -266,6 +256,13 @@ describe('logsPatternsLogic', () => {
},
})
)
+
+ logic.actions.setBaselineMode('lastWeek')
+ await expectLogic(logic).toDispatchActions(['loadDiffSuccess'])
+ expect(mockDiffCreate).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ baselineDateRange: undefined }) // the backend applies the -7d default
+ )
})
it('compare armed before mount makes mounting load the diff, not the plain mine', async () => {
@@ -278,13 +275,13 @@ describe('logsPatternsLogic', () => {
configLogic.mount()
configLogic.actions.setCompareEnabled(true)
- configLogic.actions.setBaselineMode('preceding')
+ configLogic.actions.setBaselineMode('lastWeek')
configLogic.actions.setViewMode('patterns')
logic.mount()
await expectLogic(logic).toDispatchActions(['loadDiff', 'loadDiffSuccess'])
expect(mockCreate).not.toHaveBeenCalled()
- expect(logic.values.baselineMode).toBe('preceding')
+ expect(logic.values.baselineMode).toBe('lastWeek')
})
it('surfaces a load failure as patternsError and clears it on the next success', async () => {
diff --git a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
index a8a022b7919e..d9b49bf2b278 100644
--- a/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogsDisplayBar.tsx
@@ -224,8 +224,8 @@ const PatternsCompareControls = ({ id }: { id: string }): JSX.Element => {
value={baselineMode}
onChange={setBaselineMode}
options={[
- { value: 'lastWeek' as const, label: 'vs. same time last week' },
{ value: 'preceding' as const, label: 'vs. preceding period' },
+ { value: 'lastWeek' as const, label: 'vs. same time last week' },
]}
data-attr="logs-patterns-baseline-mode"
/>
diff --git a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
index af3b3f31cc5a..2f66e2196223 100644
--- a/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic.ts
@@ -35,6 +35,7 @@ export const DEFAULT_VIEW_MODE: LogsViewerViewMode = 'logs'
// to the same window one week earlier (absorbs daily/weekly cycles); 'preceding' compares
// against the window immediately before the current one (the post-deploy / spike comparison).
export type PatternsBaselineMode = 'lastWeek' | 'preceding'
+export const DEFAULT_BASELINE_MODE: PatternsBaselineMode = 'preceding'
export interface LogsViewerGroupBy {
key: string
@@ -237,7 +238,7 @@ export const logsViewerConfigLogic = kea<logsViewerConfigLogicType>([
},
],
baselineMode: [
- 'lastWeek' as PatternsBaselineMode,
+ DEFAULT_BASELINE_MODE as PatternsBaselineMode,
{
setBaselineMode: (_, { mode }) => mode,
},
diff --git a/products/logs/frontend/logsSceneLogic.test.ts b/products/logs/frontend/logsSceneLogic.test.ts
index 6b6c2c6ae133..126e8d4a8864 100644
--- a/products/logs/frontend/logsSceneLogic.test.ts
+++ b/products/logs/frontend/logsSceneLogic.test.ts
@@ -497,4 +497,36 @@ describe('logsSceneLogic', () => {
expect(router.values.searchParams).not.toHaveProperty('groupBys')
})
})
+
+ describe('patterns compare URL sync', () => {
+ it.each([
+ ['the preceding baseline', 'preceding', true, 'preceding'],
+ ['the last-week baseline', 'lastWeek', true, 'lastWeek'],
+ ['an unrecognised baseline leaves compare off', 'nonsense', false, 'preceding'],
+ ])('applies compare from the URL: %s', async (_, urlValue, expectedEnabled, expectedBaseline) => {
+ await expectLogic(logic, () => {
+ router.actions.push('/logs', { compare: urlValue })
+ }).toFinishAllListeners()
+
+ expect(logic.values.compareEnabled).toEqual(expectedEnabled)
+ expect(logic.values.baselineMode).toEqual(expectedBaseline)
+ })
+
+ it('writes the baseline while compare is on and drops the param when it is off', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setCompareEnabled(true)
+ }).toFinishAllListeners()
+ expect(router.values.searchParams.compare).toEqual('preceding')
+
+ await expectLogic(logic, () => {
+ logic.actions.setBaselineMode('lastWeek')
+ }).toFinishAllListeners()
+ expect(router.values.searchParams.compare).toEqual('lastWeek')
+
+ await expectLogic(logic, () => {
+ logic.actions.setCompareEnabled(false)
+ }).toFinishAllListeners()
+ expect(router.values.searchParams).not.toHaveProperty('compare')
+ })
+ })
})
diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsx
index d2165a225e93..365362dea7d1 100644
--- a/products/logs/frontend/logsSceneLogic.tsx
+++ b/products/logs/frontend/logsSceneLogic.tsx
@@ -18,6 +18,7 @@ import {
LogsViewerGroupBy,
LogsViewerViewMode,
MAX_GROUP_BY_DIMENSIONS,
+ PatternsBaselineMode,
} from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'
import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'
import {
@@ -54,6 +55,8 @@ export const LOGS_SCENE_VIEWER_ID = `logs-scene-${window.POSTHOG_APP_CONTEXT?.cu
const VALID_VIEW_MODES: LogsViewerViewMode[] = ['logs', 'patterns', 'group']
+const VALID_BASELINE_MODES: PatternsBaselineMode[] = ['preceding', 'lastWeek']
+
const VALID_GROUP_BY_SOURCES = Object.values(LogsGroupBySourceEnumApi)
// A groupBys URL param is a JSON array of { key, source }. Returns null on any malformed shape so
@@ -158,6 +161,8 @@ export interface logsSceneLogicValues {
facetNameSearch: string // facetRailLogic
anomaliesDateRange: DateRange // logsAnomaliesLogic
anomaliesService: string | null // logsAnomaliesLogic
+ baselineMode: PatternsBaselineMode // logsViewerConfigLogic
+ compareEnabled: boolean // logsViewerConfigLogic
groupBys: LogsViewerGroupBy[] // logsViewerConfigLogic
orderBy: LogsOrderBy // logsViewerConfigLogic
viewMode: LogsViewerViewMode // logsViewerConfigLogic
@@ -203,6 +208,12 @@ export interface logsSceneLogicActions {
groupBy: LogsViewerGroupBy
index: number
} // logsViewerConfigLogic
+ setBaselineMode: (mode: PatternsBaselineMode) => {
+ mode: PatternsBaselineMode
+ } // logsViewerConfigLogic
+ setCompareEnabled: (enabled: boolean) => {
+ enabled: boolean
+ } // logsViewerConfigLogic
setGroupBys: (groupBys: LogsViewerGroupBy[]) => {
groupBys: LogsViewerGroupBy[]
} // logsViewerConfigLogic
@@ -274,7 +285,16 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
logsFilterHistoryLogic({ id: LOGS_SCENE_VIEWER_ID }),
['pushToFilterHistory'],
logsViewerConfigLogic({ id: LOGS_SCENE_VIEWER_ID }),
- ['setOrderBy', 'setViewMode', 'setGroupBys', 'addGroupBy', 'removeGroupByAt', 'replaceGroupByAt'],
+ [
+ 'setOrderBy',
+ 'setViewMode',
+ 'setGroupBys',
+ 'addGroupBy',
+ 'removeGroupByAt',
+ 'replaceGroupByAt',
+ 'setCompareEnabled',
+ 'setBaselineMode',
+ ],
logsViewerDataLogic({ id: LOGS_SCENE_VIEWER_ID }),
['setInitialLogsLimit', 'fetchLogsSuccess', 'handleQueryChange'],
logsViewerLogic({ id: LOGS_SCENE_VIEWER_ID }),
@@ -290,7 +310,7 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
logsViewerFiltersLogic({ id: LOGS_SCENE_VIEWER_ID }),
['filters', 'utcDateRange'],
logsViewerConfigLogic({ id: LOGS_SCENE_VIEWER_ID }),
- ['orderBy', 'viewMode', 'groupBys'],
+ ['orderBy', 'viewMode', 'groupBys', 'compareEnabled', 'baselineMode'],
logsViewerDataLogic({ id: LOGS_SCENE_VIEWER_ID }),
['initialLogsLimit'],
logsViewerLogic({ id: LOGS_SCENE_VIEWER_ID }),
@@ -302,6 +322,18 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
],
})),
urlToAction(({ actions, values, cache }) => {
+ // An absent or unrecognised param turns compare off. Set the baseline first, so that
+ // turning compare on loads one diff, against the linked baseline.
+ const applyCompareParam = (raw: unknown): void => {
+ const baseline = VALID_BASELINE_MODES.find((mode) => mode === raw) ?? null
+ if (baseline && baseline !== values.baselineMode) {
+ actions.setBaselineMode(baseline)
+ }
+ if (!!baseline !== values.compareEnabled) {
+ actions.setCompareEnabled(!!baseline)
+ }
+ }
+
const urlToAction = (_: any, params: Params): void => {
if (cache.isSyncingUrl) {
return
@@ -417,6 +449,7 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
if (groupBys && !equal(groupBys, values.groupBys)) {
actions.setGroupBys(groupBys)
}
+ applyCompareParam(params.compare)
if (params.initialLogsLimit != null && +params.initialLogsLimit !== values.initialLogsLimit) {
actions.setInitialLogsLimit(+params.initialLogsLimit)
}
@@ -568,6 +601,15 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
)
}
+ const syncCompare = (): ReturnType<typeof syncSearchParams> => {
+ return withUrlSyncGuard(() =>
+ syncSearchParams(router, (params: Params) => {
+ updateSearchParams(params, 'compare', values.compareEnabled ? values.baselineMode : null, null)
+ return params
+ })
+ )
+ }
+
const syncGroupBys = (): ReturnType<typeof syncSearchParams> => {
return withUrlSyncGuard(() =>
syncSearchParams(router, (params: Params) => {
@@ -595,6 +637,8 @@ export const logsSceneLogic = kea<logsSceneLogicType>([
addGroupBy: () => syncGroupBys(),
removeGroupByAt: () => syncGroupBys(),
replaceGroupByAt: () => syncGroupBys(),
+ setCompareEnabled: () => syncCompare(),
+ setBaselineMode: () => syncCompare(),
}
}),