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 pattern message extraction settings ui (#96735)

Jon McCalluma88caca15d5e
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdx
index b0f6a7be90e4..0a7a2e25581b 100644
--- a/docs/published/docs/logs/logs-config.mdx
+++ b/docs/published/docs/logs/logs-config.mdx
@@ -44,6 +44,8 @@ The list can't be empty.
JSON keys whose value is the message text that log patterns are derived from. Default: `["message", "msg", "event"]`.
+In **Settings > Project > Logs > Pattern message extraction**, add or remove keys, drag them into priority order, and select **Save**. Project admins can edit this setting. Clear all keys and save to turn message extraction off.
+
When a log body is a JSON object, PostHog looks up these keys in order and uses the first one whose value is a non-empty string as the text to build the pattern from. A key whose value is a number, an object, or an empty string is skipped, and the search continues down the list.
If no key matches, the pattern is built from the object's set of top-level key names instead, so records with the same shape group together.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d64c2eff7987..fdf5c33d834b 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9436,6 +9436,14 @@ snapshots:
hash: v1.k794b7964.1aa226e2340f780cab3be2c4c58df4aa306c192093f889275b54db44761ed25e.4fAT0IldZHoHUB5OJKtr1MU7DN0n0t-8eEPKH-Mrzm8
scenes-app-settings-project--settings-project-integrations--light:
hash: v1.k794b7964.78000b9fb5415dc591e2d554b15eda54e4cf236fea779b643c8d00bfabe01024.pPGoBVvfxP-T4iYNRwqo_DfXZWCiOhtD1bUcStUoDHY
+ scenes-app-settings-project--settings-project-logs--dark:
+ hash: v1.k794b7964.49d053d0783c37817aef5a402d8b00781837f6d4fcf96ce8018dcc439ee744f6.XDbj-HU8eX-2niM5nkM6KmkxOLY_sD30DE6_93XKRsU
+ scenes-app-settings-project--settings-project-logs--light:
+ hash: v1.k794b7964.a333ea2a5d4895fb9d44471c21df570ce6a1fbe00e5fe56ccde792344dccdc22.eK8MVYW-hmpPBpBMTNecSMjDDT4-7NKqh8ckYPSodS8
+ scenes-app-settings-project--settings-project-logs-read-only--dark:
+ hash: v1.k794b7964.c48f5aa9adb1e98503493f3f36c4136cfc2846d5d447397987ffe66aa53fc690.wRENzqvVWKmuhtUr6ACFDU1LV90Lz2TZrWFc5SW_VHY
+ scenes-app-settings-project--settings-project-logs-read-only--light:
+ hash: v1.k794b7964.4e11ad0c20b5ae6426397736a50c17ba21f6750d95d1a0a9f3106ed9cfc002ba.TrjQhBRaVixnEN_lFBvMriCqDdY0iA3Q2tdHRAybdvs
scenes-app-settings-project--settings-project-product-analytics--dark:
hash: v1.k794b7964.5a07f89b3cfdd21f4db69f6efd92794257b59cc2d743dc5bd3e801fc249c1fc6.teJLydFRlsuGeFHnCiQBE2Fxcc6YKf8mCBLTv6bXMKM
scenes-app-settings-project--settings-project-product-analytics--light:
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.ts
index 28a0254d3101..d9ed801905ba 100644
--- a/frontend/src/generated/core/api.ts
+++ b/frontend/src/generated/core/api.ts
@@ -1276,54 +1276,6 @@ export const organizationsProjectsIsGeneratingDemoDataRetrieve = async (
)
}
-export const getOrganizationsProjectsLogsConfigRetrieveUrl = (organizationId: string, id: number) => {
- return `/api/organizations/${organizationId}/projects/${id}/logs_config/`
-}
-
-/**
- * Manage logs product configuration for this project's canonical environment.
- * Members can read; writing requires project admin, matching the admin-only
- * settings UI. Mirrors the env-router action so /api/projects/:id/logs_config/
- * resolves alongside the legacy /api/environments/:id/logs_config/ alias.
- */
-export const organizationsProjectsLogsConfigRetrieve = async (
- organizationId: string,
- id: number,
- options?: RequestInit
-): Promise<ProjectBackwardCompatApi> => {
- return apiMutator<ProjectBackwardCompatApi>(getOrganizationsProjectsLogsConfigRetrieveUrl(organizationId, id), {
- ...options,
- method: 'GET',
- })
-}
-
-export const getOrganizationsProjectsLogsConfigPartialUpdateUrl = (organizationId: string, id: number) => {
- return `/api/organizations/${organizationId}/projects/${id}/logs_config/`
-}
-
-/**
- * Manage logs product configuration for this project's canonical environment.
- * Members can read; writing requires project admin, matching the admin-only
- * settings UI. Mirrors the env-router action so /api/projects/:id/logs_config/
- * resolves alongside the legacy /api/environments/:id/logs_config/ alias.
- */
-export const organizationsProjectsLogsConfigPartialUpdate = async (
- organizationId: string,
- id: number,
- patchedProjectBackwardCompatApi?: NonReadonly<PatchedProjectBackwardCompatApi>,
- options?: RequestInit
-): Promise<ProjectBackwardCompatApi> => {
- return apiMutator<ProjectBackwardCompatApi>(
- getOrganizationsProjectsLogsConfigPartialUpdateUrl(organizationId, id),
- {
- ...options,
- method: 'PATCH',
- headers: { 'Content-Type': 'application/json', ...options?.headers },
- body: JSON.stringify(patchedProjectBackwardCompatApi),
- }
- )
-}
-
export const getOrganizationsProjectsResetTokenPartialUpdateUrl = (organizationId: string, id: number) => {
return `/api/organizations/${organizationId}/projects/${id}/reset_token/`
}
diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.ts
index 42d3491b6517..4ad93e76cbda 100644
--- a/frontend/src/generated/core/api.zod.ts
+++ b/frontend/src/generated/core/api.zod.ts
@@ -542,16 +542,6 @@ export const OrganizationsProjectsGenerateConversationsPublicTokenCreateBody = /
.record(zod.string(), zod.unknown())
.describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
-/**
- * Manage logs product configuration for this project's canonical environment.
- * Members can read; writing requires project admin, matching the admin-only
- * settings UI. Mirrors the env-router action so /api/projects/:id/logs_config/
- * resolves alongside the legacy /api/environments/:id/logs_config/ alias.
- */
-export const OrganizationsProjectsLogsConfigPartialUpdateBody = /* @__PURE__ */ zod
- .record(zod.string(), zod.unknown())
- .describe('Deep\/recursive schema (opaque in Zod — use TypeScript types for full shape)')
-
/**
* Projects for the current organization.
*/
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 52f478be4c4e..2bbb827d6649 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -122,6 +122,7 @@ import {
LogsRetentionSettings,
} from './environment/LogsCaptureSettings'
import { LogsDistinctIdAttributeKeys } from './environment/LogsDistinctIdAttributeKeys'
+import { LogsPatternMessageKeys } from './environment/LogsPatternMessageKeys'
import { LogsSessionIdAttributeKeys } from './environment/LogsSessionIdAttributeKeys'
import { ManagedReverseProxy } from './environment/ManagedReverseProxy'
import { MarketingAnalyticsSettingsWrapper } from './environment/MarketingAnalyticsSettingsWrapper'
@@ -915,6 +916,14 @@ export const SETTINGS_MAP: SettingSection[] = [
component: <LogsDistinctIdAttributeKeys />,
keywords: ['log', 'person', 'distinct', 'attribute', 'pivot', 'profile', 'link'],
},
+ {
+ id: 'logs-pattern-message-keys',
+ title: 'Pattern message extraction',
+ description:
+ 'Choose which JSON keys provide the message used to group logs into patterns. Keys are matched literally at the top level, in order. This does not change the stored log body.',
+ component: <LogsPatternMessageKeys />,
+ keywords: ['log', 'pattern', 'message', 'extract', 'json', 'group'],
+ },
{
id: 'logs-session-id-attribute-keys',
title: 'Link to session',
diff --git a/frontend/src/scenes/settings/environment/LogsPatternMessageKeys.tsx b/frontend/src/scenes/settings/environment/LogsPatternMessageKeys.tsx
new file mode 100644
index 000000000000..5d0747fc5acd
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/LogsPatternMessageKeys.tsx
@@ -0,0 +1,76 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+
+import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
+
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+import { logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
+
+export function LogsPatternMessageKeys(): JSX.Element {
+ const {
+ logsConfig,
+ logsConfigLoading,
+ patternMessageKeysChanged,
+ patternMessageKeysValidationErrors,
+ isPatternMessageKeysSubmitting,
+ } = useValues(logsConfigLogic)
+ const { loadLogsConfig } = useActions(logsConfigLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+
+ if (!logsConfig) {
+ return logsConfigLoading ? (
+ <LemonSkeleton className="w-1/2 h-4" />
+ ) : (
+ <LemonBanner type="error" action={{ children: 'Retry', onClick: () => loadLogsConfig() }}>
+ Could not load pattern message extraction settings.
+ </LemonBanner>
+ )
+ }
+
+ return (
+ <Form logic={logsConfigLogic} formKey="patternMessageKeys" enableFormOnSubmit className="space-y-4">
+ <LemonField
+ name="keys"
+ label="Message keys"
+ help="Drag keys to change their priority. Clear all keys to disable message extraction."
+ >
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
+ sortable={!restrictedReason && !logsConfigLoading && !isPatternMessageKeysSubmitting}
+ limit={10}
+ disableCommaSplitting
+ bulkActions="clear-all"
+ placeholder="Add a message key"
+ loading={logsConfigLoading}
+ disabled={logsConfigLoading || isPatternMessageKeysSubmitting || !!restrictedReason}
+ data-attr="logs-pattern-message-keys-select"
+ className="max-w-md"
+ />
+ </LemonField>
+ {patternMessageKeysValidationErrors.keys?.[0] && (
+ <LemonField.Error error={patternMessageKeysValidationErrors.keys[0]} />
+ )}
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ disabledReason={
+ restrictedReason ||
+ patternMessageKeysValidationErrors.keys?.[0] ||
+ (!patternMessageKeysChanged ? 'No changes to save' : undefined)
+ }
+ loading={logsConfigLoading || isPatternMessageKeysSubmitting}
+ >
+ Save
+ </LemonButton>
+ </Form>
+ )
+}
diff --git a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
index 3dbfd52defe9..571ddf91f897 100644
--- a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
@@ -3,8 +3,9 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import type { Meta, StoryObj } from '@storybook/react'
import { router } from 'kea-router'
-import { STORYBOOK_FEATURE_FLAGS } from 'lib/constants'
+import { STORYBOOK_FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
import { App } from 'scenes/App'
+import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
@@ -84,3 +85,45 @@ export const SettingsProjectSurveys: Story = { args: { sectionId: 'project-surve
export const SettingsProjectIntegrations: Story = { args: { sectionId: 'project-integrations' } }
export const SettingsProjectAccessControl: Story = { args: { sectionId: 'project-access-control' } }
+
+export const SettingsProjectLogs: Story = {
+ args: { sectionId: 'project-logs' },
+ parameters: { featureFlags: [] },
+ decorators: [
+ mswDecorator({
+ get: {
+ '/api/projects/:id/logs/sampling_rules/': { results: [] },
+ '/api/projects/:id/logs/alerts/': { results: [] },
+ '/api/projects/:id/logs_config/': {
+ logs_distinct_id_attribute_key: 'posthogDistinctId',
+ logs_distinct_id_attribute_keys: ['posthogDistinctId'],
+ logs_session_id_attribute_keys: ['sessionId'],
+ logs_pattern_message_keys: ['message', 'msg', 'event'],
+ },
+ },
+ patch: {
+ '/api/projects/:id/logs_config/': async ({ request }) => [
+ 200,
+ {
+ logs_distinct_id_attribute_key: 'posthogDistinctId',
+ logs_distinct_id_attribute_keys: ['posthogDistinctId'],
+ logs_session_id_attribute_keys: ['sessionId'],
+ ...((await request.json()) as object),
+ },
+ ],
+ },
+ }),
+ ],
+}
+
+export const SettingsProjectLogsReadOnly: Story = {
+ ...SettingsProjectLogs,
+ render: ({ sectionId }) => {
+ teamLogic.actions.loadCurrentTeamSuccess({
+ ...MOCK_DEFAULT_TEAM,
+ effective_membership_level: OrganizationMembershipLevel.Member,
+ })
+ router.actions.push(urls.settings(sectionId))
+ return <App />
+ },
+}
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index 79b8afc4d1c0..1cb67438248d 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -65,6 +65,7 @@ export type SettingSectionId =
| 'project-autocapture'
| 'project-customization'
| 'project-integrations'
+ | 'project-logs'
| 'project-product-analytics'
| 'project-replay'
| 'project-surveys'
@@ -206,6 +207,7 @@ export type SettingId =
| 'logs-drop-rules'
| 'logs-json-parse'
| 'logs-metric-rules'
+ | 'logs-pattern-message-keys'
| 'logs-pii-scrub'
| 'logs-retention'
| 'logs-retention-rules'
diff --git a/posthog/api/project.py b/posthog/api/project.py
index 8fbea6aa4aea..34e86a3e52dc 100644
--- a/posthog/api/project.py
+++ b/posthog/api/project.py
@@ -37,6 +37,7 @@ from posthog.api.team import (
EventIngestionRestrictionSerializer,
TeamCustomerAnalyticsConfigSerializer,
TeamFeatureFlagPolicyConfigSerializer,
+ TeamLogsConfigSerializer,
TeamMarketingAnalyticsConfigSerializer,
TeamRevenueAnalyticsConfigSerializer,
TeamSerializer,
@@ -1725,6 +1726,18 @@ class ProjectViewSet(
project = self.get_object()
return response.Response({"is_generating_demo_data": project.passthrough_team.get_is_generating_demo_data()})
+ @extend_schema(
+ methods=["GET"],
+ request=None,
+ responses={200: TeamLogsConfigSerializer},
+ extensions={"x-product": "logs"},
+ )
+ @extend_schema(
+ methods=["PATCH"],
+ request=TeamLogsConfigSerializer,
+ responses={200: TeamLogsConfigSerializer},
+ extensions={"x-product": "logs"},
+ )
@action(
methods=["GET", "PATCH"],
detail=True,
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 86c65a1b26ea..cb0c1dbb42c1 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -2594,6 +2594,18 @@ class TeamViewSet(
)
return response.Response(TeamSerializer(team, context=self.get_serializer_context()).data)
+ @extend_schema(
+ methods=["GET"],
+ request=None,
+ responses={200: TeamLogsConfigSerializer},
+ extensions={"x-product": "logs"},
+ )
+ @extend_schema(
+ methods=["PATCH"],
+ request=TeamLogsConfigSerializer,
+ responses={200: TeamLogsConfigSerializer},
+ extensions={"x-product": "logs"},
+ )
@action(
methods=["GET", "PATCH"],
detail=True,
diff --git a/products/logs/frontend/generated/api.schemas.ts b/products/logs/frontend/generated/api.schemas.ts
index 0c4c17ba86aa..246283e80e5e 100644
--- a/products/logs/frontend/generated/api.schemas.ts
+++ b/products/logs/frontend/generated/api.schemas.ts
@@ -7,6 +7,52 @@
* PostHog API - generated
* OpenAPI spec version: 1.0.0
*/
+export interface TeamLogsConfigApi {
+ /** Legacy single-key alias — always the first entry of `logs_distinct_id_attribute_keys`. Read-only; write the plural field instead. */
+ readonly logs_distinct_id_attribute_key: string
+ /**
+ * Log attribute keys whose values should match a person's distinct_id — a log links to a person when any of these attributes equals one of their distinct IDs. Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to ['posthogDistinctId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the person identifier under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_distinct_id_attribute_keys: string[]
+ /**
+ * Ordered list of log attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_session_id_attribute_keys: string[]
+ /**
+ * Ordered list of top-level JSON keys whose value is the message text that log patterns are derived from. Keys are matched literally at the top level of the log body; a dot in a key is part of the key name, not a path into nested objects. Selection checks keys in order; the first key whose value is a non-empty string wins. Defaults to ['message', 'msg', 'event']. An empty list turns message extraction off, so JSON log bodies group by their key set instead. The stored log body is never changed by this setting.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_pattern_message_keys: string[]
+}
+
+export interface PatchedTeamLogsConfigApi {
+ /** Legacy single-key alias — always the first entry of `logs_distinct_id_attribute_keys`. Read-only; write the plural field instead. */
+ readonly logs_distinct_id_attribute_key?: string
+ /**
+ * Log attribute keys whose values should match a person's distinct_id — a log links to a person when any of these attributes equals one of their distinct IDs. Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to ['posthogDistinctId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the person identifier under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_distinct_id_attribute_keys?: string[]
+ /**
+ * Ordered list of log attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_session_id_attribute_keys?: string[]
+ /**
+ * Ordered list of top-level JSON keys whose value is the message text that log patterns are derived from. Keys are matched literally at the top level of the log body; a dot in a key is part of the key name, not a path into nested objects. Selection checks keys in order; the first key whose value is a non-empty string wins. Defaults to ['message', 'msg', 'event']. An empty list turns message extraction off, so JSON log bodies group by their key set instead. The stored log body is never changed by this setting.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_pattern_message_keys?: string[]
+}
+
export type FilterLogicalOperatorApi = (typeof FilterLogicalOperatorApi)[keyof typeof FilterLogicalOperatorApi]
export const FilterLogicalOperatorApi = {
diff --git a/products/logs/frontend/generated/api.ts b/products/logs/frontend/generated/api.ts
index 3bf00ae62886..70c83a3dbc3c 100644
--- a/products/logs/frontend/generated/api.ts
+++ b/products/logs/frontend/generated/api.ts
@@ -53,6 +53,8 @@ import type {
PatchedLogsRetentionRuleApi,
PatchedLogsSamplingRuleApi,
PatchedLogsViewApi,
+ PatchedTeamLogsConfigApi,
+ TeamLogsConfigApi,
_LogsAttributesResponseApi,
_LogsCountRangesRequestApi,
_LogsCountRangesResponseApi,
@@ -94,6 +96,51 @@ type NonReadonly<T> = [T] extends [UnionToIntersection<T>]
}
: DistributeReadOnlyOverUnions<T>
+export const getOrganizationsProjectsLogsConfigRetrieveUrl = (organizationId: string, id: number) => {
+ return `/api/organizations/${organizationId}/projects/${id}/logs_config/`
+}
+
+/**
+ * Manage logs product configuration for this project's canonical environment.
+ * Members can read; writing requires project admin, matching the admin-only
+ * settings UI. Mirrors the env-router action so /api/projects/:id/logs_config/
+ * resolves alongside the legacy /api/environments/:id/logs_config/ alias.
+ */
+export const organizationsProjectsLogsConfigRetrieve = async (
+ organizationId: string,
+ id: number,
+ options?: RequestInit
+): Promise<TeamLogsConfigApi> => {
+ return apiMutator<TeamLogsConfigApi>(getOrganizationsProjectsLogsConfigRetrieveUrl(organizationId, id), {
+ ...options,
+ method: 'GET',
+ })
+}
+
+export const getOrganizationsProjectsLogsConfigPartialUpdateUrl = (organizationId: string, id: number) => {
+ return `/api/organizations/${organizationId}/projects/${id}/logs_config/`
+}
+
+/**
+ * Manage logs product configuration for this project's canonical environment.
+ * Members can read; writing requires project admin, matching the admin-only
+ * settings UI. Mirrors the env-router action so /api/projects/:id/logs_config/
+ * resolves alongside the legacy /api/environments/:id/logs_config/ alias.
+ */
+export const organizationsProjectsLogsConfigPartialUpdate = async (
+ organizationId: string,
+ id: number,
+ patchedTeamLogsConfigApi?: NonReadonly<PatchedTeamLogsConfigApi>,
+ options?: RequestInit
+): Promise<TeamLogsConfigApi> => {
+ return apiMutator<TeamLogsConfigApi>(getOrganizationsProjectsLogsConfigPartialUpdateUrl(organizationId, id), {
+ ...options,
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(patchedTeamLogsConfigApi),
+ })
+}
+
export const getLogsAlertsListUrl = (projectId: string, params?: LogsAlertsListParams) => {
const normalizedParams = new URLSearchParams()
diff --git a/products/logs/frontend/generated/api.zod.ts b/products/logs/frontend/generated/api.zod.ts
index d02f193a1e98..6f0ec991e144 100644
--- a/products/logs/frontend/generated/api.zod.ts
+++ b/products/logs/frontend/generated/api.zod.ts
@@ -9,6 +9,48 @@
*/
import * as zod from 'zod'
+/**
+ * Manage logs product configuration for this project's canonical environment.
+ * Members can read; writing requires project admin, matching the admin-only
+ * settings UI. Mirrors the env-router action so /api/projects/:id/logs_config/
+ * resolves alongside the legacy /api/environments/:id/logs_config/ alias.
+ */
+export const organizationsProjectsLogsConfigPartialUpdateBodyLogsDistinctIdAttributeKeysItemMax = 200
+
+export const organizationsProjectsLogsConfigPartialUpdateBodyLogsDistinctIdAttributeKeysMax = 10
+
+export const organizationsProjectsLogsConfigPartialUpdateBodyLogsSessionIdAttributeKeysItemMax = 200
+
+export const organizationsProjectsLogsConfigPartialUpdateBodyLogsSessionIdAttributeKeysMax = 10
+
+export const organizationsProjectsLogsConfigPartialUpdateBodyLogsPatternMessageKeysItemMax = 200
+
+export const organizationsProjectsLogsConfigPartialUpdateBodyLogsPatternMessageKeysMax = 10
+
+export const OrganizationsProjectsLogsConfigPartialUpdateBody = /* @__PURE__ */ zod.object({
+ logs_distinct_id_attribute_keys: zod
+ .array(zod.string().max(organizationsProjectsLogsConfigPartialUpdateBodyLogsDistinctIdAttributeKeysItemMax))
+ .max(organizationsProjectsLogsConfigPartialUpdateBodyLogsDistinctIdAttributeKeysMax)
+ .optional()
+ .describe(
+ "Log attribute keys whose values should match a person's distinct_id — a log links to a person when any of these attributes equals one of their distinct IDs. Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to ['posthogDistinctId'] — the convention documented at https:\/\/posthog.com\/docs\/logs\/link-session-replay and the key the posthog-js \/ posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the person identifier under different attributes."
+ ),
+ logs_session_id_attribute_keys: zod
+ .array(zod.string().max(organizationsProjectsLogsConfigPartialUpdateBodyLogsSessionIdAttributeKeysItemMax))
+ .max(organizationsProjectsLogsConfigPartialUpdateBodyLogsSessionIdAttributeKeysMax)
+ .optional()
+ .describe(
+ "Ordered list of log attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'] — the convention documented at https:\/\/posthog.com\/docs\/logs\/link-session-replay and the key the posthog-js \/ posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes."
+ ),
+ logs_pattern_message_keys: zod
+ .array(zod.string().max(organizationsProjectsLogsConfigPartialUpdateBodyLogsPatternMessageKeysItemMax))
+ .max(organizationsProjectsLogsConfigPartialUpdateBodyLogsPatternMessageKeysMax)
+ .optional()
+ .describe(
+ "Ordered list of top-level JSON keys whose value is the message text that log patterns are derived from. Keys are matched literally at the top level of the log body; a dot in a key is part of the key name, not a path into nested objects. Selection checks keys in order; the first key whose value is a non-empty string wins. Defaults to ['message', 'msg', 'event']. An empty list turns message extraction off, so JSON log bodies group by their key set instead. The stored log body is never changed by this setting."
+ ),
+})
+
export const logsAlertsCreateBodyNameMax = 255
export const logsAlertsCreateBodyEnabledDefault = true
diff --git a/products/logs/frontend/logsConfigLogic.test.ts b/products/logs/frontend/logsConfigLogic.test.ts
new file mode 100644
index 000000000000..8a0474889e84
--- /dev/null
+++ b/products/logs/frontend/logsConfigLogic.test.ts
@@ -0,0 +1,93 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import type { TeamLogsConfigApi } from './generated/api.schemas'
+import { logsConfigLogic } from './logsConfigLogic'
+
+const config: TeamLogsConfigApi = {
+ logs_distinct_id_attribute_key: 'posthogDistinctId',
+ logs_distinct_id_attribute_keys: ['posthogDistinctId'],
+ logs_session_id_attribute_keys: ['sessionId'],
+ logs_pattern_message_keys: ['message', 'msg', 'event'],
+}
+
+describe('logsConfigLogic pattern message keys', () => {
+ let logic: ReturnType<typeof logsConfigLogic.build>
+ let patch: jest.Mock
+ let submittedPatch: unknown
+
+ beforeEach(async () => {
+ submittedPatch = undefined
+ patch = jest.fn(async ({ request }) => {
+ submittedPatch = await request.json()
+ return [200, { ...config, ...(submittedPatch as object) }]
+ })
+ useMocks({
+ get: { '/api/projects/:id/logs_config/': config },
+ patch: { '/api/projects/:id/logs_config/': patch },
+ })
+ initKeaTests()
+ logic = logsConfigLogic()
+ logic.mount()
+ await expectLogic(logic)
+ .toDispatchActions(['loadLogsConfigSuccess'])
+ .toMatchValues({
+ patternMessageKeys: { keys: config.logs_pattern_message_keys },
+ patternMessageKeysChanged: false,
+ })
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it.each([
+ ['an empty list', [], []],
+ ['reordered keys', ['msg', 'message'], ['msg', 'message']],
+ ['trimmed literal keys', [' log.message ', 'message'], ['log.message', 'message']],
+ ])('saves %s without changing correlation settings', async (_name, keys, expected) => {
+ logic.actions.setPatternMessageKeysValue('keys', keys)
+ await expectLogic(logic, () => logic.actions.submitPatternMessageKeys())
+ .toDispatchActions(['updateLogsConfigSuccess', 'submitPatternMessageKeysSuccess'])
+ .toMatchValues({
+ logsConfig: { ...config, logs_pattern_message_keys: expected },
+ patternMessageKeys: { keys: expected },
+ patternMessageKeysChanged: false,
+ isPatternMessageKeysSubmitting: false,
+ })
+ expect(patch).toHaveBeenCalledTimes(1)
+ expect(submittedPatch).toEqual({ logs_pattern_message_keys: expected })
+ })
+
+ it.each([
+ [['message', ' message '], 'Keys must be unique.'],
+ [[' '], 'Keys cannot be blank.'],
+ [['x'.repeat(201)], 'Each key must be 200 characters or fewer.'],
+ [Array.from({ length: 11 }, (_, index) => `key${index}`), 'Use at most 10 keys.'],
+ ])('rejects invalid keys %j before saving', async (keys, error) => {
+ logic.actions.setPatternMessageKeysValue('keys', keys)
+ await expectLogic(logic, () => logic.actions.submitPatternMessageKeys()).toMatchValues({
+ patternMessageKeysValidationErrors: { keys: [error] },
+ isPatternMessageKeysSubmitting: false,
+ })
+ expect(patch).not.toHaveBeenCalled()
+ })
+
+ it('preserves the draft and allows retrying after a failed save', async () => {
+ patch.mockResolvedValueOnce([500, { detail: 'Could not save settings' }])
+ logic.actions.setPatternMessageKeysValue('keys', [])
+ await expectLogic(logic, () => logic.actions.submitPatternMessageKeys())
+ .toDispatchActions(['submitPatternMessageKeysFailure'])
+ .toMatchValues({
+ logsConfig: config,
+ patternMessageKeys: { keys: [] },
+ patternMessageKeysChanged: true,
+ isPatternMessageKeysSubmitting: false,
+ })
+ await expectLogic(logic, () => logic.actions.submitPatternMessageKeys()).toDispatchActions([
+ 'submitPatternMessageKeysSuccess',
+ ])
+ })
+})
diff --git a/products/logs/frontend/logsConfigLogic.ts b/products/logs/frontend/logsConfigLogic.ts
index 1f79eb2c4cab..934a43c0e193 100644
--- a/products/logs/frontend/logsConfigLogic.ts
+++ b/products/logs/frontend/logsConfigLogic.ts
@@ -1,9 +1,13 @@
-import { MakeLogicType, afterMount, connect, kea, path, selectors } from 'kea'
+import { MakeLogicType, afterMount, connect, kea, listeners, path, selectors } from 'kea'
+import { forms } from 'kea-forms'
+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
import api from 'lib/api'
import { teamLogic } from 'scenes/teamLogic'
+import type { TeamLogsConfigApi } from './generated/api.schemas'
+
// Mirrors the backend default in products/logs/backend/models.py — the convention
// documented at https://posthog.com/docs/logs/link-session-replay. Used as the
// pre-load fallback for the attribute-key caption in `PersonLogsTab` before
@@ -16,11 +20,11 @@ export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS = [DEFAULT_LOGS_DISTINCT_ID
// detection checks keys in list order and the first match wins.
export const DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ['sessionId']
-export interface LogsConfig {
- // Legacy single-key alias — always the first entry of logs_distinct_id_attribute_keys.
- logs_distinct_id_attribute_key: string
- logs_distinct_id_attribute_keys: string[]
- logs_session_id_attribute_keys: string[]
+export const DEFAULT_LOGS_PATTERN_MESSAGE_KEYS = ['message', 'msg', 'event']
+
+async function saveLogsConfig(teamId: number | null, patch: Partial<TeamLogsConfigApi>): Promise<TeamLogsConfigApi> {
+ // nosemgrep: prefer-codegen-api
+ return await api.update(`api/projects/${teamId}/logs_config/`, patch)
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -28,8 +32,32 @@ export interface logsConfigLogicValues {
currentTeamId: number | null // teamLogic
configuredDistinctIdKeys: string[] | undefined
configuredSessionIdKeys: string[] | undefined
- logsConfig: LogsConfig | null
+ isPatternMessageKeysSubmitting: boolean
+ isPatternMessageKeysValid: boolean
+ logsConfig: TeamLogsConfigApi | null
logsConfigLoading: boolean
+ patternMessageKeys: {
+ keys: string[]
+ }
+ patternMessageKeysAllErrors: Record<string, any>
+ patternMessageKeysChanged: boolean
+ patternMessageKeysErrors: DeepPartialMap<
+ {
+ keys: string[]
+ },
+ ValidationErrorType
+ >
+ patternMessageKeysHasErrors: boolean
+ patternMessageKeysManualErrors: Record<string, any>
+ patternMessageKeysTouched: boolean
+ patternMessageKeysTouches: Record<string, boolean>
+ patternMessageKeysValidationErrors: DeepPartialMap<
+ {
+ keys: string[]
+ },
+ ValidationErrorType
+ >
+ showPatternMessageKeysErrors: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -43,13 +71,60 @@ export interface logsConfigLogicActions {
errorObject?: any
}
loadLogsConfigSuccess: (
- logsConfig: LogsConfig,
+ logsConfig: TeamLogsConfigApi,
payload?: any
) => {
- logsConfig: LogsConfig
+ logsConfig: TeamLogsConfigApi
payload?: any
}
- updateLogsConfig: (patch: Partial<LogsConfig>) => Partial<LogsConfig>
+ resetPatternMessageKeys: (values?: { keys: string[] }) => {
+ values?: {
+ keys: string[]
+ }
+ }
+ setPatternMessageKeysManualErrors: (errors: Record<string, any>) => {
+ errors: Record<string, any>
+ }
+ setPatternMessageKeysValue: (
+ key: FieldName,
+ value: any
+ ) => {
+ name: FieldName
+ value: any
+ }
+ setPatternMessageKeysValues: (
+ values: DeepPartial<{
+ keys: string[]
+ }>
+ ) => {
+ values: DeepPartial<{
+ keys: string[]
+ }>
+ }
+ submitPatternMessageKeys: () => {
+ value: boolean
+ }
+ submitPatternMessageKeysFailure: (
+ error: Error,
+ errors: Record<string, any>
+ ) => {
+ error: Error
+ errors: Record<string, any>
+ }
+ submitPatternMessageKeysRequest: (patternMessageKeys: { keys: string[] }) => {
+ patternMessageKeys: {
+ keys: string[]
+ }
+ }
+ submitPatternMessageKeysSuccess: (patternMessageKeys: { keys: string[] }) => {
+ patternMessageKeys: {
+ keys: string[]
+ }
+ }
+ touchPatternMessageKeysField: (key: string) => {
+ key: string
+ }
+ updateLogsConfig: (patch: Partial<TeamLogsConfigApi>) => Partial<TeamLogsConfigApi>
updateLogsConfigFailure: (
error: string,
errorObject?: any
@@ -58,19 +133,19 @@ export interface logsConfigLogicActions {
errorObject?: any
}
updateLogsConfigSuccess: (
- logsConfig: LogsConfig,
- payload?: Partial<LogsConfig>
+ logsConfig: TeamLogsConfigApi,
+ payload?: Partial<TeamLogsConfigApi>
) => {
- logsConfig: LogsConfig
- payload?: Partial<LogsConfig>
+ logsConfig: TeamLogsConfigApi
+ payload?: Partial<TeamLogsConfigApi>
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsConfigLogicMeta {
__keaTypeGenInternalSelectorTypes: {
- configuredDistinctIdKeys: (logsConfig: LogsConfig | null) => string[] | undefined
- configuredSessionIdKeys: (logsConfig: LogsConfig | null) => string[] | undefined
+ configuredDistinctIdKeys: (logsConfig: TeamLogsConfigApi | null) => string[] | undefined
+ configuredSessionIdKeys: (logsConfig: TeamLogsConfigApi | null) => string[] | undefined
}
}
@@ -84,17 +159,41 @@ export type logsConfigLogicType = MakeLogicType<
export const logsConfigLogic = kea<logsConfigLogicType>([
path(['products', 'logs', 'frontend', 'logsConfigLogic']),
connect({ values: [teamLogic, ['currentTeamId']] }),
+ forms(({ actions, values }) => ({
+ patternMessageKeys: {
+ defaults: { keys: DEFAULT_LOGS_PATTERN_MESSAGE_KEYS },
+ errors: ({ keys }) => {
+ const cleaned = keys.map((key) => key.trim())
+ const error =
+ cleaned.length > 10
+ ? 'Use at most 10 keys.'
+ : cleaned.some((key) => !key)
+ ? 'Keys cannot be blank.'
+ : cleaned.some((key) => key.length > 200)
+ ? 'Each key must be 200 characters or fewer.'
+ : new Set(cleaned).size !== cleaned.length
+ ? 'Keys must be unique.'
+ : undefined
+ return { keys: error ? [error] : undefined }
+ },
+ submit: async ({ keys }) => {
+ const config = await saveLogsConfig(values.currentTeamId, {
+ logs_pattern_message_keys: keys.map((key) => key.trim()),
+ })
+ actions.updateLogsConfigSuccess(config)
+ },
+ },
+ })),
loaders(({ values }) => ({
logsConfig: [
- null as LogsConfig | null,
+ null as TeamLogsConfigApi | null,
{
- loadLogsConfig: async (): Promise<LogsConfig> => {
+ loadLogsConfig: async (): Promise<TeamLogsConfigApi> => {
// nosemgrep: prefer-codegen-api
return await api.get(`api/projects/${values.currentTeamId}/logs_config/`)
},
- updateLogsConfig: async (patch: Partial<LogsConfig>): Promise<LogsConfig> => {
- // nosemgrep: prefer-codegen-api
- return await api.update(`api/projects/${values.currentTeamId}/logs_config/`, patch)
+ updateLogsConfig: async (patch: Partial<TeamLogsConfigApi>): Promise<TeamLogsConfigApi> => {
+ return await saveLogsConfig(values.currentTeamId, patch)
},
},
],
@@ -104,15 +203,27 @@ export const logsConfigLogic = kea<logsConfigLogicType>([
// built-in convention list (which contains the default) in the meantime.
configuredDistinctIdKeys: [
(s) => [s.logsConfig],
- (logsConfig: LogsConfig | null): string[] | undefined => logsConfig?.logs_distinct_id_attribute_keys,
+ (logsConfig: TeamLogsConfigApi | null): string[] | undefined => logsConfig?.logs_distinct_id_attribute_keys,
],
// Undefined until logs_config resolves — session detection falls back to its
// built-in convention list (which contains the default) in the meantime.
configuredSessionIdKeys: [
(s) => [s.logsConfig],
- (logsConfig: LogsConfig | null): string[] | undefined => logsConfig?.logs_session_id_attribute_keys,
+ (logsConfig: TeamLogsConfigApi | null): string[] | undefined => logsConfig?.logs_session_id_attribute_keys,
],
}),
+ listeners(({ actions }) => ({
+ loadLogsConfigSuccess: ({ logsConfig }) => {
+ actions.resetPatternMessageKeys({
+ keys: logsConfig.logs_pattern_message_keys ?? DEFAULT_LOGS_PATTERN_MESSAGE_KEYS,
+ })
+ },
+ updateLogsConfigSuccess: ({ logsConfig }) => {
+ actions.resetPatternMessageKeys({
+ keys: logsConfig.logs_pattern_message_keys ?? DEFAULT_LOGS_PATTERN_MESSAGE_KEYS,
+ })
+ },
+ })),
afterMount(({ actions }) => {
actions.loadLogsConfig()
}),
diff --git a/products/logs/mcp/tools.yaml b/products/logs/mcp/tools.yaml
index 2bef7b9cb34c..76ca1424fafb 100644
--- a/products/logs/mcp/tools.yaml
+++ b/products/logs/mcp/tools.yaml
@@ -572,6 +572,12 @@ tools:
logs-views-update:
operation: logs_views_update
enabled: false
+ organizations-projects-logs-config-partial-update:
+ operation: organizations_projects_logs_config_partial_update
+ enabled: false
+ organizations-projects-logs-config-retrieve:
+ operation: organizations_projects_logs_config_retrieve
+ enabled: false
query-logs:
operation: logs_query_create
enabled: true
diff --git a/services/mcp/definitions/core.yaml b/services/mcp/definitions/core.yaml
index 327551ef76ee..ce45a6b20d28 100644
--- a/services/mcp/definitions/core.yaml
+++ b/services/mcp/definitions/core.yaml
@@ -319,12 +319,6 @@ tools:
organizations-projects-experiments-config-retrieve:
operation: organizations_projects_experiments_config_retrieve
enabled: false
- organizations-projects-logs-config-partial-update:
- operation: organizations_projects_logs_config_partial_update
- enabled: false
- organizations-projects-logs-config-retrieve:
- operation: organizations_projects_logs_config_retrieve
- enabled: false
organizations-projects-settings-as-of-retrieve:
operation: organizations_projects_settings_as_of_retrieve
enabled: false
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 78436027fcb7..a682fcbe10aa 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -70196,6 +70196,29 @@ export namespace Schemas {
channel?: string | null;
}
+ export interface PatchedTeamLogsConfig {
+ /** Legacy single-key alias — always the first entry of `logs_distinct_id_attribute_keys`. Read-only; write the plural field instead. */
+ readonly logs_distinct_id_attribute_key?: string;
+ /**
+ * Log attribute keys whose values should match a person's distinct_id — a log links to a person when any of these attributes equals one of their distinct IDs. Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to ['posthogDistinctId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the person identifier under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_distinct_id_attribute_keys?: string[];
+ /**
+ * Ordered list of log attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_session_id_attribute_keys?: string[];
+ /**
+ * Ordered list of top-level JSON keys whose value is the message text that log patterns are derived from. Keys are matched literally at the top level of the log body; a dot in a key is part of the key name, not a path into nested objects. Selection checks keys in order; the first key whose value is a non-empty string wins. Defaults to ['message', 'msg', 'event']. An empty list turns message extraction off, so JSON log bodies group by their key set instead. The stored log body is never changed by this setting.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_pattern_message_keys?: string[];
+ }
+
export interface PatchedTeamTracingConfig {
/**
* Span or resource attribute keys whose values should match a person's distinct_id — a span links to a person when any of these attributes holds one of their distinct IDs. Defaults to ['posthogDistinctId'], the key the posthog-js / posthog-react-native SDKs attach to the OTel signals they emit. Add keys only if your pipeline emits the person identifier under different attributes.
@@ -88502,6 +88525,29 @@ export namespace Schemas {
readonly sending_allowance: EmailSendingAllowance | null;
}
+ export interface TeamLogsConfig {
+ /** Legacy single-key alias — always the first entry of `logs_distinct_id_attribute_keys`. Read-only; write the plural field instead. */
+ readonly logs_distinct_id_attribute_key: string;
+ /**
+ * Log attribute keys whose values should match a person's distinct_id — a log links to a person when any of these attributes equals one of their distinct IDs. Used by the person profile Logs tab and the `query-logs` MCP tool. Defaults to ['posthogDistinctId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the person identifier under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_distinct_id_attribute_keys: string[];
+ /**
+ * Ordered list of log attribute keys whose values hold the PostHog session ID. Detection checks keys in order, then falls back to common session ID attribute conventions; the first key with a value wins. Defaults to ['sessionId'] — the convention documented at https://posthog.com/docs/logs/link-session-replay and the key the posthog-js / posthog-react-native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_session_id_attribute_keys: string[];
+ /**
+ * Ordered list of top-level JSON keys whose value is the message text that log patterns are derived from. Keys are matched literally at the top level of the log body; a dot in a key is part of the key name, not a path into nested objects. Selection checks keys in order; the first key whose value is a non-empty string wins. Defaults to ['message', 'msg', 'event']. An empty list turns message extraction off, so JSON log bodies group by their key set instead. The stored log body is never changed by this setting.
+ * @maxItems 10
+ * @items.maxLength 200
+ */
+ logs_pattern_message_keys: string[];
+ }
+
export const TeamMCPGatewayConfigMemberDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const
export const TeamMCPGatewayConfigAgentDefaultPreset = {...MCPPolicyPresetEnum,...BlankEnum,} as const
export interface TeamMCPGatewayConfig {