: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 typed column model, registry, and legacy-config migration (#69233)
Jon McCallum7cee4ffc6fbd
diff --git a/products/logs/frontend/components/LogsViewer/config/columns.test.ts b/products/logs/frontend/components/LogsViewer/config/columns.test.tsnew file mode 100644index 000000000000..dfb6d27c1cfb--- /dev/null+++ b/products/logs/frontend/components/LogsViewer/config/columns.test.ts@@ -0,0 +1,56 @@+import { AttributeColumnConfig } from 'products/logs/frontend/types'++import { columnsToCustomColumns, LogsColumnConfig, migrateAttributeColumns } from './columns'++describe('logs column config', () => {+ describe('columnsToCustomColumns', () => {+ it('lowers only custom columns, in order, and never sends built-ins', () => {+ const columns: LogsColumnConfig[] = [+ { id: 'timestamp', type: 'timestamp' },+ { id: 'a', type: 'custom', expression: 'attributes.http.url' },+ { id: 'level', type: 'level' },+ { id: 'b', type: 'custom', expression: ' upper(level) ' },+ { id: 'message', type: 'message' },+ ]+ expect(columnsToCustomColumns(columns)).toEqual(['attributes.http.url', 'upper(level)'])+ })++ it.each<[string, LogsColumnConfig[]]>([+ ['no columns', []],+ ['built-ins only', [{ id: 'timestamp', type: 'timestamp' }]],+ ['custom with blank expression', [{ id: 'x', type: 'custom', expression: ' ' }]],+ ['custom with no expression', [{ id: 'x', type: 'custom' }]],+ ])('returns undefined (not []) for %s, keeping query payloads cache-identical', (_, columns) => {+ expect(columnsToCustomColumns(columns)).toBeUndefined()+ })+ })++ describe('migrateAttributeColumns', () => {+ it('orders by the legacy order field and preserves width', () => {+ // Insertion order deliberately disagrees with the order field+ const legacy: Record<string, AttributeColumnConfig> = {+ 'k8s.pod': { order: 1, width: 240 },+ 'http.status_code': { order: 0 },+ }+ const migrated = migrateAttributeColumns(legacy)++ expect(migrated.map((c) => c.name)).toEqual(['http.status_code', 'k8s.pod'])+ expect(migrated.map((c) => c.type)).toEqual(['custom', 'custom'])+ expect(migrated[0].width).toBeUndefined()+ expect(migrated[1].width).toBe(240)+ expect(new Set(migrated.map((c) => c.id)).size).toBe(2)+ })++ it('emits an expression that reads both maps, matching the legacy attributes-then-resource fallback', () => {+ const [migrated] = migrateAttributeColumns({ 'service.version': { order: 0 } })+ expect(migrated.expression).toBe(+ "if(mapContains(attributes, 'service.version'), attributes['service.version'], resource_attributes['service.version'])"+ )+ })++ it('escapes quotes and backslashes so keys cannot break out of the expression string', () => {+ const [migrated] = migrateAttributeColumns({ "we'ird\\key": { order: 0 } })+ expect(migrated.expression).toContain("we\\'ird\\\\key")+ })+ })+})diff --git a/products/logs/frontend/components/LogsViewer/config/columns.ts b/products/logs/frontend/components/LogsViewer/config/columns.tsnew file mode 100644index 000000000000..21d6279c134f--- /dev/null+++ b/products/logs/frontend/components/LogsViewer/config/columns.ts@@ -0,0 +1,90 @@+import { uuid } from 'lib/utils/dom'++import { LogsQuery } from '~/queries/schema/schema-general'++import { AttributeColumnConfig, ParsedLogMessage } from 'products/logs/frontend/types'++export type LogsColumnType = 'timestamp' | 'level' | 'source' | 'trace_id' | 'span_id' | 'message' | 'custom'++export interface LogsColumnConfig {+ /** Stable identity for list operations (React keys, reorder). Never sent to the server. */+ id: string+ type: LogsColumnType+ /** Header label override. Defaults to the registry label (built-ins) or the expression (custom). */+ name?: string+ /**+ * Only meaningful for `type: 'custom'`: a source-prefixed shorthand (`attributes.<key>`,+ * `resource_attributes.<key>`, `body.<json.path>`) or a scalar HogQL expression, sent+ * verbatim in `LogsQuery.customColumns`. Column order is the array index.+ */+ expression?: string+ width?: number+}++interface BuiltInColumnDef {+ label: string+ getValue: (log: ParsedLogMessage) => string+}++// Built-in column types resolve client-side from fields every log row already carries —+// they never hit the wire. `source` has no top-level row field; the service name rides in+// resource_attributes per OTel convention.+export const LOGS_COLUMN_REGISTRY: Record<Exclude<LogsColumnType, 'custom'>, BuiltInColumnDef> = {+ timestamp: { label: 'Timestamp', getValue: (log) => log.timestamp },+ level: { label: 'Level', getValue: (log) => log.severity_text },+ source: { label: 'Source', getValue: (log) => String(log.resource_attributes?.['service.name'] ?? '') },+ trace_id: { label: 'Trace ID', getValue: (log) => log.trace_id },+ span_id: { label: 'Span ID', getValue: (log) => log.span_id },+ message: { label: 'Message', getValue: (log) => log.body },+}++// Mirrors today's default table (timestamp + message) so the rendering cutover is invisible+// for users with no column customization.+export const DEFAULT_LOGS_COLUMNS: LogsColumnConfig[] = [+ { id: 'timestamp', type: 'timestamp' },+ { id: 'message', type: 'message' },+]++export function columnLabel(column: LogsColumnConfig): string {+ if (column.name) {+ return column.name+ }+ return column.type === 'custom' ? (column.expression ?? '') : LOGS_COLUMN_REGISTRY[column.type].label+}++/** Lower a column list to the `LogsQuery.customColumns` wire value. Built-ins never hit the wire. */+export function columnsToCustomColumns(columns: LogsColumnConfig[]): LogsQuery['customColumns'] {+ const expressions = columns+ .map((column) => (column.type === 'custom' ? column.expression?.trim() : undefined))+ .filter((expression): expression is string => !!expression)+ // Undefined (not []) when there are no custom columns, so the query payload is+ // byte-identical to a pre-custom-columns query and cache keys are unaffected.+ return expressions.length > 0 ? expressions : undefined+}++function escapeHogQLString(value: string): string {+ return value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")+}++/**+ * Expression preserving the legacy attribute-column lookup, which coalesced across both maps+ * (`log.attributes[key] ?? log.resource_attributes[key]`). The `attributes.<key>` shorthand+ * reads only one map, so a plain shorthand would render resource-attribute columns empty.+ */+export function attributeLookupExpression(key: string): string {+ const escaped = escapeHogQLString(key)+ return `if(mapContains(attributes, '${escaped}'), attributes['${escaped}'], resource_attributes['${escaped}'])`+}++/** Migrate the legacy persisted `attributeColumnsConfig` map to typed custom columns. */+export function migrateAttributeColumns(config: Record<string, AttributeColumnConfig>): LogsColumnConfig[] {+ return Object.entries(config)+ .sort(([, a], [, b]) => a.order - b.order)+ .map(([key, { width }]) => ({+ id: uuid(),+ type: 'custom' as const,+ name: key,+ expression: attributeLookupExpression(key),+ ...(width !== undefined ? { width } : {}),+ }))+}diff --git a/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.ts b/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.tsindex 26abb2402a43..0cda6dc0da79 100644--- a/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.ts+++ b/products/logs/frontend/components/LogsViewer/logsViewerLogic.test.ts@@ -639,6 +639,42 @@ describe('logsViewerLogic', () => {})})+ describe('typed columns', () => {+ beforeEach(async () => {+ ;({ logic } = mountWithLogs())+ logic.actions.setColumns([+ { id: 'timestamp', type: 'timestamp' },+ { id: 'c1', type: 'custom', expression: 'attributes.http.url' },+ { id: 'message', type: 'message' },+ ])+ await expectLogic(logic).toFinishAllListeners()+ })++ const columnIds = (): string[] => logic.values.columns.map((c) => c.id)++ it.each<['left' | 'right', string, string[]]>([+ ['left', 'c1', ['c1', 'timestamp', 'message']],+ ['right', 'c1', ['timestamp', 'message', 'c1']],+ ['left', 'timestamp', ['timestamp', 'c1', 'message']], // first, no-op+ ['right', 'message', ['timestamp', 'c1', 'message']], // last, no-op+ ['left', 'missing', ['timestamp', 'c1', 'message']], // unknown id, no-op+ ])('moveColumn %s on %s yields %j without losing columns', (direction, id, expected) => {+ logic.actions.moveColumn(id, direction)+ expect(columnIds()).toEqual(expected)+ })++ it('exposes only custom expressions on the customColumns selector', () => {+ expect(logic.values.customColumns).toEqual(['attributes.http.url'])+ logic.actions.removeColumn('c1')+ expect(logic.values.customColumns).toBeUndefined()+ })++ it('sets width only on the matching column', () => {+ logic.actions.setColumnWidth('c1', 240)+ expect(logic.values.columns.map((c) => c.width)).toEqual([undefined, 240, undefined])+ })+ })+describe('expansion', () => {beforeEach(() => {;({ logic } = mountWithLogs())diff --git a/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts b/products/logs/frontend/components/LogsViewer/logsViewerLogic.tsindex 052fb9cf8f54..0a27933d5f17 100644--- a/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts+++ b/products/logs/frontend/components/LogsViewer/logsViewerLogic.ts@@ -12,6 +12,7 @@ import { logsViewerDataLogic } from 'products/logs/frontend/components/LogsVieweimport { logsViewerFiltersLogic } from 'products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic'import { AttributeColumnConfig, LogsOrderBy, ParsedLogMessage } from '../../types'+import { columnsToCustomColumns, DEFAULT_LOGS_COLUMNS, LogsColumnConfig } from './config/columns'import { logDetailsModalLogic } from './LogDetailsModal/logDetailsModalLogic'import type { logsViewerLogicType } from './logsViewerLogicType'import { logsViewerSettingsLogic } from './logsViewerSettingsLogic'@@ -127,6 +128,13 @@ export const logsViewerLogic = kea<logsViewerLogicType>([setAttributeColumnWidth: (attributeKey: string, width: number) => ({ attributeKey, width }),moveAttributeColumn: (attributeKey: string, direction: 'left' | 'right') => ({ attributeKey, direction }),+ // Typed columns (unified column model — dormant until the rendering cutover)+ setColumns: (columns: LogsColumnConfig[]) => ({ columns }),+ addColumn: (column: LogsColumnConfig) => ({ column }),+ removeColumn: (id: string) => ({ id }),+ setColumnWidth: (id: string, width: number) => ({ id, width }),+ moveColumn: (id: string, direction: 'left' | 'right') => ({ id, direction }),+// Row height recomputation (triggered by child components when content changes)recomputeRowHeights: (logIds?: string[]) => ({ logIds }),@@ -267,6 +275,31 @@ export const logsViewerLogic = kea<logsViewerLogicType>([},],+ // Unified typed-column model. Read by nothing yet — the table still renders from+ // attributeColumnsConfig until the rendering cutover, which will also migrate the+ // legacy persisted state into this shape (see config/columns.ts).+ columns: [+ DEFAULT_LOGS_COLUMNS,+ { persist: true },+ {+ setColumns: (_, { columns }) => columns,+ addColumn: (state, { column }) => [...state, column],+ removeColumn: (state, { id }) => state.filter((column) => column.id !== id),+ setColumnWidth: (state, { id, width }) =>+ state.map((column) => (column.id === id ? { ...column, width } : column)),+ moveColumn: (state, { id, direction }) => {+ const index = state.findIndex((column) => column.id === id)+ const targetIndex = direction === 'left' ? index - 1 : index + 1+ if (index === -1 || targetIndex < 0 || targetIndex >= state.length) {+ return state+ }+ const next = [...state]+ ;[next[index], next[targetIndex]] = [next[targetIndex], next[index]]+ return next+ },+ },+ ],+// Tracks requests to recompute row heights - VirtualizedLogsList watches thisrecomputeRowHeightsRequest: [null as { logIds?: string[]; timestamp: number } | null,@@ -426,6 +459,12 @@ export const logsViewerLogic = kea<logsViewerLogicType>([attributeKey in config,],+ // Lowered wire value for LogsQuery.customColumns — undefined until a custom column exists+ customColumns: [+ (s) => [s.columns],+ (columns: LogsColumnConfig[]): string[] | undefined => columnsToCustomColumns(columns),+ ],+// Selection selectorsisSelectionActive: [(s) => [s.selectedLogIds],