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): add retention rules settings section (#73829)

Frank Hamanda70488866f2d
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index 88f310bf723b..9a8f31694824 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -366,6 +366,7 @@ export const FEATURE_FLAGS = {
LOGS_SETTINGS_JSON: 'logs-settings-json', // owner: #team-logs
LOGS_SETTINGS_PII_SCRUB: 'logs-settings-pii-scrub', // owner: #team-logs
LOGS_SETTINGS_RETENTION: 'logs-settings-retention', // owner: #team-logs
+ LOGS_SETTINGS_RETENTION_RULES: 'logs-settings-retention-rules', // owner: #team-logs
LOGS_SPARKLINE_SERVICE_BREAKDOWN: 'logs-sparkline-service-breakdown', // owner: #team-logs
LOGS_SQL_VIEW: 'logs-sql-view', // owner: #team-logs
LOGS_TABBED_VIEW: 'logs-tabbed-view', // owner: #team-logs
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 7887a50c6905..b2619b96b925 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -58,6 +58,7 @@ import { ExceptionAutocaptureToggle } from 'products/error_tracking/frontend/sce
import { SuppressionRules } from 'products/error_tracking/frontend/scenes/ErrorTrackingConfigurationScene/suppression_rules/SuppressionRules'
import { LogsAlertingSection } from 'products/logs/frontend/components/LogsAlerting/LogsAlertingSection'
import { LogsMetricRulesSection } from 'products/logs/frontend/components/LogsMetricRules/LogsMetricRulesSection'
+import { LogsRetentionSection } from 'products/logs/frontend/components/LogsRetention/LogsRetentionSection'
import { LogsSamplingSection } from 'products/logs/frontend/components/LogsSampling/LogsSamplingSection'
import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'
import { WorkflowsEmailTrackingConsentSettings } from 'products/workflows/frontend/scenes/settings/WorkflowsEmailTrackingConsentSettings'
@@ -872,6 +873,15 @@ export const SETTINGS_MAP: SettingSection[] = [
flag: LogsFeatureFlagKeys.metricRules,
keywords: ['metric', 'metrics', 'generate', 'count', 'aggregate', 'logs to metrics'],
},
+ {
+ id: 'logs-retention-rules',
+ title: 'Retention rules',
+ description:
+ "Keep matching logs longer or shorter than the environment default using ordered rules. The first matching rule sets a log's retention; retention is applied at ingest.",
+ component: <LogsRetentionSection />,
+ flag: LogsFeatureFlagKeys.retentionRules,
+ keywords: ['retention', 'storage', 'ttl', 'rules', 'filter', 'keep', 'expire'],
+ },
{
id: 'logs-alerting',
title: 'Alerting',
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index c31356c4e98f..c2602eb13d77 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -190,6 +190,7 @@ export type SettingId =
| 'logs-metric-rules'
| 'logs-pii-scrub'
| 'logs-retention'
+ | 'logs-retention-rules'
| 'logs-session-id-attribute-keys'
| 'marketing-settings'
| 'mcp-hints'
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx
new file mode 100644
index 000000000000..1b0a77aacf5d
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionRulesSortableTable.tsx
@@ -0,0 +1,251 @@
+import {
+ DndContext,
+ DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ closestCenter,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core'
+import { restrictToVerticalAxis } from '@dnd-kit/modifiers'
+import {
+ SortableContext,
+ arrayMove,
+ sortableKeyboardCoordinates,
+ useSortable,
+ verticalListSortingStrategy,
+} from '@dnd-kit/sortable'
+import { CSS } from '@dnd-kit/utilities'
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { IconPlus } from '@posthog/icons'
+import { LemonButton, LemonSwitch } from '@posthog/lemon-ui'
+
+import { SortableDragIcon } from 'lib/lemon-ui/icons'
+import { urls } from 'scenes/urls'
+
+import { LogsRetentionRuleApi } from 'products/logs/frontend/generated/api.schemas'
+
+import { logsRetentionSectionLogic } from './logsRetentionSectionLogic'
+
+/** Read the retention tier out of the rule's config JSON for display. */
+function retentionDaysLabel(rule: LogsRetentionRuleApi): string {
+ const days = (rule.config as Record<string, unknown> | undefined)?.retention_days
+ return typeof days === 'number' ? `${days} days` : '—'
+}
+
+interface SortableRowProps {
+ row: LogsRetentionRuleApi
+ orderIndex: number
+ disabledReason: string | null
+ ruleEnabledTogglePendingId: string | null
+ saveRulesOrderPending: boolean
+ onSetRuleEnabled: (ruleId: string, enabled: boolean) => void
+}
+
+function SortableRow({
+ row,
+ orderIndex,
+ disabledReason,
+ ruleEnabledTogglePendingId,
+ saveRulesOrderPending,
+ onSetRuleEnabled,
+}: SortableRowProps): JSX.Element {
+ const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
+ id: row.id,
+ disabled: Boolean(disabledReason),
+ })
+
+ const style = {
+ transform: CSS.Transform.toString(transform),
+ transition: isDragging ? 'none' : transition,
+ opacity: isDragging ? 0.85 : 1,
+ zIndex: isDragging ? 10 : ('auto' as const),
+ }
+
+ return (
+ <tr
+ ref={disabledReason ? undefined : setNodeRef}
+ style={style}
+ className={clsx('border-b border-border bg-bg-light hover:bg-bg-3000', {
+ 'shadow-md bg-bg-3000': isDragging,
+ })}
+ >
+ <td className="py-2 px-2 w-10 align-middle">
+ <div
+ className={clsx('flex items-center justify-center', {
+ 'cursor-grab active:cursor-grabbing': !disabledReason,
+ 'opacity-40': disabledReason,
+ })}
+ {...(disabledReason ? {} : attributes)}
+ {...(disabledReason ? {} : listeners)}
+ >
+ <SortableDragIcon className="text-muted-alt h-3 w-3" />
+ </div>
+ </td>
+ <td className="py-2 px-2 w-12 text-center text-muted text-sm font-medium align-middle">{orderIndex + 1}</td>
+ <td className="py-2 px-2 min-w-0 align-middle">
+ <LemonButton
+ size="small"
+ type="tertiary"
+ to={urls.logsRetentionDetail(row.id)}
+ data-attr="logs-retention-rule-link"
+ >
+ <strong>{row.name}</strong>
+ </LemonButton>
+ </td>
+ <td className="py-2 px-2 text-secondary text-sm align-middle whitespace-nowrap">
+ {retentionDaysLabel(row)}
+ </td>
+ <td className="py-2 px-2 w-32 align-middle">
+ <LemonSwitch
+ checked={row.enabled ?? false}
+ onChange={(checked) => onSetRuleEnabled(row.id, checked)}
+ disabledReason={
+ ruleEnabledTogglePendingId === row.id
+ ? 'Saving…'
+ : saveRulesOrderPending
+ ? 'Updating order…'
+ : undefined
+ }
+ data-attr="logs-retention-rule-enabled-switch"
+ />
+ </td>
+ </tr>
+ )
+}
+
+export function LogsRetentionRulesSortableTable(): JSX.Element {
+ const { rules, rulesLoading, saveRulesOrderPending, ruleEnabledTogglePendingId } =
+ useValues(logsRetentionSectionLogic)
+ const { loadRules, saveRulesOrder, setRuleEnabled } = useActions(logsRetentionSectionLogic)
+
+ const [localRules, setLocalRules] = useState<LogsRetentionRuleApi[]>(rules)
+ const [isDragging, setIsDragging] = useState(false)
+
+ useEffect(() => {
+ if (!isDragging && !saveRulesOrderPending) {
+ setLocalRules(rules)
+ }
+ }, [rules, isDragging, saveRulesOrderPending])
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, {
+ activationConstraint: { distance: 8 },
+ }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
+ )
+
+ const handleDragEnd = (event: DragEndEvent): void => {
+ setIsDragging(false)
+ const { active, over } = event
+ if (!over || active.id === over.id) {
+ return
+ }
+ const oldIndex = localRules.findIndex((r) => r.id === active.id)
+ const newIndex = localRules.findIndex((r) => r.id === over.id)
+ if (oldIndex === -1 || newIndex === -1) {
+ return
+ }
+ const next = arrayMove(localRules, oldIndex, newIndex)
+ setLocalRules(next)
+ saveRulesOrder(next.map((r) => r.id))
+ }
+
+ const dragDisabledReason =
+ saveRulesOrderPending || rulesLoading
+ ? 'Please wait…'
+ : localRules.length < 2
+ ? 'Add another rule to reorder'
+ : null
+
+ if (rulesLoading && rules.length === 0) {
+ return (
+ <div>
+ <div className="flex justify-end mb-2">
+ <LemonButton type="primary" icon={<IconPlus />} to={urls.logsRetentionNew()}>
+ New retention rule
+ </LemonButton>
+ </div>
+ <div className="border border-border rounded-md bg-bg-light py-10 text-center text-muted">Loading…</div>
+ </div>
+ )
+ }
+
+ return (
+ <div>
+ <div className="flex justify-end mb-2">
+ <LemonButton type="primary" icon={<IconPlus />} to={urls.logsRetentionNew()}>
+ New retention rule
+ </LemonButton>
+ </div>
+ <div
+ className={clsx('border border-border rounded-md overflow-hidden bg-bg-light', {
+ 'opacity-70 pointer-events-none': rulesLoading && rules.length > 0,
+ })}
+ >
+ <DndContext
+ sensors={sensors}
+ collisionDetection={closestCenter}
+ onDragStart={() => setIsDragging(true)}
+ onDragEnd={handleDragEnd}
+ onDragCancel={() => setIsDragging(false)}
+ modifiers={[restrictToVerticalAxis]}
+ >
+ <table className="w-full table-fixed">
+ <thead className="bg-bg-3000">
+ <tr>
+ <th className="py-2 px-2 w-10" />
+ <th className="py-2 px-2 w-12 text-left text-xs font-semibold text-muted-alt uppercase tracking-wider">
+ Order
+ </th>
+ <th className="py-2 px-2 text-left text-xs font-semibold text-muted-alt uppercase tracking-wider min-w-0">
+ Name
+ </th>
+ <th className="py-2 px-2 text-left text-xs font-semibold text-muted-alt uppercase tracking-wider whitespace-nowrap">
+ Retention
+ </th>
+ <th className="py-2 px-2 w-32 text-left text-xs font-semibold text-muted-alt uppercase tracking-wider">
+ Enabled
+ </th>
+ </tr>
+ </thead>
+ <tbody>
+ {localRules.length === 0 ? (
+ <tr>
+ <td colSpan={5} className="text-center py-8 text-muted">
+ No retention rules yet
+ </td>
+ </tr>
+ ) : (
+ <SortableContext
+ items={localRules.map((r) => r.id)}
+ strategy={verticalListSortingStrategy}
+ >
+ {localRules.map((row, index) => (
+ <SortableRow
+ key={row.id}
+ row={row}
+ orderIndex={index}
+ disabledReason={dragDisabledReason}
+ ruleEnabledTogglePendingId={ruleEnabledTogglePendingId}
+ saveRulesOrderPending={saveRulesOrderPending}
+ onSetRuleEnabled={setRuleEnabled}
+ />
+ ))}
+ </SortableContext>
+ )}
+ </tbody>
+ </table>
+ </DndContext>
+ </div>
+ <div className="mt-2">
+ <LemonButton size="small" type="secondary" onClick={() => loadRules()}>
+ Refresh list
+ </LemonButton>
+ </div>
+ </div>
+ )
+}
diff --git a/products/logs/frontend/components/LogsRetention/LogsRetentionSection.tsx b/products/logs/frontend/components/LogsRetention/LogsRetentionSection.tsx
new file mode 100644
index 000000000000..658169b6b0af
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/LogsRetentionSection.tsx
@@ -0,0 +1,28 @@
+import { BindLogic } from 'kea'
+
+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
+
+import { LogsFeatureFlagKeys } from 'products/logs/frontend/logsFeatureFlagKeys'
+
+import { LogsRetentionRulesSortableTable } from './LogsRetentionRulesSortableTable'
+import { logsRetentionSectionLogic } from './logsRetentionSectionLogic'
+
+export function LogsRetentionSection(): JSX.Element | null {
+ const enabled = useFeatureFlag(LogsFeatureFlagKeys.retentionRules)
+ if (!enabled) {
+ return null
+ }
+ return (
+ <BindLogic logic={logsRetentionSectionLogic} props={{}}>
+ <div className="space-y-3">
+ <p className="text-muted m-0">
+ Keep some logs longer or shorter than the environment default. Rules run top to bottom during
+ ingestion — drag the handle on each row to change that order, and the first matching rule sets a
+ log's retention. Logs matching no rule keep the environment default. Retention is applied at ingest,
+ so changes only affect logs received from that point onwards.
+ </p>
+ <LogsRetentionRulesSortableTable />
+ </div>
+ </BindLogic>
+ )
+}
diff --git a/products/logs/frontend/components/LogsRetention/logsRetentionSectionLogic.ts b/products/logs/frontend/components/LogsRetention/logsRetentionSectionLogic.ts
new file mode 100644
index 000000000000..8c62ecc8ec1c
--- /dev/null
+++ b/products/logs/frontend/components/LogsRetention/logsRetentionSectionLogic.ts
@@ -0,0 +1,148 @@
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import {
+ logsRetentionRulesList,
+ logsRetentionRulesPartialUpdate,
+ logsRetentionRulesReorderCreate,
+} from 'products/logs/frontend/generated/api'
+import { LogsRetentionRuleApi } from 'products/logs/frontend/generated/api.schemas'
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsRetentionSectionLogicValues {
+ currentTeamId: number | null // teamLogic
+ ruleEnabledTogglePendingId: string | null
+ rules: LogsRetentionRuleApi[]
+ rulesLoading: boolean
+ saveRulesOrderPending: boolean
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface logsRetentionSectionLogicActions {
+ loadRules: () => any
+ loadRulesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadRulesSuccess: (
+ rules: LogsRetentionRuleApi[],
+ payload?: any
+ ) => {
+ rules: LogsRetentionRuleApi[]
+ payload?: any
+ }
+ saveRulesOrder: (orderedIds: string[]) => {
+ orderedIds: string[]
+ }
+ saveRulesOrderFinished: () => {
+ value: true
+ }
+ setRuleEnabled: (
+ ruleId: string,
+ enabled: boolean
+ ) => {
+ enabled: boolean
+ ruleId: string
+ }
+ setRuleEnabledFinished: () => {
+ value: true
+ }
+}
+
+export type logsRetentionSectionLogicType = MakeLogicType<
+ logsRetentionSectionLogicValues,
+ logsRetentionSectionLogicActions
+>
+
+export const logsRetentionSectionLogic = kea<logsRetentionSectionLogicType>([
+ path(['products', 'logs', 'frontend', 'components', 'LogsRetention', 'logsRetentionSectionLogic']),
+
+ connect({
+ values: [teamLogic, ['currentTeamId']],
+ }),
+
+ actions({
+ saveRulesOrder: (orderedIds: string[]) => ({ orderedIds }),
+ saveRulesOrderFinished: true,
+ setRuleEnabled: (ruleId: string, enabled: boolean) => ({ ruleId, enabled }),
+ setRuleEnabledFinished: true,
+ }),
+
+ reducers({
+ saveRulesOrderPending: [
+ false,
+ {
+ saveRulesOrder: () => true,
+ saveRulesOrderFinished: () => false,
+ },
+ ],
+ ruleEnabledTogglePendingId: [
+ null as string | null,
+ {
+ setRuleEnabled: (_, { ruleId }) => ruleId,
+ setRuleEnabledFinished: () => null,
+ },
+ ],
+ }),
+
+ loaders(({ values }) => ({
+ rules: [
+ [] as LogsRetentionRuleApi[],
+ {
+ loadRules: async () => {
+ const page = await logsRetentionRulesList(String(values.currentTeamId))
+ return page.results
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions, values }) => ({
+ saveRulesOrder: async ({ orderedIds }) => {
+ const projectId = values.currentTeamId
+ if (projectId === null) {
+ actions.saveRulesOrderFinished()
+ return
+ }
+ try {
+ await logsRetentionRulesReorderCreate(String(projectId), { ordered_ids: orderedIds })
+ lemonToast.success('Evaluation order updated')
+ await actions.loadRules()
+ } catch (e: unknown) {
+ const err = e as { detail?: string; message?: string }
+ lemonToast.error(err?.detail ?? err?.message ?? 'Failed to update order')
+ await actions.loadRules()
+ } finally {
+ actions.saveRulesOrderFinished()
+ }
+ },
+ setRuleEnabled: async ({ ruleId, enabled }) => {
+ const projectId = values.currentTeamId
+ if (projectId === null) {
+ actions.setRuleEnabledFinished()
+ return
+ }
+ try {
+ await logsRetentionRulesPartialUpdate(String(projectId), ruleId, { enabled })
+ await actions.loadRules()
+ } catch (e: unknown) {
+ const err = e as { detail?: string; message?: string }
+ lemonToast.error(err?.detail ?? err?.message ?? 'Failed to update rule')
+ await actions.loadRules()
+ } finally {
+ actions.setRuleEnabledFinished()
+ }
+ },
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadRules()
+ }),
+])
diff --git a/products/logs/frontend/logsFeatureFlagKeys.ts b/products/logs/frontend/logsFeatureFlagKeys.ts
index 00d3f51c981f..b5fc44003052 100644
--- a/products/logs/frontend/logsFeatureFlagKeys.ts
+++ b/products/logs/frontend/logsFeatureFlagKeys.ts
@@ -4,4 +4,9 @@ import type { FeatureFlagLookupKey } from 'lib/constants'
export const LogsFeatureFlagKeys = {
dropRules: 'LOGS_SETTINGS_DROP_RULES',
metricRules: 'LOGS_METRIC_RULES',
-} as const satisfies { dropRules: FeatureFlagLookupKey; metricRules: FeatureFlagLookupKey }
+ retentionRules: 'LOGS_SETTINGS_RETENTION_RULES',
+} as const satisfies {
+ dropRules: FeatureFlagLookupKey
+ metricRules: FeatureFlagLookupKey
+ retentionRules: FeatureFlagLookupKey
+}