: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 logs_pattern_message_keys to team logs config (#93585)
Jon McCallumfbe52ee0b8d8
diff --git a/docs/published/docs/logs/logs-config.mdx b/docs/published/docs/logs/logs-config.mdxnew file mode 100644index 000000000000..b0f6a7be90e4--- /dev/null+++ b/docs/published/docs/logs/logs-config.mdx@@ -0,0 +1,57 @@+---+title: Logs configuration+sidebar: Docs+showTitle: true+---++Each project has a logs configuration that tells PostHog how to read your log records. It holds the attribute keys that link logs to people and sessions, and the JSON keys that log patterns are derived from.++Read or change it through the `logs_config` endpoint. You need to be a project admin to change it.++```text+GET /api/projects/:project_id/logs_config/+PATCH /api/projects/:project_id/logs_config/+```++A `PATCH` is partial. Send only the fields you want to change and the rest keep their values.++## Fields++All three list fields share the same rules:++- Keys are matched literally at the top level. A dot is part of the key name, not a path into nested objects. `log.message` names one key called `log.message`.+- Order matters. PostHog checks keys in list order, and the first key that holds a value wins.+- Whitespace around a key is trimmed. Blank keys and duplicate keys are rejected.+- A list holds at most 10 keys, each up to 200 characters.++### `logs_distinct_id_attribute_keys`++Log attribute keys whose values hold a PostHog distinct ID. Default: `["posthogDistinctId"]`.++Used to link a log to a person, so the log appears on that person's Logs tab and the `query-logs` MCP tool can filter logs to one user. Add keys only if your pipeline emits the person identifier under a different attribute. See [linking logs to session replay](/docs/logs/link-session-replay).++The list can't be empty.++### `logs_session_id_attribute_keys`++Log attribute keys whose values hold a PostHog session ID. Default: `["sessionId"]`.++Used to link a log to a session replay or an error tracking session. Add keys only if your pipeline emits the session ID under a different attribute.++The list can't be empty.++### `logs_pattern_message_keys`++JSON keys whose value is the message text that log patterns are derived from. Default: `["message", "msg", "event"]`.++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.++An empty list turns message extraction off. Every JSON body then groups by its key set.++This setting changes only how patterns are derived. The stored log body is never changed.++## Propagation++A change reaches log ingestion within a few minutes. Records ingested in that window keep the patterns derived from the previous configuration.diff --git a/docs/published/docs/logs/owners.yaml b/docs/published/docs/logs/owners.yamlnew file mode 100644index 000000000000..ebe908e1acac--- /dev/null+++ b/docs/published/docs/logs/owners.yaml@@ -0,0 +1,3 @@+version: 1+owners:+ - team-apmdiff --git a/posthog/api/team.py b/posthog/api/team.pyindex 183f97264c01..2b7ab2d62750 100644--- a/posthog/api/team.py+++ b/posthog/api/team.py@@ -163,6 +163,20 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):"if your pipeline emits the session ID under different attributes."),)+ logs_pattern_message_keys = serializers.ListField(+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),+ allow_empty=True,+ max_length=10,+ help_text=(+ "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."+ ),+ )class Meta:model = TeamLogsConfig@@ -170,6 +184,7 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):"logs_distinct_id_attribute_key","logs_distinct_id_attribute_keys","logs_session_id_attribute_keys",+ "logs_pattern_message_keys",]def _validate_unique_keys(self, value: list[str]) -> list[str]:@@ -185,6 +200,9 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):def validate_logs_session_id_attribute_keys(self, value: list[str]) -> list[str]:return self._validate_unique_keys(value)+ def validate_logs_pattern_message_keys(self, value: list[str]) -> list[str]:+ return self._validate_unique_keys(value)+def update(self, instance: TeamLogsConfig, validated_data: dict) -> TeamLogsConfig:# Keep the legacy single-key column in sync so pre-plural readers stay coherent.keys = validated_data.get("logs_distinct_id_attribute_keys")diff --git a/posthog/api/test/test_team_logs_config.py b/posthog/api/test/test_team_logs_config.pyindex 939c80265425..261c3570d55d 100644--- a/posthog/api/test/test_team_logs_config.py+++ b/posthog/api/test/test_team_logs_config.py@@ -12,6 +12,7 @@ from posthog.models.team.extensions import get_or_create_team_extensionfrom products.logs.backend.models import (DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS,+ DEFAULT_LOGS_PATTERN_MESSAGE_KEYS,DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS,TeamLogsConfig,)@@ -24,6 +25,7 @@ DEFAULT_CONFIG = {"logs_distinct_id_attribute_key": DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,"logs_distinct_id_attribute_keys": DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS,"logs_session_id_attribute_keys": DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS,+ "logs_pattern_message_keys": DEFAULT_LOGS_PATTERN_MESSAGE_KEYS,}@@ -156,7 +158,7 @@ class TestTeamLogsConfig(APIBaseTest):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.+ # to its default — the settings must update independently.self.client.patch(f"/api/projects/{self.team.id}/logs_config/",{"logs_session_id_attribute_keys": ["session.id"]},@@ -167,6 +169,11 @@ class TestTeamLogsConfig(APIBaseTest):{"logs_distinct_id_attribute_keys": ["user.id"]},format="json",)+ self.client.patch(+ f"/api/projects/{self.team.id}/logs_config/",+ {"logs_pattern_message_keys": ["text"]},+ format="json",+ )response = self.client.get(f"/api/projects/{self.team.id}/logs_config/")self.assertEqual(@@ -175,6 +182,7 @@ class TestTeamLogsConfig(APIBaseTest):"logs_distinct_id_attribute_key": "user.id","logs_distinct_id_attribute_keys": ["user.id"],"logs_session_id_attribute_keys": ["session.id"],+ "logs_pattern_message_keys": ["text"],},)@@ -182,6 +190,7 @@ class TestTeamLogsConfig(APIBaseTest):[("distinct_id", "logs_distinct_id_attribute_keys"),("session_id", "logs_session_id_attribute_keys"),+ ("pattern_message", "logs_pattern_message_keys"),])def test_patch_rejects_invalid_keys(self, _name: str, field: str):@@ -189,16 +198,36 @@ class TestTeamLogsConfig(APIBaseTest):# The full validation matrix lives in TestTeamLogsConfigSerializerValidation.response = self.client.patch(f"/api/projects/{self.team.id}/logs_config/",- {field: []},+ {field: ["dup", "dup"]},format="json",)self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)+ def test_patch_empty_pattern_message_keys_turns_extraction_off(self):+ # Empty is the off switch for this field, unlike the two attribute-key lists, so a+ # copied `allow_empty=False` would silently remove the only way to disable extraction.+ response = self.client.patch(+ f"/api/projects/{self.team.id}/logs_config/",+ {"logs_pattern_message_keys": []},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ self.assertEqual(response.json()["logs_pattern_message_keys"], [])++ config = get_or_create_team_extension(self.team, TeamLogsConfig)+ self.assertEqual(config.logs_pattern_message_keys, [])+++KEY_LIST_FIELDS = [+ "logs_distinct_id_attribute_keys",+ "logs_session_id_attribute_keys",+ "logs_pattern_message_keys",+]-KEY_LIST_FIELDS = ["logs_distinct_id_attribute_keys", "logs_session_id_attribute_keys"]+NON_EMPTY_KEY_LIST_FIELDS = ["logs_distinct_id_attribute_keys", "logs_session_id_attribute_keys"]INVALID_KEY_LISTS = [- ("empty_list", []),("blank_entry", ["posthogSessionId", ""]),("whitespace_entry", ["posthogSessionId", " "]),("duplicate_keys", ["session.id", "session.id"]),@@ -218,6 +247,19 @@ class TestTeamLogsConfigSerializerValidation(SimpleTestCase):self.assertFalse(serializer.is_valid())self.assertIn(field, serializer.errors)+ @parameterized.expand([(field,) for field in NON_EMPTY_KEY_LIST_FIELDS])+ def test_rejects_empty_list(self, field: str):+ serializer = TeamLogsConfigSerializer(data={field: []}, partial=True)++ self.assertFalse(serializer.is_valid())+ self.assertIn(field, serializer.errors)++ def test_accepts_empty_pattern_message_keys(self):+ serializer = TeamLogsConfigSerializer(data={"logs_pattern_message_keys": []}, partial=True)++ self.assertTrue(serializer.is_valid())+ self.assertEqual(serializer.validated_data["logs_pattern_message_keys"], [])+@parameterized.expand([(field,) for field in KEY_LIST_FIELDS])def test_trims_whitespace_from_keys(self, field: str):serializer = TeamLogsConfigSerializer(data={field: [" first.key ", "second.key"]}, partial=True)diff --git a/products/logs/backend/migrations/0023_teamlogsconfig_logs_pattern_message_keys.py b/products/logs/backend/migrations/0023_teamlogsconfig_logs_pattern_message_keys.pynew file mode 100644index 000000000000..494b2826fd00--- /dev/null+++ b/products/logs/backend/migrations/0023_teamlogsconfig_logs_pattern_message_keys.py@@ -0,0 +1,25 @@+# Generated by Django 5.2.17 on 2026-09-02 15:50++import django.contrib.postgres.fields+from django.db import migrations, models++import products.logs.backend.models+++class Migration(migrations.Migration):+ dependencies = [+ ("logs", "0022_backfill_logs_session_id_attribute_keys"),+ ]++ operations = [+ migrations.AddField(+ model_name="teamlogsconfig",+ name="logs_pattern_message_keys",+ field=django.contrib.postgres.fields.ArrayField(+ base_field=models.CharField(max_length=200),+ db_default=models.Value("{message,msg,event}"),+ default=products.logs.backend.models.default_logs_pattern_message_keys,+ size=None,+ ),+ ),+ ]diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txtindex 1a387b05ab1b..c869227648e7 100644--- a/products/logs/backend/migrations/max_migration.txt+++ b/products/logs/backend/migrations/max_migration.txt@@ -1 +1 @@-0022_backfill_logs_session_id_attribute_keys+0023_teamlogsconfig_logs_pattern_message_keysdiff --git a/products/logs/backend/models.py b/products/logs/backend/models.pyindex f59666b80890..b893b2f62fb7 100644--- a/products/logs/backend/models.py+++ b/products/logs/backend/models.py@@ -66,6 +66,17 @@ def default_logs_session_id_attribute_keys() -> list[str]:return list(DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS)+# Default top-level JSON keys that hold the message text a log pattern is derived from.+# Keys match literally, so a dot is part of the name and never a path. Ordered: selection+# checks keys in list order and the first key whose value is a non-empty string wins. An+# empty list turns extraction off, so JSON bodies group by their key set instead.+DEFAULT_LOGS_PATTERN_MESSAGE_KEYS = ["message", "msg", "event"]+++def default_logs_pattern_message_keys() -> list[str]:+ return list(DEFAULT_LOGS_PATTERN_MESSAGE_KEYS)++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@@ -103,6 +114,17 @@ class TeamLogsConfig(models.Model):db_default=Value("{posthogSessionId}"),)+ # Ordered list of top-level JSON keys whose value is the message text that log patterns are+ # derived from. Matched literally, so `log.message` names one key and never descends. The+ # first key in order whose value is a non-empty string wins. An empty list+ # turns extraction off. Read by the logs ingestion consumer, so this only shapes the+ # stored `pattern` column and never rewrites the log body.+ logs_pattern_message_keys = ArrayField(+ models.CharField(max_length=200),+ default=default_logs_pattern_message_keys,+ db_default=Value("{message,msg,event}"),+ )+register_team_extension_signal(TeamLogsConfig, logger=logger)