: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): persist group by dimensions in the URL (#94222)
Jon McCallum5284088df644
diff --git a/products/logs/frontend/logsSceneLogic.test.ts b/products/logs/frontend/logsSceneLogic.test.tsindex d41e966aa2bb..6b6c2c6ae133 100644--- a/products/logs/frontend/logsSceneLogic.test.ts+++ b/products/logs/frontend/logsSceneLogic.test.ts@@ -5,6 +5,7 @@ import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'import { FilterLogicalOperator } from '~/types'+import { LogsViewerGroupBy } from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import {SERVICE_NAME_FILTER,SEVERITY_LEVEL_FILTER,@@ -412,4 +413,88 @@ describe('logsSceneLogic', () => {expect(router.values.searchParams).toHaveProperty('anomaliesService', 'checkout')})})++ describe('groupBys URL sync', () => {+ // The URL-sync guard clears on a macrotask (setTimeout(0)), so a write followed by a+ // router push in the same tick would see the guard still set and skip re-parsing. Flush+ // it between the two so each step exercises the real urlToAction path.+ const flushUrlSyncGuard = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 0))+ const GROUP_BYS: LogsViewerGroupBy[] = [+ { key: 'service.name', source: 'resource' },+ { key: 'severity_level', source: 'column' },+ ]++ it('parses groupBys from the URL', async () => {+ await expectLogic(logic, () => {+ router.actions.push('/logs', { groupBys: JSON.stringify(GROUP_BYS) })+ }).toFinishAllListeners()++ expect(logic.values.groupBys).toEqual(GROUP_BYS)+ })++ it.each([+ ['a dimension with no source', '[{"key":"only-a-key"}]'],+ ['an empty key', '[{"key":"","source":"resource"}]'],+ ['a column source the endpoint cannot group by', '[{"key":"service.name","source":"column"}]'],+ ])('leaves the live grouping alone for %s', async (_name, param) => {+ await expectLogic(logic, () => {+ logic.actions.setGroupBys(GROUP_BYS)+ }).toFinishAllListeners()+ await flushUrlSyncGuard()++ await expectLogic(logic, () => {+ router.actions.push('/logs', { groupBys: param })+ }).toFinishAllListeners()++ expect(logic.values.groupBys).toEqual(GROUP_BYS)+ })++ it('drops duplicate dimensions from the URL', async () => {+ await expectLogic(logic, () => {+ router.actions.push('/logs', { groupBys: JSON.stringify([...GROUP_BYS, GROUP_BYS[0]]) })+ }).toFinishAllListeners()++ expect(logic.values.groupBys).toEqual(GROUP_BYS)+ })++ it('caps groupBys from the URL at the dimension limit', async () => {+ const overCap: LogsViewerGroupBy[] = [+ { key: 'a', source: 'resource' },+ { key: 'b', source: 'resource' },+ { key: 'c', source: 'resource' },+ { key: 'd', source: 'resource' },+ { key: 'e', source: 'resource' },+ ]+ await expectLogic(logic, () => {+ router.actions.push('/logs', { groupBys: JSON.stringify(overCap) })+ }).toFinishAllListeners()++ expect(logic.values.groupBys).toEqual(overCap.slice(0, 4))+ })++ it('resets the grouping when the param is absent', async () => {+ await expectLogic(logic, () => {+ logic.actions.setGroupBys(GROUP_BYS)+ }).toFinishAllListeners()+ await flushUrlSyncGuard()++ await expectLogic(logic, () => {+ router.actions.push('/logs', {})+ }).toFinishAllListeners()++ expect(logic.values.groupBys).toEqual([])+ })++ it('syncs the grouping to the URL and drops the param when empty', async () => {+ await expectLogic(logic, () => {+ logic.actions.setGroupBys(GROUP_BYS)+ }).toFinishAllListeners()+ expect(router.values.searchParams.groupBys).toEqual(GROUP_BYS)++ await expectLogic(logic, () => {+ logic.actions.setGroupBys([])+ }).toFinishAllListeners()+ expect(router.values.searchParams).not.toHaveProperty('groupBys')+ })+ })})diff --git a/products/logs/frontend/logsSceneLogic.tsx b/products/logs/frontend/logsSceneLogic.tsxindex 58d1fdc553d5..d2165a225e93 100644--- a/products/logs/frontend/logsSceneLogic.tsx+++ b/products/logs/frontend/logsSceneLogic.tsx@@ -15,7 +15,9 @@ import {DEFAULT_ORDER_BY,DEFAULT_VIEW_MODE,logsViewerConfigLogic,+ LogsViewerGroupBy,LogsViewerViewMode,+ MAX_GROUP_BY_DIMENSIONS,} from 'products/logs/frontend/components/LogsViewer/config/logsViewerConfigLogic'import { LogsViewerFilters } from 'products/logs/frontend/components/LogsViewer/config/types'import {@@ -35,8 +37,10 @@ import {isValidSeverityLevel,logsViewerFiltersLogic,} from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'+import { GROUPABLE_COLUMN_KEYS } from 'products/logs/frontend/components/LogsViewer/groupBySource'import { logDetailsModalLogic } from 'products/logs/frontend/components/LogsViewer/LogDetailsModal/logDetailsModalLogic'import { logsViewerLogic } from 'products/logs/frontend/components/LogsViewer/logsViewerLogic'+import { LogsGroupBySourceEnumApi } from 'products/logs/frontend/generated/api.schemas'import { DEFAULT_ANOMALIES_DATE_RANGE, logsAnomaliesLogic } from 'products/logs/frontend/logsAnomaliesLogic'import type { DateRange, LogMessage } from '../../../frontend/src/queries/schema/schema-general'@@ -50,6 +54,48 @@ export const LOGS_SCENE_VIEWER_ID = `logs-scene-${window.POSTHOG_APP_CONTEXT?.cuconst VALID_VIEW_MODES: LogsViewerViewMode[] = ['logs', 'patterns', 'group']+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+// a bad link leaves the live grouping alone rather than clearing it. Caps at the API's dimension+// limit — the same guard the picker enforces — so a hand-edited URL can't build a combination the+// endpoint would reject.+const parseGroupBysParam = (raw: unknown): LogsViewerGroupBy[] | null => {+ let value: unknown = raw+ if (typeof value === 'string') {+ try {+ value = JSON.parse(value)+ } catch {+ return null+ }+ }+ if (!Array.isArray(value)) {+ return null+ }+ const parsed: LogsViewerGroupBy[] = []+ for (const entry of value) {+ if (typeof entry !== 'object' || entry === null) {+ return null+ }+ const { key, source } = entry as LogsViewerGroupBy+ if (typeof key !== 'string' || key === '' || !VALID_GROUP_BY_SOURCES.includes(source)) {+ return null+ }+ // A "column" dimension only groups by a top-level log field, so a link naming anything+ // else there is a combination the endpoint rejects.+ if (source === 'column' && !GROUPABLE_COLUMN_KEYS.has(key)) {+ return null+ }+ // Duplicates are dropped rather than rejected, matching what addGroupBy does with a+ // dimension already in the list.+ if (parsed.some((d) => d.key === key && d.source === source)) {+ continue+ }+ parsed.push({ key, source })+ }+ return parsed.slice(0, MAX_GROUP_BY_DIMENSIONS)+}+export type LogsSceneActiveTab =| 'viewer'| 'services'@@ -112,6 +158,7 @@ export interface logsSceneLogicValues {facetNameSearch: string // facetRailLogicanomaliesDateRange: DateRange // logsAnomaliesLogicanomaliesService: string | null // logsAnomaliesLogic+ groupBys: LogsViewerGroupBy[] // logsViewerConfigLogicorderBy: LogsOrderBy // logsViewerConfigLogicviewMode: LogsViewerViewMode // logsViewerConfigLogicinitialLogsLimit: number | null // logsViewerDataLogic@@ -143,6 +190,22 @@ export interface logsSceneLogicActions {pushToFilterHistory: (filters: LogsViewerFilters) => {filters: LogsViewerFilters} // logsFilterHistoryLogic+ addGroupBy: (groupBy: LogsViewerGroupBy) => {+ groupBy: LogsViewerGroupBy+ } // logsViewerConfigLogic+ removeGroupByAt: (index: number) => {+ index: number+ } // logsViewerConfigLogic+ replaceGroupByAt: (+ index: number,+ groupBy: LogsViewerGroupBy+ ) => {+ groupBy: LogsViewerGroupBy+ index: number+ } // logsViewerConfigLogic+ setGroupBys: (groupBys: LogsViewerGroupBy[]) => {+ groupBys: LogsViewerGroupBy[]+ } // logsViewerConfigLogicsetOrderBy: (orderBy: LogsOrderBy,source?: 'header' | 'toolbar' | undefined@@ -211,7 +274,7 @@ export const logsSceneLogic = kea<logsSceneLogicType>([logsFilterHistoryLogic({ id: LOGS_SCENE_VIEWER_ID }),['pushToFilterHistory'],logsViewerConfigLogic({ id: LOGS_SCENE_VIEWER_ID }),- ['setOrderBy', 'setViewMode'],+ ['setOrderBy', 'setViewMode', 'setGroupBys', 'addGroupBy', 'removeGroupByAt', 'replaceGroupByAt'],logsViewerDataLogic({ id: LOGS_SCENE_VIEWER_ID }),['setInitialLogsLimit', 'fetchLogsSuccess', 'handleQueryChange'],logsViewerLogic({ id: LOGS_SCENE_VIEWER_ID }),@@ -227,7 +290,7 @@ export const logsSceneLogic = kea<logsSceneLogicType>([logsViewerFiltersLogic({ id: LOGS_SCENE_VIEWER_ID }),['filters', 'utcDateRange'],logsViewerConfigLogic({ id: LOGS_SCENE_VIEWER_ID }),- ['orderBy', 'viewMode'],+ ['orderBy', 'viewMode', 'groupBys'],logsViewerDataLogic({ id: LOGS_SCENE_VIEWER_ID }),['initialLogsLimit'],logsViewerLogic({ id: LOGS_SCENE_VIEWER_ID }),@@ -347,6 +410,13 @@ export const logsSceneLogic = kea<logsSceneLogicType>([if (viewMode !== values.viewMode) {actions.setViewMode(viewMode)}+ // Grouping dimensions travel in the URL so a Group-lens link opens on the same+ // grouping. Absent param means no grouping (reset); a malformed one is left alone so+ // a broken link can't silently drop a live grouping.+ const groupBys = params.groupBys != null ? parseGroupBysParam(params.groupBys) : []+ if (groupBys && !equal(groupBys, values.groupBys)) {+ actions.setGroupBys(groupBys)+ }if (params.initialLogsLimit != null && +params.initialLogsLimit !== values.initialLogsLimit) {actions.setInitialLogsLimit(+params.initialLogsLimit)}@@ -498,6 +568,17 @@ export const logsSceneLogic = kea<logsSceneLogicType>([)}+ const syncGroupBys = (): ReturnType<typeof syncSearchParams> => {+ return withUrlSyncGuard(() =>+ syncSearchParams(router, (params: Params) => {+ // Empty grouping is the default, so it drops the param instead of pinning an+ // empty array into every copied URL.+ updateSearchParams(params, 'groupBys', values.groupBys, [])+ return params+ })+ )+ }+return {// initialLogsLimit is a one-shot override from "copy link to log" URLs.// It ensures the first fetch loads enough logs to include the linked log,@@ -510,6 +591,10 @@ export const logsSceneLogic = kea<logsSceneLogicType>([setViewMode: () => syncViewMode(),setAnomaliesService: () => syncAnomalies(),setAnomaliesDateRange: () => syncAnomalies(),+ setGroupBys: () => syncGroupBys(),+ addGroupBy: () => syncGroupBys(),+ removeGroupByAt: () => syncGroupBys(),+ replaceGroupByAt: () => syncGroupBys(),}}),