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 team-configurable logs distinct_id attribute key (#60536)

Daniel Viscadd1e80965735
diff --git a/.github/scripts/check-idor-model-coverage.py b/.github/scripts/check-idor-model-coverage.py
index 0c54824aa880..b7306cf07e7e 100644
--- a/.github/scripts/check-idor-model-coverage.py
+++ b/.github/scripts/check-idor-model-coverage.py
@@ -166,6 +166,7 @@ def get_scoped_models() -> tuple[dict[str, set[str]], set[str], set[str], set[st
"TeamDefaultEvaluationContext",
"TeamDataWarehouseConfig",
"TeamExperimentsConfig",
+ "TeamLogsConfig",
"TeamMarketingAnalyticsConfig",
"TeamRevenueAnalyticsConfig",
"TeamJsSnippetConfig",
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 721c93c03398..1eaa17cacee4 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -93,6 +93,7 @@ from products.feature_flags.backend.models.evaluation_context import (
TeamDefaultEvaluationContext,
normalize_context_name,
)
+from products.logs.backend.models import TeamLogsConfig
from products.signals.backend.models import SignalSourceConfig
tracer = trace.get_tracer(__name__)
@@ -1703,6 +1704,44 @@ class TeamViewSet(TeamAndOrgViewSetMixin, AccessControlViewSetMixin, viewsets.Mo
return response.Response({"enabled": config.enabled, "default_groups": config.default_groups})
+ @action(
+ methods=["GET", "PATCH"],
+ detail=True,
+ permission_classes=[TeamMemberLightManagementPermission],
+ url_path="logs_config",
+ )
+ def logs_config(self, request: request.Request, id: str, **kwargs) -> response.Response:
+ """Manage logs product configuration for this environment."""
+ from rest_framework import serializers
+
+ class TeamLogsConfigSerializer(serializers.ModelSerializer):
+ logs_distinct_id_attribute_key = serializers.CharField(
+ max_length=200,
+ help_text=(
+ "Log attribute key whose value should match a person's distinct_id. "
+ "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. Override only if "
+ "your pipeline emits a different attribute."
+ ),
+ )
+
+ class Meta:
+ model = TeamLogsConfig
+ fields = ["logs_distinct_id_attribute_key"]
+
+ team = self.get_object()
+ config = get_or_create_team_extension(team, TeamLogsConfig)
+
+ if request.method == "PATCH":
+ serializer = TeamLogsConfigSerializer(config, data=request.data, partial=True)
+ serializer.is_valid(raise_exception=True)
+ serializer.save()
+ return response.Response(serializer.data)
+
+ return response.Response(TeamLogsConfigSerializer(config).data)
+
@action(
methods=["GET", "PATCH"],
detail=True,
diff --git a/posthog/api/test/test_team_logs_config.py b/posthog/api/test/test_team_logs_config.py
new file mode 100644
index 000000000000..1ab4ee214848
--- /dev/null
+++ b/posthog/api/test/test_team_logs_config.py
@@ -0,0 +1,86 @@
+from posthog.test.base import APIBaseTest
+
+from rest_framework import status
+
+from posthog.models import OrganizationMembership, Team
+from posthog.models.team.extensions import get_or_create_team_extension
+
+from products.logs.backend.models import TeamLogsConfig
+
+
+class TestTeamLogsConfig(APIBaseTest):
+ def setUp(self):
+ super().setUp()
+ self.organization_membership.level = OrganizationMembership.Level.ADMIN
+ self.organization_membership.save()
+ self.url = f"/api/environments/{self.team.id}/logs_config/"
+
+ def test_get_returns_default_attribute_key(self):
+ response = self.client.get(self.url)
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), {"logs_distinct_id_attribute_key": "posthogDistinctId"})
+
+ def test_patch_updates_attribute_key(self):
+ response = self.client.patch(
+ self.url,
+ {"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"})
+
+ config = get_or_create_team_extension(self.team, TeamLogsConfig)
+ self.assertEqual(config.logs_distinct_id_attribute_key, "user.id")
+
+ def test_patch_persists_across_requests(self):
+ self.client.patch(
+ self.url,
+ {"logs_distinct_id_attribute_key": "posthog.distinct_id"},
+ format="json",
+ )
+
+ response = self.client.get(self.url)
+ self.assertEqual(response.json(), {"logs_distinct_id_attribute_key": "posthog.distinct_id"})
+
+ def test_patch_rejects_key_over_max_length(self):
+ response = self.client.patch(
+ self.url,
+ {"logs_distinct_id_attribute_key": "x" * 201},
+ format="json",
+ )
+ self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ def test_regular_member_can_patch(self):
+ self.organization_membership.level = OrganizationMembership.Level.MEMBER
+ self.organization_membership.save()
+
+ response = self.client.patch(
+ self.url,
+ {"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"})
+
+ def test_config_is_scoped_per_environment(self):
+ # Each environment under a project must keep its own config. A write on this
+ # environment must not leak to a sibling environment that shares its project.
+ sibling = Team.objects.create(
+ organization=self.organization,
+ parent_team=self.team,
+ name="sibling-env",
+ )
+
+ self.client.patch(
+ self.url,
+ {"logs_distinct_id_attribute_key": "user.id"},
+ format="json",
+ )
+
+ sibling_response = self.client.get(f"/api/environments/{sibling.id}/logs_config/")
+ self.assertEqual(
+ sibling_response.json(),
+ {"logs_distinct_id_attribute_key": "posthogDistinctId"},
+ )
diff --git a/products/logs/backend/migrations/0014_teamlogsconfig.py b/products/logs/backend/migrations/0014_teamlogsconfig.py
new file mode 100644
index 000000000000..39824cf4773e
--- /dev/null
+++ b/products/logs/backend/migrations/0014_teamlogsconfig.py
@@ -0,0 +1,35 @@
+# Generated by Django 5.2.14 on 2026-05-29 16:01
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0013_alter_logsalertconfiguration_threshold_count"),
+ ("posthog", "1186_activitylog_ip_address"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="TeamLogsConfig",
+ fields=[
+ (
+ "team",
+ models.OneToOneField(
+ on_delete=django.db.models.deletion.CASCADE,
+ primary_key=True,
+ serialize=False,
+ to="posthog.team",
+ ),
+ ),
+ (
+ "logs_distinct_id_attribute_key",
+ models.CharField(db_default="posthogDistinctId", default="posthogDistinctId", max_length=200),
+ ),
+ ],
+ options={
+ "abstract": False,
+ },
+ ),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index bbb022ee1172..4497cf36ad6f 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0013_alter_logsalertconfiguration_threshold_count
+0014_teamlogsconfig
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index cb606d9ac346..8b659bc7dcdc 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import logging
from datetime import UTC, datetime, timedelta
from typing import TYPE_CHECKING
@@ -7,12 +8,43 @@ from django.core.exceptions import ValidationError
from django.db import models
from posthog.models.activity_logging.model_activity import ModelActivityMixin
+from posthog.models.team.extensions import register_team_extension_signal
from posthog.models.utils import CreatedMetaFields, UpdatedMetaFields, UUIDModel
from posthog.utils import generate_short_id
if TYPE_CHECKING:
from products.logs.backend.alert_state_machine import AlertSnapshot
+logger = logging.getLogger(__name__)
+
+# Default log attribute key whose value matches a PostHog person's distinct_id. Mirrors
+# the convention documented at https://posthog.com/docs/logs/link-session-replay: the
+# posthog-js / posthog-react-native SDKs auto-attach `posthogDistinctId` to every log
+# they emit, and the docs instruct OTel-emitting backends to set the same key. Customers
+# whose pipeline uses a different key can override via the `logs_config` endpoint.
+DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY = "posthogDistinctId"
+
+
+class TeamLogsConfig(models.Model):
+ # Plain `models.Model` (not `TeamScopedRootMixin`) — log emission and ingestion
+ # are per-environment, and so is this config. Inheriting the root-mixin would
+ # rewrite writes to the parent project on save, letting a member of one child
+ # environment mutate config that affects sibling environments they may not have
+ # access to. Mirrors the `TeamExperimentsConfig` precedent.
+ team = models.OneToOneField("posthog.Team", on_delete=models.CASCADE, primary_key=True)
+
+ # Log attribute key whose value matches a PostHog person's distinct_id. Used by the
+ # person profile Logs tab and the `query-logs` MCP tool to filter logs to a single
+ # user without needing per-team prompt engineering.
+ logs_distinct_id_attribute_key = models.CharField(
+ max_length=200,
+ default=DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,
+ db_default=DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,
+ )
+
+
+register_team_extension_signal(TeamLogsConfig, logger=logger)
+
# Upper bound on LogsAlertConfiguration.evaluation_periods. Doubles as the per-alert
# cap on retained OK event rows — the N-of-M evaluator never reads more than this many
# non-errored rows per alert, so older OK rows are pruned. Mirrored in the serializer's
diff --git a/products/logs/backend/test/test_models.py b/products/logs/backend/test/test_models.py
index 9f3970c6ad7f..b5ef2a77a325 100644
--- a/products/logs/backend/test/test_models.py
+++ b/products/logs/backend/test/test_models.py
@@ -7,7 +7,15 @@ from django.core.exceptions import ValidationError
from parameterized import parameterized
-from products.logs.backend.models import MAX_EVALUATION_PERIODS, LogsAlertConfiguration, LogsAlertEvent
+from posthog.models.team.extensions import get_or_create_team_extension
+
+from products.logs.backend.models import (
+ DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,
+ MAX_EVALUATION_PERIODS,
+ LogsAlertConfiguration,
+ LogsAlertEvent,
+ TeamLogsConfig,
+)
class TestLogsAlertConfiguration(BaseTest):
@@ -216,3 +224,29 @@ class TestLogsAlertEvent(BaseTest):
alert.delete()
assert LogsAlertEvent.objects.count() == 0
+
+
+class TestTeamLogsConfig(BaseTest):
+ def test_default_attribute_key(self):
+ config = get_or_create_team_extension(self.team, TeamLogsConfig)
+ assert config.logs_distinct_id_attribute_key == DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY
+ # Matches the JS SDK / docs convention so logs from posthog-js are linked to
+ # their person without any team configuration.
+ assert config.logs_distinct_id_attribute_key == "posthogDistinctId"
+
+ def test_custom_attribute_key_persists(self):
+ config = get_or_create_team_extension(self.team, TeamLogsConfig)
+ config.logs_distinct_id_attribute_key = "user.id"
+ config.save()
+
+ refetched = get_or_create_team_extension(self.team, TeamLogsConfig)
+ assert refetched.logs_distinct_id_attribute_key == "user.id"
+
+ def test_cascade_delete_with_team(self):
+ get_or_create_team_extension(self.team, TeamLogsConfig)
+ team_id = self.team.pk
+ assert TeamLogsConfig.objects.filter(team_id=team_id).exists()
+
+ self.team.delete()
+
+ assert not TeamLogsConfig.objects.filter(team_id=team_id).exists()