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 the JSON parse log attribute setting (#100759)

Jon McCallum7b5d0bbc9487
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdx
index 0a7a2e25581b..227c931032af 100644
--- a/docs/published/docs/logs/logs-config.mdx
+++ b/docs/published/docs/logs/logs-config.mdx
@@ -57,3 +57,18 @@ This setting changes only how patterns are derived. The stored log body is never
## Propagation
A change reaches log ingestion within a few minutes. Records ingested in that window keep the patterns derived from the previous configuration.
+
+## JSON attribute parsing configuration
+
+In **Settings > Project > Logs > JSON parse log attribute**, enter one attribute key and select **Save**. Clear the key and save to turn it off. This setting is independent of **JSON parse logs**, which parses the log body. The control uses the same project-admin and Logs Editor restrictions as the other Logs settings.
+
+The `logs-json-attribute-parsing` feature flag controls the setting's visibility. Saving or clearing the key uses the existing project API permissions and does not require that flag.
+
+The project API stores the key in `logs_settings.json_parse_logs_attribute_key`, separately from the `logs_config` endpoint above:
+
+- The value must be a string. Leading and trailing whitespace is trimmed, and the trimmed key can be at most 200 characters.
+- The key is matched literally, including dots.
+- The default is off. An empty string disables parsing.
+- The API replaces the entire `logs_settings` object. Include the other current settings when updating it, as the UI does. Sending `logs_settings: null` clears all Logs settings.
+
+Saving a key records your choice. Ingestion does not read it yet, so no fields are extracted from the attribute.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 4a37c49c347e..fd462e851358 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -9948,6 +9948,18 @@ snapshots:
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-json-parsing--dark:
+ hash: v1.k794b7964.a89186c997dcd395692893231d52d457df7fa64ec154e0defd88baf99cc8099a.xH6fqBcnWPtnc7IyPYreeC8VziWL4UfaTMI4BYTf1ig
+ scenes-app-settings-project--settings-project-logs-json-parsing--light:
+ hash: v1.k794b7964.4ea3e60d1dcde31f4cbf83d72c11abd82f0b361dca787c745fd48d9b18b0828d.NyJPwlLG7lNjiljm924JjmbRG4fENhwyEvMNkVY_cs4
+ scenes-app-settings-project--settings-project-logs-json-parsing-flag-off--dark:
+ hash: v1.k794b7964.f7c7cba0b4c2a24e13d16a45d2cbe9a2552537fea7601ce304f5f47a27c9fa7f.5rMxKeTX6477lSe2NgCz-lymXydmlFrOSs9huOA6G1I
+ scenes-app-settings-project--settings-project-logs-json-parsing-flag-off--light:
+ hash: v1.k794b7964.f7df29cade88c11f4f11f04666d7fc284d90b3097bcf0409490e8a0de4bfc9d5.LyGeqPBa8mnx7r-NpFPbtDhuytK_J_6fGgwfLe_KRNc
+ scenes-app-settings-project--settings-project-logs-json-parsing-read-only--dark:
+ hash: v1.k794b7964.d3f34d2173a80fc5135f8bf506cd90bc7734a541b79ba6b591151ed919d8a449.-lqoaQrlCedRQgNlfFbEDwHa87HTARVDZMQ3Cc6wZTA
+ scenes-app-settings-project--settings-project-logs-json-parsing-read-only--light:
+ hash: v1.k794b7964.719265f98039ff59380c147bf41c0dcbc1ddfd8be84a3c4854b60c73d602722d.s3InBhoh2dbEckM1edlrinZmXUb-0LNYrL-V7qOrwsE
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:
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index ff47d1d03784..b9f77b53ae7c 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -370,6 +370,7 @@ export const FEATURE_FLAGS = {
LOGS_ANOMALIES: 'logs-anomalies', // owner: @jonmcwest #team-logs
LOGS_IMPACT_STRIP: 'logs-impact-strip', // owner: #team-logs
LOGS_IN_ERROR_TRACKING: 'logs-in-error-tracking', // owner: @jonmcwest #team-logs
+ LOGS_JSON_ATTRIBUTE_PARSING: 'logs-json-attribute-parsing', // owner: #team-logs
LOGS_SERVICES_VIEW: 'logs-services-view', // owner: #team-logs
LOGS_SERVICES_VIEW_V2: 'logs-services-view-v2', // owner: #team-logs
LOGS_SESSION_ERROR_BADGES: 'logs-session-error-badges', // owner: #team-logs
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index ccdcb9fd513c..c19566b033a4 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -123,6 +123,7 @@ import {
LogsRetentionSettings,
} from './environment/LogsCaptureSettings'
import { LogsDistinctIdAttributeKeys } from './environment/LogsDistinctIdAttributeKeys'
+import { LogsJsonParseAttributeSettings } from './environment/LogsJsonParseAttributeSettings'
import { LogsPatternMessageKeys } from './environment/LogsPatternMessageKeys'
import { LogsSessionIdAttributeKeys } from './environment/LogsSessionIdAttributeKeys'
import { ManagedReverseProxy } from './environment/ManagedReverseProxy'
@@ -892,6 +893,16 @@ export const SETTINGS_MAP: SettingSection[] = [
flag: 'LOGS_SETTINGS_JSON',
keywords: ['json', 'parse', 'structured', 'format'],
},
+ {
+ id: 'logs-json-parse-attribute',
+ title: 'JSON parse log attribute',
+ description:
+ 'Choose a log attribute containing JSON to make its nested fields available in filters. This works independently of JSON parse logs.',
+ docsUrl: 'https://posthog.com/docs/logs/logs-config',
+ component: <LogsJsonParseAttributeSettings />,
+ flag: 'LOGS_JSON_ATTRIBUTE_PARSING',
+ keywords: ['json', 'parse', 'attributes', 'nested', 'structured'],
+ },
{
id: 'logs-pii-scrub',
title: 'PII scrubbing',
diff --git a/frontend/src/scenes/settings/environment/LogsJsonParseAttributeSettings.tsx b/frontend/src/scenes/settings/environment/LogsJsonParseAttributeSettings.tsx
new file mode 100644
index 000000000000..f29720e59d19
--- /dev/null
+++ b/frontend/src/scenes/settings/environment/LogsJsonParseAttributeSettings.tsx
@@ -0,0 +1,75 @@
+import { useActions, useValues } from 'kea'
+import { useEffect, useState } from 'react'
+
+import { LemonButton, LemonInput, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { AccessControlAction } from 'lib/components/AccessControlAction'
+import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'
+import { TeamMembershipLevel } from 'lib/constants'
+import { teamLogic } from 'scenes/teamLogic'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+export function LogsJsonParseAttributeSettings(): JSX.Element {
+ const { currentTeam, currentTeamLoading } = useValues(teamLogic)
+ const { updateCurrentTeam } = useActions(teamLogic)
+ const restrictedReason = useRestrictedArea({
+ scope: RestrictionScope.Project,
+ minimumAccessLevel: TeamMembershipLevel.Admin,
+ })
+ const savedKey = currentTeam?.logs_settings?.json_parse_logs_attribute_key ?? ''
+ const [value, setValue] = useState(savedKey)
+
+ useEffect(() => {
+ setValue(savedKey)
+ }, [savedKey])
+
+ if (!currentTeam) {
+ return <LemonSkeleton className="w-1/2 h-4" />
+ }
+
+ const trimmed = value.trim()
+
+ return (
+ <div className="deprecated-space-y-4">
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Logs}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonInput
+ value={value}
+ onChange={setValue}
+ maxLength={200}
+ placeholder="e.g. attributes"
+ aria-label="JSON log attribute key"
+ disabled={currentTeamLoading || !!restrictedReason}
+ data-attr="logs-json-parse-attribute-key"
+ className="max-w-md"
+ />
+ </AccessControlAction>
+ <p className="text-secondary text-sm max-w-200">
+ Parse JSON in this log attribute on new logs. Nested fields become dotted attributes, such as{' '}
+ <code>attributes.sessionId</code>. PostHog adds up to 50 fields per log. Use those keys in Link to
+ person or Link to session. The original attribute and existing values are kept. Invalid JSON is left
+ unchanged. Clear the key and save to disable.
+ </p>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Logs}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ <LemonButton
+ type="primary"
+ onClick={() =>
+ updateCurrentTeam({
+ logs_settings: { ...currentTeam.logs_settings, json_parse_logs_attribute_key: trimmed },
+ })
+ }
+ disabledReason={restrictedReason || (trimmed === savedKey ? 'No changes to save' : undefined)}
+ loading={currentTeamLoading}
+ >
+ Save
+ </LemonButton>
+ </AccessControlAction>
+ </div>
+ )
+}
diff --git a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
index 571ddf91f897..61e377c41b35 100644
--- a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
@@ -3,13 +3,14 @@ import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
import type { Meta, StoryObj } from '@storybook/react'
import { router } from 'kea-router'
-import { STORYBOOK_FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
+import { FEATURE_FLAGS, 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'
import preflightJson from '~/mocks/fixtures/_preflight.json'
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { SettingSectionId } from '../types'
@@ -45,11 +46,16 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {
'/api/projects/:id/tags': ['eu-region', 'production'],
},
patch: {
- '/api/projects/:id': async ({ request }) => {
- // bounce the setting back as is
- const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) }
- return [200, newTeamSettings]
- },
+ // bounce the setting back as is. `updateCurrentTeam` patches the environment for
+ // everything except a bare project rename, so both routes need a handler.
+ '/api/projects/:id': async ({ request }) => [
+ 200,
+ { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) },
+ ],
+ '/api/environments/:id': async ({ request }) => [
+ 200,
+ { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) },
+ ],
},
}),
],
@@ -127,3 +133,34 @@ export const SettingsProjectLogsReadOnly: Story = {
return <App />
},
}
+
+export const SettingsProjectLogsJsonParsing: Story = {
+ ...SettingsProjectLogs,
+ parameters: {
+ featureFlags: [FEATURE_FLAGS.LOGS_SETTINGS_JSON, FEATURE_FLAGS.LOGS_JSON_ATTRIBUTE_PARSING],
+ },
+ beforeEach: () => {
+ const appContext = window.POSTHOG_APP_CONTEXT
+ if (!appContext) {
+ return
+ }
+ const originalAccess = appContext.resource_access_control
+ appContext.resource_access_control = {
+ ...originalAccess,
+ [AccessControlResourceType.Logs]: AccessControlLevel.Manager,
+ }
+ return () => {
+ appContext.resource_access_control = originalAccess
+ }
+ },
+}
+
+export const SettingsProjectLogsJsonParsingReadOnly: Story = {
+ ...SettingsProjectLogsJsonParsing,
+ render: SettingsProjectLogsReadOnly.render,
+}
+
+export const SettingsProjectLogsJsonParsingFlagOff: Story = {
+ ...SettingsProjectLogsJsonParsing,
+ parameters: { featureFlags: [FEATURE_FLAGS.LOGS_SETTINGS_JSON] },
+}
diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.ts
index a0fe87943788..a56ffaacf945 100644
--- a/frontend/src/scenes/settings/types.ts
+++ b/frontend/src/scenes/settings/types.ts
@@ -206,6 +206,7 @@ export type SettingId =
| 'logs-distinct-id-attribute-key'
| 'logs-drop-rules'
| 'logs-json-parse'
+ | 'logs-json-parse-attribute'
| 'logs-metric-rules'
| 'logs-pattern-message-keys'
| 'logs-pii-scrub'
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 221dce99635c..32212ffb9dd4 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -802,6 +802,7 @@ export interface ConversationsSettings {
export interface LogsSettings {
capture_console_logs?: boolean
json_parse_logs?: boolean
+ json_parse_logs_attribute_key?: string
pii_scrub_logs?: boolean
retention_days?: number
retention_last_updated?: string
diff --git a/posthog/api/team.py b/posthog/api/team.py
index d226f607fd30..cc9ac5d13e35 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -1864,6 +1864,20 @@ class TeamSerializer(serializers.ModelSerializer, UserPermissionsSerializerMixin
if value is None:
return value
+ if not isinstance(value, dict):
+ raise exceptions.ValidationError("logs_settings must be an object or null.")
+
+ if "json_parse_logs_attribute_key" in value:
+ attribute_key = value["json_parse_logs_attribute_key"]
+ # Length is measured after trimming, matching CharField(trim_whitespace=True,
+ # max_length=200) on the logs_config key lists.
+ if not isinstance(attribute_key, str) or len(attribute_key.strip()) > 200:
+ raise exceptions.ValidationError(
+ "json_parse_logs_attribute_key must be a string of at most 200 characters. "
+ "Use an empty string to disable parsing."
+ )
+ value["json_parse_logs_attribute_key"] = attribute_key.strip()
+
new_retention = value.get("retention_days")
if new_retention is not None and new_retention not in TeamSerializer.VALID_RETENTION_DAYS:
raise exceptions.ValidationError(
diff --git a/posthog/api/test/test_team.py b/posthog/api/test/test_team.py
index e3376f6f16d0..acd6f200c1fc 100644
--- a/posthog/api/test/test_team.py
+++ b/posthog/api/test/test_team.py
@@ -2003,6 +2003,52 @@ def team_api_test_factory():
)
assert "retention_days must be one of" in response.json()["detail"]
+ @parameterized.expand(
+ [
+ (" app.context ", "app.context"),
+ ("", ""),
+ (" " + "a" * 200 + " ", "a" * 200),
+ (" \t" + "😀" * 200 + "\n ", "😀" * 200),
+ ("\u001c\u001d\u001e\u001f\u0085" + "😀" * 200 + "\u3000\u00a0", "😀" * 200),
+ ("\ufeff" + "a" * 199, "\ufeff" + "a" * 199),
+ ]
+ )
+ def test_logs_settings_json_attribute_key(self, key, expected):
+ existing_settings = {
+ "retention_days": 14,
+ "json_parse_logs": False,
+ "pii_scrub_logs": True,
+ "future_setting": {"enabled": True},
+ }
+ self.team.logs_settings = existing_settings
+ self.team.save()
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {**existing_settings, "json_parse_logs_attribute_key": key}},
+ )
+ assert response.status_code == status.HTTP_200_OK
+ self.team.refresh_from_db()
+ expected_settings = {**existing_settings, "json_parse_logs_attribute_key": expected}
+ assert self.team.logs_settings == expected_settings
+ assert response.json()["logs_settings"] == expected_settings
+
+ @parameterized.expand([(123,), ("😀" * 201,), ("\ufeff" + "a" * 200,)])
+ def test_logs_settings_invalid_json_attribute_key(self, key):
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": {"json_parse_logs_attribute_key": key}},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "json_parse_logs_attribute_key must be a string" in response.json()["detail"]
+
+ def test_logs_settings_must_be_an_object(self):
+ response = self.client.patch(
+ "/api/environments/@current/",
+ {"logs_settings": "json_parse_logs_attribute_key"},
+ )
+ assert response.status_code == status.HTTP_400_BAD_REQUEST
+ assert "logs_settings must be an object" in response.json()["detail"]
+
def test_logs_settings_retention_requires_matching_feature(self):
response = self.client.patch(
"/api/environments/@current/",
@@ -2060,6 +2106,7 @@ def team_api_test_factory():
"logs_settings": {
"retention_days": 14, # Same retention
"json_parse_logs": True,
+ "json_parse_logs_attribute_key": "context",
}
},
)
@@ -3723,6 +3770,24 @@ _TOO_MANY_WILDCARDS = ["https://*.*.*.*.*.*.example.com"]
class TestTeamSerializerValidationNoDB(SimpleTestCase):
+ @parameterized.expand([(None,), (True,), (123,), ([],), ({},), ("a" * 201,)])
+ def test_invalid_logs_json_attribute_key(self, key):
+ self._assert_field_error(
+ "logs_settings",
+ {"json_parse_logs_attribute_key": key},
+ "invalid",
+ "json_parse_logs_attribute_key must be a string of at most 200 characters. "
+ "Use an empty string to disable parsing.",
+ )
+
+ @parameterized.expand(
+ [("context", "context"), (" app.context ", "app.context"), (" ", ""), (" " + "a" * 200 + " ", "a" * 200)]
+ )
+ def test_normalize_logs_json_attribute_key(self, key, expected):
+ assert TeamSerializer().validate_logs_settings({"json_parse_logs_attribute_key": key}) == {
+ "json_parse_logs_attribute_key": expected
+ }
+
# Field-level input validation runs inside `is_valid()` (in `to_internal_value`),
# before the object-level `validate()` that needs request context — so these never
# touch the DB. `.errors` carries DRF's raw code (`invalid`); the HTTP envelope's
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index 809625d76ef9..21d2c3842523 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -1291,6 +1291,7 @@ class TestLogsPersonIdFilter(_LogsScopeFilterTestMixin, ClickhouseTestMixin, API
[
("single_key", ["team_ref"], {"team_ref"}),
("multiple_keys", ["team_ref", "account_ref"], {"team_ref", "account_ref"}),
+ ("flattened_json_key", ["attributes.personId"], {"attributes.personId"}),
]
)
def test_person_id_respects_configured_attribute_keys(
@@ -1307,6 +1308,7 @@ class TestLogsPersonIdFilter(_LogsScopeFilterTestMixin, ClickhouseTestMixin, API
[
self._log_row("person-id-test-cfg", attribute_key="team_ref"),
self._log_row("person-id-test-cfg", attribute_key="account_ref"),
+ self._log_row("person-id-test-cfg", attribute_key="attributes.personId"),
]
)
diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.ts
index 5ba35ea836a8..07a8c259cc5c 100644
--- a/products/logs/frontend/utils.test.ts
+++ b/products/logs/frontend/utils.test.ts
@@ -55,12 +55,14 @@ describe('logs utils', () => {
})
describe('getDistinctIdWithKey', () => {
- it('prefers a configured key over a convention, and attributes over resource_attributes', () => {
+ it.each(['user.id', 'attributes.personId'])('prefers configured key %s over a convention', (configuredKey) => {
expect(
- getDistinctIdWithKey({ distinct_id: 'convention', 'user.id': 'configured' }, undefined, ['user.id'])
- ).toEqual({ key: 'user.id', value: 'configured', source: 'attribute' })
- expect(getDistinctIdWithKey({}, { 'user.id': 'configured' }, ['user.id'])).toEqual({
- key: 'user.id',
+ getDistinctIdWithKey({ distinct_id: 'convention', [configuredKey]: 'configured' }, undefined, [
+ configuredKey,
+ ])
+ ).toEqual({ key: configuredKey, value: 'configured', source: 'attribute' })
+ expect(getDistinctIdWithKey({}, { [configuredKey]: 'configured' }, [configuredKey])).toEqual({
+ key: configuredKey,
value: 'configured',
source: 'resource_attribute',
})
@@ -134,6 +136,16 @@ describe('logs utils', () => {
describe('configured session ID keys', () => {
it.each([
+ [
+ 'flattened JSON attribute is matched literally',
+ ['attributes.sessionId'],
+ {
+ attributes: '{"sessionId":"01901234-5678-7000-8000-000000000001"}',
+ 'attributes.sessionId': '01901234-5678-7000-8000-000000000001',
+ },
+ undefined,
+ '01901234-5678-7000-8000-000000000001',
+ ],
[
'configured key wins over a built-in convention key',
['my.custom.key'],