: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 configurable session id attribute keys setting (#70414)
Jon McCallum38e1b869f873
diff --git a/frontend/src/generated/core/api.ts b/frontend/src/generated/core/api.tsindex 7cdf6f126dba..98516f99a798 100644--- a/frontend/src/generated/core/api.ts+++ b/frontend/src/generated/core/api.ts@@ -1103,8 +1103,9 @@ export const getOrganizationsProjectsLogsConfigRetrieveUrl = (organizationId: st/*** Manage logs product configuration for this project's canonical environment.- * Mirrors the env-router action so /api/projects/:id/logs_config/ resolves- * alongside the legacy /api/environments/:id/logs_config/ alias.+ * 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,@@ -1123,8 +1124,9 @@ export const getOrganizationsProjectsLogsConfigPartialUpdateUrl = (organizationI/*** Manage logs product configuration for this project's canonical environment.- * Mirrors the env-router action so /api/projects/:id/logs_config/ resolves- * alongside the legacy /api/environments/:id/logs_config/ alias.+ * 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,diff --git a/frontend/src/generated/core/api.zod.ts b/frontend/src/generated/core/api.zod.tsindex 5ee4ffcedaf8..0c78dd3e7876 100644--- a/frontend/src/generated/core/api.zod.ts+++ b/frontend/src/generated/core/api.zod.ts@@ -7082,8 +7082,9 @@ export const OrganizationsProjectsGenerateConversationsPublicTokenCreateBody = //*** Manage logs product configuration for this project's canonical environment.- * Mirrors the env-router action so /api/projects/:id/logs_config/ resolves- * alongside the legacy /api/environments/:id/logs_config/ alias.+ * 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 organizationsProjectsLogsConfigPartialUpdateBodyNameMax = 200diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsxindex aaa17f671fd2..8d674b54f53c 100644--- a/frontend/src/scenes/settings/SettingsMap.tsx+++ b/frontend/src/scenes/settings/SettingsMap.tsx@@ -101,6 +101,7 @@ import {LogsRetentionSettings,} from './environment/LogsCaptureSettings'import { LogsDistinctIdAttributeKey } from './environment/LogsDistinctIdAttributeKey'+import { LogsSessionIdAttributeKeys } from './environment/LogsSessionIdAttributeKeys'import { ManagedReverseProxy } from './environment/ManagedReverseProxy'import { MarketingAnalyticsSettingsWrapper } from './environment/MarketingAnalyticsSettingsWrapper'import MCPServerSettings from './environment/MCPServerSettings'@@ -775,6 +776,23 @@ export const SETTINGS_MAP: SettingSection[] = [flag: 'LOGS_SETTINGS',keywords: ['log', 'person', 'distinct', 'attribute', 'pivot', 'profile', 'link'],},+ {+ id: 'logs-session-id-attribute-keys',+ title: 'Link to session',+ description: (+ <>+ The log attributes PostHog reads to identify which session a log belongs to, checked in order+ with the first match winning. Defaults to <code>posthogSessionId</code>, the key the JavaScript+ and React Native SDKs auto-attach. Add keys only if your pipeline emits the session ID under+ different attributes.+ </>+ ),+ searchDescription:+ 'The log attributes PostHog reads to identify which session a log belongs to, checked in order with the first match winning. Defaults to posthogSessionId, the key the JavaScript and React Native SDKs auto-attach. Add keys only if your pipeline emits the session ID under different attributes.',+ component: <LogsSessionIdAttributeKeys />,+ flag: 'LOGS_SETTINGS',+ keywords: ['log', 'session', 'replay', 'attribute', 'link'],+ },{id: 'logs-retention',title: 'Retention',diff --git a/frontend/src/scenes/settings/environment/LogsSessionIdAttributeKeys.tsx b/frontend/src/scenes/settings/environment/LogsSessionIdAttributeKeys.tsxnew file mode 100644index 000000000000..d168f728b383--- /dev/null+++ b/frontend/src/scenes/settings/environment/LogsSessionIdAttributeKeys.tsx@@ -0,0 +1,64 @@+import { useActions, useValues } from 'kea'+import { useEffect, useState } from 'react'++import { LemonButton } from '@posthog/lemon-ui'++import { RestrictionScope, useRestrictedArea } from 'lib/components/RestrictedArea'+import { TeamMembershipLevel } from 'lib/constants'+import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { objectsEqual } from 'lib/utils/objects'++import { DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS, logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'++export function LogsSessionIdAttributeKeys(): JSX.Element {+ const { logsConfig, logsConfigLoading } = useValues(logsConfigLogic)+ const { updateLogsConfig } = useActions(logsConfigLogic)+ const restrictedReason = useRestrictedArea({+ scope: RestrictionScope.Project,+ minimumAccessLevel: TeamMembershipLevel.Admin,+ })++ const [value, setValue] = useState<string[]>([])++ useEffect(() => {+ if (logsConfig) {+ setValue(logsConfig.logs_session_id_attribute_keys ?? DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS)+ }+ }, [logsConfig])++ if (!logsConfig && logsConfigLoading) {+ return <LemonSkeleton className="w-1/2 h-4" />+ }++ const cleaned = value.map((key) => key.trim()).filter(Boolean)+ const isDirty = !objectsEqual(cleaned, logsConfig?.logs_session_id_attribute_keys ?? [])+ const isEmpty = cleaned.length === 0++ return (+ <div className="deprecated-space-y-4">+ <LemonInputSelect+ mode="multiple"+ allowCustomValues+ value={value}+ onChange={(values: string[]) => setValue(values || [])}+ placeholder={DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS.join(', ')}+ loading={logsConfigLoading}+ disabled={!!restrictedReason}+ data-attr="logs-session-id-attribute-keys-select"+ className="max-w-md"+ />+ <LemonButton+ type="primary"+ onClick={() => updateLogsConfig({ logs_session_id_attribute_keys: cleaned })}+ disabledReason={+ restrictedReason ||+ (isEmpty ? 'At least one attribute key is required' : !isDirty ? 'No changes to save' : undefined)+ }+ loading={logsConfigLoading}+ >+ Save+ </LemonButton>+ </div>+ )+}diff --git a/frontend/src/scenes/settings/types.ts b/frontend/src/scenes/settings/types.tsindex 9923f9116d95..96f1d203cd2f 100644--- a/frontend/src/scenes/settings/types.ts+++ b/frontend/src/scenes/settings/types.ts@@ -182,6 +182,7 @@ export type SettingId =| 'logs-json-parse'| 'logs-pii-scrub'| 'logs-retention'+ | 'logs-session-id-attribute-keys'| 'marketing-settings'| 'mcp-hints'| 'mcp-servers-manage'diff --git a/posthog/api/project.py b/posthog/api/project.pyindex 42741a6fbe9f..fe40fa73c8de 100644--- a/posthog/api/project.py+++ b/posthog/api/project.py@@ -1588,13 +1588,14 @@ class ProjectViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets@action(methods=["GET", "PATCH"],detail=True,- permission_classes=[TeamMemberLightManagementPermission],+ permission_classes=[TeamMemberStrictManagementPermission],url_path="logs_config",)def logs_config(self, request: request.Request, id: str, **kwargs) -> response.Response:"""Manage logs product configuration for this project's canonical environment.- Mirrors the env-router action so /api/projects/:id/logs_config/ resolves- alongside the legacy /api/environments/:id/logs_config/ alias."""+ 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."""project = self.get_object()return handle_logs_config(request, project.passthrough_team)diff --git a/posthog/api/team.py b/posthog/api/team.pyindex c491c6edf4ad..c90ddb3532d8 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -114,10 +114,30 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):"your pipeline emits a different attribute."),)+ logs_session_id_attribute_keys = serializers.ListField(+ child=serializers.CharField(max_length=200, allow_blank=False),+ allow_empty=False,+ max_length=10,+ help_text=(+ "Ordered list of log attribute keys whose values hold the PostHog session ID. "+ "Detection checks keys in order; the first key with a value wins. Defaults to "+ "['posthogSessionId'] — the key the posthog-js / posthog-react-native SDKs "+ "auto-attach. Add keys only if your pipeline emits the session ID under "+ "different attributes."+ ),+ )class Meta:model = TeamLogsConfig- fields = ["logs_distinct_id_attribute_key"]+ fields = ["logs_distinct_id_attribute_key", "logs_session_id_attribute_keys"]++ def validate_logs_session_id_attribute_keys(self, value: list[str]) -> list[str]:+ keys = [key.strip() for key in value]+ if any(not key for key in keys):+ raise serializers.ValidationError("Attribute keys cannot be blank.")+ if len(set(keys)) != len(keys):+ raise serializers.ValidationError("Attribute keys must be unique.")+ return keysdef handle_logs_config(request: request.Request, team: Team) -> response.Response:@@ -2088,11 +2108,12 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo@action(methods=["GET", "PATCH"],detail=True,- permission_classes=[TeamMemberLightManagementPermission],+ permission_classes=[TeamMemberStrictManagementPermission],url_path="logs_config",)def logs_config(self, request: request.Request, id: str, **kwargs) -> response.Response:- """Manage logs product configuration for this environment."""+ """Manage logs product configuration for this environment. Members can read;+ writing requires project admin, matching the admin-only settings UI."""return handle_logs_config(request, self.get_object())@action(diff --git a/posthog/api/test/test_team_logs_config.py b/posthog/api/test/test_team_logs_config.pyindex 0587fdd04423..f3da6eb5ea07 100644--- a/posthog/api/test/test_team_logs_config.py+++ b/posthog/api/test/test_team_logs_config.py@@ -1,8 +1,11 @@from posthog.test.base import APIBaseTest+from django.test import SimpleTestCase+from parameterized import parameterizedfrom rest_framework import status+from posthog.api.team import TeamLogsConfigSerializerfrom posthog.models import OrganizationMembership, Teamfrom posthog.models.team.extensions import get_or_create_team_extension@@ -12,6 +15,11 @@ from products.logs.backend.models import TeamLogsConfig# remains as the back-compat alias. See `handle_logs_config` in posthog/api/team.py.URL_PREFIXES = [("projects", "api/projects"), ("environments", "api/environments")]+DEFAULT_CONFIG = {+ "logs_distinct_id_attribute_key": "posthogDistinctId",+ "logs_session_id_attribute_keys": ["posthogSessionId"],+}+class TestTeamLogsConfig(APIBaseTest):def setUp(self):@@ -23,11 +31,11 @@ class TestTeamLogsConfig(APIBaseTest):return f"/{prefix}/{self.team.id}/logs_config/"@parameterized.expand(URL_PREFIXES)- def test_get_returns_default_attribute_key(self, _name: str, prefix: str):+ def test_get_returns_defaults(self, _name: str, prefix: str):response = self.client.get(self._url(prefix))self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"logs_distinct_id_attribute_key": "posthogDistinctId"})+ self.assertEqual(response.json(), DEFAULT_CONFIG)@parameterized.expand(URL_PREFIXES)def test_patch_updates_attribute_key(self, _name: str, prefix: str):@@ -38,7 +46,7 @@ class TestTeamLogsConfig(APIBaseTest):)self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"logs_distinct_id_attribute_key": "user.id"})+ self.assertEqual(response.json()["logs_distinct_id_attribute_key"], "user.id")config = get_or_create_team_extension(self.team, TeamLogsConfig)self.assertEqual(config.logs_distinct_id_attribute_key, "user.id")@@ -52,7 +60,7 @@ class TestTeamLogsConfig(APIBaseTest):)response = self.client.get(self._url(prefix))- self.assertEqual(response.json(), {"logs_distinct_id_attribute_key": "posthog.distinct_id"})+ self.assertEqual(response.json()["logs_distinct_id_attribute_key"], "posthog.distinct_id")@parameterized.expand(URL_PREFIXES)def test_patch_rejects_key_over_max_length(self, _name: str, prefix: str):@@ -64,17 +72,21 @@ class TestTeamLogsConfig(APIBaseTest):self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)@parameterized.expand(URL_PREFIXES)- def test_regular_member_can_patch(self, _name: str, prefix: str):+ def test_regular_member_can_read_but_not_patch(self, _name: str, prefix: str):+ # Writes are admin-only, matching the admin-gated settings UI; reads stay open+ # to members so the settings page can render for everyone.self.organization_membership.level = OrganizationMembership.Level.MEMBERself.organization_membership.save()- response = self.client.patch(+ get_response = self.client.get(self._url(prefix))+ self.assertEqual(get_response.status_code, status.HTTP_200_OK)++ patch_response = self.client.patch(self._url(prefix),{"logs_distinct_id_attribute_key": "user.id"},format="json",)- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(response.json(), {"logs_distinct_id_attribute_key": "user.id"})+ self.assertEqual(patch_response.status_code, status.HTTP_403_FORBIDDEN)@parameterized.expand(URL_PREFIXES)def test_config_is_scoped_per_environment(self, _name: str, prefix: str):@@ -93,10 +105,7 @@ class TestTeamLogsConfig(APIBaseTest):)sibling_response = self.client.get(f"/{prefix}/{sibling.id}/logs_config/")- self.assertEqual(- sibling_response.json(),- {"logs_distinct_id_attribute_key": "posthogDistinctId"},- )+ self.assertEqual(sibling_response.json(), DEFAULT_CONFIG)def test_project_and_environment_share_same_config(self):# Writes via the canonical /api/projects/ URL must be visible via the@@ -108,4 +117,80 @@ class TestTeamLogsConfig(APIBaseTest):format="json",)env_response = self.client.get(f"/api/environments/{self.team.id}/logs_config/")- self.assertEqual(env_response.json(), {"logs_distinct_id_attribute_key": "user.id"})+ self.assertEqual(env_response.json()["logs_distinct_id_attribute_key"], "user.id")++ def test_patch_updates_session_id_keys_preserving_order(self):+ response = self.client.patch(+ f"/api/projects/{self.team.id}/logs_config/",+ {"logs_session_id_attribute_keys": ["session.id", "posthogSessionId"]},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["logs_session_id_attribute_keys"], ["session.id", "posthogSessionId"])++ config = get_or_create_team_extension(self.team, TeamLogsConfig)+ self.assertEqual(config.logs_session_id_attribute_keys, ["session.id", "posthogSessionId"])++ def test_partial_patch_leaves_other_field_untouched(self):+ # A naive serializer change could make a PATCH on one field reset the other+ # to its default — the two settings must update independently.+ self.client.patch(+ f"/api/projects/{self.team.id}/logs_config/",+ {"logs_session_id_attribute_keys": ["session.id"]},+ format="json",+ )+ self.client.patch(+ f"/api/projects/{self.team.id}/logs_config/",+ {"logs_distinct_id_attribute_key": "user.id"},+ format="json",+ )++ response = self.client.get(f"/api/projects/{self.team.id}/logs_config/")+ self.assertEqual(+ response.json(),+ {+ "logs_distinct_id_attribute_key": "user.id",+ "logs_session_id_attribute_keys": ["session.id"],+ },+ )++ def test_patch_rejects_invalid_session_id_keys(self):+ # Wiring guard: the endpoint must reject bodies the serializer marks invalid.+ # The full validation matrix lives in TestTeamLogsConfigSerializerValidation.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/logs_config/",+ {"logs_session_id_attribute_keys": []},+ format="json",+ )+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+++class TestTeamLogsConfigSerializerValidation(SimpleTestCase):+ @parameterized.expand(+ [+ ("empty_list", []),+ ("blank_entry", ["posthogSessionId", ""]),+ ("whitespace_entry", ["posthogSessionId", " "]),+ ("duplicate_keys", ["session.id", "session.id"]),+ ("duplicate_after_trim", ["session.id", " session.id "]),+ ("too_many_keys", [f"key{i}" for i in range(11)]),+ ("key_over_max_length", ["x" * 201]),+ ]+ )+ def test_rejects_invalid_session_id_keys(self, _name: str, keys):+ serializer = TeamLogsConfigSerializer(data={"logs_session_id_attribute_keys": keys}, partial=True)++ self.assertFalse(serializer.is_valid())+ self.assertIn("logs_session_id_attribute_keys", serializer.errors)++ def test_trims_whitespace_from_keys(self):+ serializer = TeamLogsConfigSerializer(+ data={"logs_session_id_attribute_keys": [" session.id ", "sessionId"]}, partial=True+ )++ self.assertTrue(serializer.is_valid())+ self.assertEqual(+ serializer.validated_data["logs_session_id_attribute_keys"],+ ["session.id", "sessionId"],+ )diff --git a/posthog/models/team/util.py b/posthog/models/team/util.pyindex 288ee03d541c..b9b4a1f7ea39 100644--- a/posthog/models/team/util.py+++ b/posthog/models/team/util.py@@ -31,6 +31,7 @@ actions_that_require_current_team = ["experiments_config","default_evaluation_contexts","evaluation_context_suggestions",+ "logs_config",]diff --git a/products/logs/backend/migrations/0015_teamlogsconfig_logs_session_id_attribute_keys.py b/products/logs/backend/migrations/0015_teamlogsconfig_logs_session_id_attribute_keys.pynew file mode 100644index 000000000000..585ebfc28800--- /dev/null+++ b/products/logs/backend/migrations/0015_teamlogsconfig_logs_session_id_attribute_keys.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.14 on 2026-07-13 11:26++import django.contrib.postgres.fields+from django.db import migrations, models++import products.logs.backend.models+++class Migration(migrations.Migration):+ dependencies = [+ ("logs", "0014_teamlogsconfig"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamlogsconfig",+ name="logs_session_id_attribute_keys",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ db_default=models.Value("{posthogSessionId}"),+ default=products.logs.backend.models.default_logs_session_id_attribute_keys,+ size=None,+ ),+ ),+ ]diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txtindex 4497cf36ad6f..4406e97a9d7b 100644--- a/products/logs/backend/migrations/max_migration.txt+++ b/products/logs/backend/migrations/max_migration.txt@@ -1 +1 @@-0014_teamlogsconfig+0015_teamlogsconfig_logs_session_id_attribute_keysdiff --git a/products/logs/backend/models.py b/products/logs/backend/models.pyindex 8b659bc7dcdc..b8d811d3f9e1 100644--- a/products/logs/backend/models.py+++ b/products/logs/backend/models.py@@ -4,8 +4,10 @@ import loggingfrom datetime import UTC, datetime, timedeltafrom typing import TYPE_CHECKING+from django.contrib.postgres.fields import ArrayFieldfrom django.core.exceptions import ValidationErrorfrom django.db import models+from django.db.models import Valuefrom posthog.models.activity_logging.model_activity import ModelActivityMixinfrom posthog.models.team.extensions import register_team_extension_signal@@ -24,6 +26,17 @@ logger = logging.getLogger(__name__)# whose pipeline uses a different key can override via the `logs_config` endpoint.DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY = "posthogDistinctId"+# Default log attribute keys whose values hold the PostHog session ID. `posthogSessionId`+# is the key the posthog-js / posthog-react-native SDKs auto-attach to every log they+# emit (see https://posthog.com/docs/logs/link-session-replay). Ordered: detection checks+# keys in list order and the first match wins. Customers whose pipeline emits the session+# ID under different keys can override via the `logs_config` endpoint.+DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ["posthogSessionId"]+++def default_logs_session_id_attribute_keys() -> list[str]:+ return list(DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS)+class TeamLogsConfig(models.Model):# Plain `models.Model` (not `TeamScopedRootMixin`) — log emission and ingestion@@ -42,6 +55,15 @@ class TeamLogsConfig(models.Model):db_default=DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,)+ # Ordered list of log attribute keys whose values hold the PostHog session ID.+ # Detection checks keys in order; the first key with a value wins. Used to link+ # logs to session replay and error tracking sessions.+ logs_session_id_attribute_keys = ArrayField(+ models.CharField(max_length=200),+ default=default_logs_session_id_attribute_keys,+ db_default=Value("{posthogSessionId}"),+ )+register_team_extension_signal(TeamLogsConfig, logger=logger)diff --git a/products/logs/frontend/logsConfigLogic.ts b/products/logs/frontend/logsConfigLogic.tsindex fa1a8f098a6e..88f3fd9c321f 100644--- a/products/logs/frontend/logsConfigLogic.ts+++ b/products/logs/frontend/logsConfigLogic.ts@@ -12,8 +12,13 @@ import type { logsConfigLogicType } from './logsConfigLogicType'// SDK convention before `logs_config` resolves.export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY = 'posthogDistinctId'+// Mirrors the backend default in products/logs/backend/models.py. Ordered: session ID+// detection checks keys in list order and the first match wins.+export const DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS = ['posthogSessionId']+export interface LogsConfig {logs_distinct_id_attribute_key: string+ logs_session_id_attribute_keys: string[]}export const logsConfigLogic = kea<logsConfigLogicType>([