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): support multiple distinct ID attribute keys for linking logs to persons (#73053)

Daniel Visca8fa03f8bb0e4
diff --git a/frontend/src/scenes/persons/PersonLogsTab.tsx b/frontend/src/scenes/persons/PersonLogsTab.tsx
index a75aeb6a844e..ff4fc8132b31 100644
--- a/frontend/src/scenes/persons/PersonLogsTab.tsx
+++ b/frontend/src/scenes/persons/PersonLogsTab.tsx
@@ -6,52 +6,62 @@ import { LemonButton } from '@posthog/lemon-ui'
import { urls } from 'scenes/urls'
-import { FilterLogicalOperator, LogPropertyFilter, PersonType, PropertyFilterType, PropertyOperator } from '~/types'
+import {
+ FilterLogicalOperator,
+ LogPropertyFilter,
+ PersonType,
+ PropertyFilterType,
+ PropertyOperator,
+ UniversalFiltersGroup,
+} from '~/types'
import { LogsViewer } from 'products/logs/frontend/components/LogsViewer/LogsViewer'
-import { DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY, logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
+import { DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
// Renders the Logs tab on the person profile. Mounted only when the tab is active
// (LemonTabs renders just the active tab's content), so `logsConfigLogic` only fetches
-// the team's `logs_distinct_id_attribute_key` on demand rather than on every team load.
-// While the config loads, falls back to the default key — accurate for the vast majority
+// the team's `logs_distinct_id_attribute_keys` on demand rather than on every team load.
+// While the config loads, falls back to the default keys — accurate for the vast majority
// of teams; non-default teams briefly see the wrong filter then resolve to the override.
export function PersonLogsTab({ person }: { person: PersonType }): JSX.Element {
const { logsConfig } = useValues(logsConfigLogic)
- const distinctIdAttributeKey = logsConfig?.logs_distinct_id_attribute_key ?? DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY
- const isCustomizedKey = distinctIdAttributeKey !== DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY
+ const distinctIdAttributeKeys =
+ logsConfig?.logs_distinct_id_attribute_keys ?? DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS
- const pinnedFilters = useMemo(
- () => ({
+ const pinnedFilters = useMemo((): UniversalFiltersGroup => {
+ const keyFilters = distinctIdAttributeKeys.map(
+ (key): LogPropertyFilter => ({
+ key,
+ type: PropertyFilterType.LogAttribute,
+ operator: PropertyOperator.Exact,
+ value: person.distinct_ids,
+ })
+ )
+ return {
type: FilterLogicalOperator.And,
- values: [
- {
- key: distinctIdAttributeKey,
- type: PropertyFilterType.LogAttribute,
- operator: PropertyOperator.Exact,
- value: person.distinct_ids,
- } as LogPropertyFilter,
- ],
- }),
- [distinctIdAttributeKey, person.distinct_ids]
- )
+ // A single key pins a plain filter; multiple keys pin a nested OR group so a
+ // log matches when any configured attribute holds one of the distinct IDs.
+ values: keyFilters.length === 1 ? keyFilters : [{ type: FilterLogicalOperator.Or, values: keyFilters }],
+ }
+ }, [distinctIdAttributeKeys, person.distinct_ids])
return (
<div className="flex flex-col h-[calc(100vh-16rem)] min-h-[25rem]">
<p className="text-muted text-xs mb-2 flex items-center gap-1 flex-wrap">
<span>
- Scoped to this person via the <code>{distinctIdAttributeKey}</code> log attribute.
- {isCustomizedKey && (
- <>
- {' '}
- Customised from default <code>{DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY}</code>.
- </>
- )}
+ Scoped to this person via{' '}
+ {distinctIdAttributeKeys.map((key, index) => (
+ <span key={key}>
+ {index > 0 && ' or '}
+ <code>{key}</code>
+ </span>
+ ))}{' '}
+ log {distinctIdAttributeKeys.length === 1 ? 'attribute' : 'attributes'}.
</span>
<LemonButton
size="xsmall"
icon={<IconGear />}
- tooltip="Change the log attribute used to link logs to a person"
+ tooltip="Change the log attributes used to link logs to a person"
to={urls.settings('environment-logs', 'logs-distinct-id-attribute-key')}
/>
</p>
diff --git a/frontend/src/scenes/settings/SettingsMap.tsx b/frontend/src/scenes/settings/SettingsMap.tsx
index 1407b7988563..78168d0d2529 100644
--- a/frontend/src/scenes/settings/SettingsMap.tsx
+++ b/frontend/src/scenes/settings/SettingsMap.tsx
@@ -101,7 +101,7 @@ import {
LogsPiiScrubSettings,
LogsRetentionSettings,
} from './environment/LogsCaptureSettings'
-import { LogsDistinctIdAttributeKey } from './environment/LogsDistinctIdAttributeKey'
+import { LogsDistinctIdAttributeKeys } from './environment/LogsDistinctIdAttributeKeys'
import { LogsSessionIdAttributeKeys } from './environment/LogsSessionIdAttributeKeys'
import { ManagedReverseProxy } from './environment/ManagedReverseProxy'
import { MarketingAnalyticsSettingsWrapper } from './environment/MarketingAnalyticsSettingsWrapper'
@@ -786,15 +786,15 @@ export const SETTINGS_MAP: SettingSection[] = [
title: 'Link to person',
description: (
<>
- The log attribute PostHog reads to identify which person a log belongs to. Matched against the
- person&apos;s distinct IDs to surface logs on their profile. Defaults to{' '}
- <code>posthogDistinctId</code> — the key the JavaScript and React Native SDKs auto-attach.
- Override only if your backend pipeline emits the person identifier under a different key.
+ The log attributes PostHog reads to identify which person a log belongs to. A log is linked when
+ any of these attributes matches one of the person&apos;s distinct IDs. Defaults to{' '}
+ <code>posthogDistinctId</code>, the key the JavaScript and React Native SDKs auto-attach. Add
+ keys only if your backend pipeline emits the person identifier under different attributes.
</>
),
searchDescription:
- "The log attribute PostHog reads to identify which person a log belongs to. Matched against the person's distinct IDs to surface logs on their profile. Defaults to posthogDistinctId — the key the JavaScript and React Native SDKs auto-attach. Override only if your backend pipeline emits the person identifier under a different key.",
- component: <LogsDistinctIdAttributeKey />,
+ "The log attributes PostHog reads to identify which person a log belongs to. A log is linked when any of these attributes matches one of the person's distinct IDs. Defaults to posthogDistinctId, the key the JavaScript and React Native SDKs auto-attach. Add keys only if your backend pipeline emits the person identifier under different attributes.",
+ component: <LogsDistinctIdAttributeKeys />,
flag: 'LOGS_SETTINGS',
keywords: ['log', 'person', 'distinct', 'attribute', 'pivot', 'profile', 'link'],
},
diff --git a/frontend/src/scenes/settings/environment/LogsDistinctIdAttributeKey.tsx b/frontend/src/scenes/settings/environment/LogsDistinctIdAttributeKeys.tsx
similarity index 53%
rename from frontend/src/scenes/settings/environment/LogsDistinctIdAttributeKey.tsx
rename to frontend/src/scenes/settings/environment/LogsDistinctIdAttributeKeys.tsx
index cd716d365921..f1268cd37b72 100644
--- a/frontend/src/scenes/settings/environment/LogsDistinctIdAttributeKey.tsx
+++ b/frontend/src/scenes/settings/environment/LogsDistinctIdAttributeKeys.tsx
@@ -1,15 +1,17 @@
import { useActions, useValues } from 'kea'
import { useEffect, useState } from 'react'
-import { LemonButton, LemonInput } from '@posthog/lemon-ui'
+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_DISTINCT_ID_ATTRIBUTE_KEY, logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
+import { DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS, logsConfigLogic } from 'products/logs/frontend/logsConfigLogic'
-export function LogsDistinctIdAttributeKey(): JSX.Element {
+export function LogsDistinctIdAttributeKeys(): JSX.Element {
const { logsConfig, logsConfigLoading } = useValues(logsConfigLogic)
const { updateLogsConfig } = useActions(logsConfigLogic)
const restrictedReason = useRestrictedArea({
@@ -17,11 +19,11 @@ export function LogsDistinctIdAttributeKey(): JSX.Element {
minimumAccessLevel: TeamMembershipLevel.Admin,
})
- const [value, setValue] = useState<string>('')
+ const [value, setValue] = useState<string[]>([])
useEffect(() => {
if (logsConfig) {
- setValue(logsConfig.logs_distinct_id_attribute_key)
+ setValue(logsConfig.logs_distinct_id_attribute_keys ?? DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS)
}
}, [logsConfig])
@@ -29,26 +31,29 @@ export function LogsDistinctIdAttributeKey(): JSX.Element {
return <LemonSkeleton className="w-1/2 h-4" />
}
- const trimmed = value.trim()
- const isDirty = trimmed !== (logsConfig?.logs_distinct_id_attribute_key ?? '')
- const isEmpty = trimmed.length === 0
+ const cleaned = value.map((key) => key.trim()).filter(Boolean)
+ const isDirty = !objectsEqual(cleaned, logsConfig?.logs_distinct_id_attribute_keys ?? [])
+ const isEmpty = cleaned.length === 0
return (
<div className="deprecated-space-y-4">
- <LemonInput
+ <LemonInputSelect
+ mode="multiple"
+ allowCustomValues
value={value}
onChange={setValue}
- placeholder={DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY}
- maxLength={200}
- disabledReason={restrictedReason}
+ placeholder={DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS.join(', ')}
+ loading={logsConfigLoading}
+ disabled={logsConfigLoading || !!restrictedReason}
+ data-attr="logs-distinct-id-attribute-keys-select"
className="max-w-md"
/>
<LemonButton
type="primary"
- onClick={() => updateLogsConfig({ logs_distinct_id_attribute_key: trimmed })}
+ onClick={() => updateLogsConfig({ logs_distinct_id_attribute_keys: cleaned })}
disabledReason={
restrictedReason ||
- (isEmpty ? 'Attribute key is required' : !isDirty ? 'No changes to save' : undefined)
+ (isEmpty ? 'At least one attribute key is required' : !isDirty ? 'No changes to save' : undefined)
}
loading={logsConfigLoading}
>
diff --git a/posthog/api/team.py b/posthog/api/team.py
index 8590e27fe9c5..39949b2d674e 100644
--- a/posthog/api/team.py
+++ b/posthog/api/team.py
@@ -105,14 +105,26 @@ tracer = trace.get_tracer(__name__)
class TeamLogsConfigSerializer(serializers.ModelSerializer):
logs_distinct_id_attribute_key = serializers.CharField(
- max_length=200,
+ read_only=True,
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 "
+ "Legacy single-key alias — always the first entry of "
+ "`logs_distinct_id_attribute_keys`. Read-only; write the plural field instead."
+ ),
+ )
+ logs_distinct_id_attribute_keys = serializers.ListField(
+ # trim_whitespace is the DRF default, but the uniqueness validator below
+ # depends on it — spell it out so it can't drift silently.
+ child=serializers.CharField(max_length=200, allow_blank=False, trim_whitespace=True),
+ allow_empty=False,
+ max_length=10,
+ help_text=(
+ "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. Override only if "
- "your pipeline emits a different attribute."
+ "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 = serializers.ListField(
@@ -132,15 +144,32 @@ class TeamLogsConfigSerializer(serializers.ModelSerializer):
class Meta:
model = TeamLogsConfig
- fields = ["logs_distinct_id_attribute_key", "logs_session_id_attribute_keys"]
+ fields = [
+ "logs_distinct_id_attribute_key",
+ "logs_distinct_id_attribute_keys",
+ "logs_session_id_attribute_keys",
+ ]
- def validate_logs_session_id_attribute_keys(self, value: list[str]) -> list[str]:
+ def _validate_unique_keys(self, value: list[str]) -> list[str]:
# The child CharField already trims whitespace and rejects blanks; only
# cross-item uniqueness needs checking here.
if len(set(value)) != len(value):
raise serializers.ValidationError("Attribute keys must be unique.")
return value
+ def validate_logs_distinct_id_attribute_keys(self, value: list[str]) -> list[str]:
+ return self._validate_unique_keys(value)
+
+ def validate_logs_session_id_attribute_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")
+ if keys:
+ validated_data["logs_distinct_id_attribute_key"] = keys[0]
+ return super().update(instance, validated_data)
+
def handle_logs_config(request: request.Request, team: Team) -> response.Response:
"""Shared handler for the logs_config action — exposed under both the team/environment
diff --git a/posthog/api/test/test_team_logs_config.py b/posthog/api/test/test_team_logs_config.py
index 317bab633163..939c80265425 100644
--- a/posthog/api/test/test_team_logs_config.py
+++ b/posthog/api/test/test_team_logs_config.py
@@ -11,6 +11,7 @@ from posthog.models.team.extensions import get_or_create_team_extension
from products.logs.backend.models import (
DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY,
+ DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS,
DEFAULT_LOGS_SESSION_ID_ATTRIBUTE_KEYS,
TeamLogsConfig,
)
@@ -21,6 +22,7 @@ URL_PREFIXES = [("projects", "api/projects"), ("environments", "api/environments
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,
}
@@ -42,38 +44,54 @@ class TestTeamLogsConfig(APIBaseTest):
self.assertEqual(response.json(), DEFAULT_CONFIG)
@parameterized.expand(URL_PREFIXES)
- def test_patch_updates_attribute_key(self, _name: str, prefix: str):
+ def test_patch_updates_distinct_id_keys(self, _name: str, prefix: str):
response = self.client.patch(
self._url(prefix),
- {"logs_distinct_id_attribute_key": "user.id"},
+ {"logs_distinct_id_attribute_keys": ["user.id", "posthogDistinctId"]},
format="json",
)
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_keys"], ["user.id", "posthogDistinctId"])
config = get_or_create_team_extension(self.team, TeamLogsConfig)
- self.assertEqual(config.logs_distinct_id_attribute_key, "user.id")
+ self.assertEqual(config.logs_distinct_id_attribute_keys, ["user.id", "posthogDistinctId"])
@parameterized.expand(URL_PREFIXES)
def test_patch_persists_across_requests(self, _name: str, prefix: str):
self.client.patch(
self._url(prefix),
- {"logs_distinct_id_attribute_key": "posthog.distinct_id"},
+ {"logs_distinct_id_attribute_keys": ["posthog.distinct_id"]},
format="json",
)
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_keys"], ["posthog.distinct_id"])
- @parameterized.expand(URL_PREFIXES)
- def test_patch_rejects_key_over_max_length(self, _name: str, prefix: str):
+ def test_patch_keeps_legacy_single_key_in_sync(self):
+ # Pre-plural readers (older MCP prompts, cached frontends) still read the
+ # singular field — it must track the first entry of the plural list.
response = self.client.patch(
- self._url(prefix),
- {"logs_distinct_id_attribute_key": "x" * 201},
+ f"/api/projects/{self.team.id}/logs_config/",
+ {"logs_distinct_id_attribute_keys": ["user.id", "backup.id"]},
format="json",
)
- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+
+ 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_of_legacy_single_key_is_ignored(self):
+ # The singular field is a read-only alias now — a write to it must not 400
+ # (old clients keep working) but must not change anything either.
+ response = self.client.patch(
+ f"/api/projects/{self.team.id}/logs_config/",
+ {"logs_distinct_id_attribute_key": "user.id"},
+ format="json",
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.json(), DEFAULT_CONFIG)
@parameterized.expand(URL_PREFIXES)
def test_regular_member_can_read_but_not_patch(self, _name: str, prefix: str):
@@ -87,7 +105,7 @@ class TestTeamLogsConfig(APIBaseTest):
patch_response = self.client.patch(
self._url(prefix),
- {"logs_distinct_id_attribute_key": "user.id"},
+ {"logs_distinct_id_attribute_keys": ["user.id"]},
format="json",
)
self.assertEqual(patch_response.status_code, status.HTTP_403_FORBIDDEN)
@@ -104,7 +122,7 @@ class TestTeamLogsConfig(APIBaseTest):
self.client.patch(
self._url(prefix),
- {"logs_distinct_id_attribute_key": "user.id"},
+ {"logs_distinct_id_attribute_keys": ["user.id"]},
format="json",
)
@@ -117,11 +135,11 @@ class TestTeamLogsConfig(APIBaseTest):
# same env-scoped TeamLogsConfig keyed by team_id.
self.client.patch(
f"/api/projects/{self.team.id}/logs_config/",
- {"logs_distinct_id_attribute_key": "user.id"},
+ {"logs_distinct_id_attribute_keys": ["user.id"]},
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_keys"], ["user.id"])
def test_patch_updates_session_id_keys_preserving_order(self):
response = self.client.patch(
@@ -146,7 +164,7 @@ class TestTeamLogsConfig(APIBaseTest):
)
self.client.patch(
f"/api/projects/{self.team.id}/logs_config/",
- {"logs_distinct_id_attribute_key": "user.id"},
+ {"logs_distinct_id_attribute_keys": ["user.id"]},
format="json",
)
@@ -155,46 +173,54 @@ class TestTeamLogsConfig(APIBaseTest):
response.json(),
{
"logs_distinct_id_attribute_key": "user.id",
+ "logs_distinct_id_attribute_keys": ["user.id"],
"logs_session_id_attribute_keys": ["session.id"],
},
)
- def test_patch_rejects_invalid_session_id_keys(self):
+ @parameterized.expand(
+ [
+ ("distinct_id", "logs_distinct_id_attribute_keys"),
+ ("session_id", "logs_session_id_attribute_keys"),
+ ]
+ )
+ def test_patch_rejects_invalid_keys(self, _name: str, field: str):
# 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": []},
+ {field: []},
format="json",
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+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"]),
+ ("duplicate_after_trim", ["session.id", " session.id "]),
+ ("too_many_keys", [f"key{i}" for i in range(11)]),
+ ("key_over_max_length", ["x" * 201]),
+]
+
+
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]),
- ]
+ [(f"{field}_{name}", field, keys) for field in KEY_LIST_FIELDS for name, keys in INVALID_KEY_LISTS]
)
- def test_rejects_invalid_session_id_keys(self, _name: str, keys):
- serializer = TeamLogsConfigSerializer(data={"logs_session_id_attribute_keys": keys}, partial=True)
+ def test_rejects_invalid_keys(self, _name: str, field: str, keys):
+ serializer = TeamLogsConfigSerializer(data={field: keys}, partial=True)
self.assertFalse(serializer.is_valid())
- self.assertIn("logs_session_id_attribute_keys", serializer.errors)
+ self.assertIn(field, serializer.errors)
- def test_trims_whitespace_from_keys(self):
- serializer = TeamLogsConfigSerializer(
- data={"logs_session_id_attribute_keys": [" session.id ", "sessionId"]}, partial=True
- )
+ @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)
self.assertTrue(serializer.is_valid())
- self.assertEqual(
- serializer.validated_data["logs_session_id_attribute_keys"],
- ["session.id", "sessionId"],
- )
+ self.assertEqual(serializer.validated_data[field], ["first.key", "second.key"])
diff --git a/posthog/api/test/test_team_project_differential.py b/posthog/api/test/test_team_project_differential.py
index 855d11feba75..a5c78c3d24c2 100644
--- a/posthog/api/test/test_team_project_differential.py
+++ b/posthog/api/test/test_team_project_differential.py
@@ -342,7 +342,7 @@ WRITE_ACTION_CASES = [
"logs_config",
"patch",
"logs_config/",
- {"logs_distinct_id_attribute_key": "myDistinctId"},
+ {"logs_distinct_id_attribute_keys": ["myDistinctId"]},
status.HTTP_200_OK,
"full_body",
),
diff --git a/products/logs/backend/logs_query_runner.py b/products/logs/backend/logs_query_runner.py
index 158c88e6fd82..73c7ee86eac6 100644
--- a/products/logs/backend/logs_query_runner.py
+++ b/products/logs/backend/logs_query_runner.py
@@ -6,12 +6,14 @@ from zoneinfo import ZoneInfo
from posthog.schema import (
CachedLogsQueryResponse,
+ FilterLogicalOperator,
HogQLFilters,
IntervalType,
LogPropertyFilter,
LogPropertyFilterType,
LogsQuery,
LogsQueryResponse,
+ PropertyGroupFilterValue,
PropertyGroupsMode,
PropertyOperator,
)
@@ -207,6 +209,41 @@ def _get_property_type(value) -> str:
return "str"
+def _map_attribute_filter_type(property_filter: LogPropertyFilter) -> LogPropertyFilter:
+ """Suffix a log attribute filter's key with its detected value type so it targets the
+ right typed attributes map (attributes_map_str / attributes_map_float).
+
+ Values that all convert cleanly to float use the __float map; anything else sticks to
+ __str. Datetime is left out until there's a decent UI for datetime filtering. Returns
+ a copy; filters without a value are returned unchanged.
+ """
+ if not property_filter.value:
+ return property_filter
+
+ property_type = "str"
+ if isinstance(property_filter.value, list):
+ property_types = {_get_property_type(v) for v in property_filter.value}
+ # only use the detected type if all given values have the same type
+ # e.g. if values are '1', '2', we can use float, if values are '1', 'a', stick to str
+ if len(property_types) == 1:
+ property_type = property_types.pop()
+ else:
+ property_type = _get_property_type(property_filter.value)
+
+ mapped = property_filter.copy(deep=True)
+ mapped.key = f"{mapped.key}__{property_type}"
+ return mapped
+
+
+def _validated_attribute_group(group: PropertyGroupFilterValue) -> PropertyGroupFilterValue:
+ if not group.values:
+ raise QueryError("Nested filter groups in logs queries must contain at least one filter")
+ for leaf in group.values:
+ if not isinstance(leaf, LogPropertyFilter) or leaf.type != LogPropertyFilterType.LOG_ATTRIBUTE:
+ raise QueryError("Nested filter groups in logs queries support only log_attribute filters")
+ return group
+
+
class LogsFilterBuilder:
"""Builds HogQL WHERE clause AST from LogsQuery filter fields.
@@ -236,8 +273,15 @@ class LogsFilterBuilder:
self.resource_attribute_negative_filters: list[LogPropertyFilter] = []
self.log_filters: list[LogPropertyFilter] = []
self.attribute_filters: list[LogPropertyFilter] = []
+ # Nested groups inside a property group — used to OR one value across several
+ # attribute keys (e.g. matching a person's distinct_id against every configured
+ # `logs_distinct_id_attribute_keys` entry). Only log_attribute leaves supported.
+ self.attribute_filter_groups: list[PropertyGroupFilterValue] = []
if self.query.filterGroup and len(self.query.filterGroup.values) > 0:
for property_group in self.query.filterGroup.values:
+ for nested_group in property_group.values:
+ if isinstance(nested_group, PropertyGroupFilterValue):
+ self.attribute_filter_groups.append(_validated_attribute_group(nested_group))
self.resource_attribute_filters = cast(
list[LogPropertyFilter],
[
@@ -260,35 +304,15 @@ class LogsFilterBuilder:
[f for f in property_group.values if f.type == LogPropertyFilterType.LOG],
)
- # dynamically detect type of the given property values
- # if they all convert cleanly to float, use the __float property mapping instead
- # we keep multiple attribute maps for different types:
- # attribute_map_str
- # attribute_map_float
- # attribute_map_datetime
- #
- # for now we'll just check str and float as we need a decent UI for datetime filtering.
+ # dynamically detect type of the given property values via the typed attribute
+ # maps (attribute_map_str / attribute_map_float) — see _map_attribute_filter_type
for property_filter in self.query.filterGroup.values[0].values:
# we only do the type mapping for log attributes
if property_filter.type != LogPropertyFilterType.LOG_ATTRIBUTE:
continue
if isinstance(property_filter, LogPropertyFilter) and property_filter.value:
- property_type = "str"
- if isinstance(property_filter.value, list):
- property_types = {_get_property_type(v) for v in property_filter.value}
- # only use the detected type if all given values have the same type
- # e.g. if values are '1', '2', we can use float, if values are '1', 'a', stick to str
- if len(property_types) == 1:
- property_type = property_types.pop()
- else:
- property_type = _get_property_type(property_filter.value)
-
- # defensive copy as we mutate the filter here and don't want to impact other copies
- property_filter = property_filter.copy(deep=True)
- property_filter.key = f"{property_filter.key}__{property_type}"
-
- self.attribute_filters.insert(0, property_filter)
+ self.attribute_filters.insert(0, _map_attribute_filter_type(property_filter))
if self.exclude_resource_attribute is not None:
self.resource_attribute_filters = [
@@ -336,6 +360,18 @@ class LogsFilterBuilder:
if self.attribute_filters:
exprs.append(property_to_expr(self.attribute_filters, team=self.team))
+ for group in self.attribute_filter_groups:
+ leaf_exprs = [
+ property_to_expr(_map_attribute_filter_type(cast(LogPropertyFilter, leaf)), team=self.team)
+ for leaf in group.values
+ ]
+ if len(leaf_exprs) == 1:
+ exprs.append(leaf_exprs[0])
+ elif group.type == FilterLogicalOperator.OR_:
+ exprs.append(ast.Or(exprs=leaf_exprs))
+ else:
+ exprs.append(ast.And(exprs=leaf_exprs))
+
if self.log_filters:
for log_filter in self.log_filters:
if log_filter.key == "severity_level":
diff --git a/products/logs/backend/migrations/0018_teamlogsconfig_logs_distinct_id_attribute_keys.py b/products/logs/backend/migrations/0018_teamlogsconfig_logs_distinct_id_attribute_keys.py
new file mode 100644
index 000000000000..0fe484e0f76e
--- /dev/null
+++ b/products/logs/backend/migrations/0018_teamlogsconfig_logs_distinct_id_attribute_keys.py
@@ -0,0 +1,23 @@
+import django.contrib.postgres.fields
+from django.db import migrations, models
+
+import products.logs.backend.models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0017_logsmetricrule"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="teamlogsconfig",
+ name="logs_distinct_id_attribute_keys",
+ field=django.contrib.postgres.fields.ArrayField(
+ base_field=models.CharField(max_length=200),
+ db_default=models.Value("{posthogDistinctId}"),
+ default=products.logs.backend.models.default_logs_distinct_id_attribute_keys,
+ size=None,
+ ),
+ ),
+ ]
diff --git a/products/logs/backend/migrations/0019_backfill_logs_distinct_id_attribute_keys.py b/products/logs/backend/migrations/0019_backfill_logs_distinct_id_attribute_keys.py
new file mode 100644
index 000000000000..1402cf0c849c
--- /dev/null
+++ b/products/logs/backend/migrations/0019_backfill_logs_distinct_id_attribute_keys.py
@@ -0,0 +1,29 @@
+from django.db import migrations
+
+BATCH_SIZE = 1000
+
+
+def backfill_distinct_id_attribute_keys(apps, schema_editor):
+ TeamLogsConfig = apps.get_model("logs", "TeamLogsConfig")
+ # The ADD COLUMN default already filled every row with {posthogDistinctId}; only
+ # rows with a customized single key need their value carried into the array.
+ configs = TeamLogsConfig.objects.exclude(logs_distinct_id_attribute_key="posthogDistinctId")
+ batch = []
+ for config in configs.iterator(chunk_size=BATCH_SIZE):
+ config.logs_distinct_id_attribute_keys = [config.logs_distinct_id_attribute_key]
+ batch.append(config)
+ if len(batch) >= BATCH_SIZE:
+ TeamLogsConfig.objects.bulk_update(batch, ["logs_distinct_id_attribute_keys"])
+ batch = []
+ if batch:
+ TeamLogsConfig.objects.bulk_update(batch, ["logs_distinct_id_attribute_keys"])
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("logs", "0018_teamlogsconfig_logs_distinct_id_attribute_keys"),
+ ]
+
+ operations = [
+ migrations.RunPython(backfill_distinct_id_attribute_keys, migrations.RunPython.noop),
+ ]
diff --git a/products/logs/backend/migrations/max_migration.txt b/products/logs/backend/migrations/max_migration.txt
index b0a032a6f6c6..57d22b681823 100644
--- a/products/logs/backend/migrations/max_migration.txt
+++ b/products/logs/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0017_logsmetricrule
+0019_backfill_logs_distinct_id_attribute_keys
diff --git a/products/logs/backend/models.py b/products/logs/backend/models.py
index ae437a4e2957..55365f47c590 100644
--- a/products/logs/backend/models.py
+++ b/products/logs/backend/models.py
@@ -27,6 +27,13 @@ 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_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS = [DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY]
+
+
+def default_logs_distinct_id_attribute_keys() -> list[str]:
+ return list(DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS)
+
+
# 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
@@ -47,15 +54,24 @@ class TeamLogsConfig(models.Model):
# 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.
+ # Legacy single-key predecessor of `logs_distinct_id_attribute_keys`, kept in sync
+ # with its first entry so pre-plural readers stay coherent. Do not write directly.
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,
)
+ # Log attribute keys whose values match a PostHog person's distinct_id — a log links
+ # to a person when any of these attributes equals one of the person's distinct IDs.
+ # 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_keys = ArrayField(
+ models.CharField(max_length=200),
+ default=default_logs_distinct_id_attribute_keys,
+ db_default=Value("{posthogDistinctId}"),
+ )
+
# 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.
diff --git a/products/logs/backend/test/test_logs_query_runner.py b/products/logs/backend/test/test_logs_query_runner.py
index 100d21434a9e..3cf39ac074ca 100644
--- a/products/logs/backend/test/test_logs_query_runner.py
+++ b/products/logs/backend/test/test_logs_query_runner.py
@@ -20,6 +20,7 @@ from posthog.schema import (
PropertyOperator,
)
+from posthog.hogql.errors import QueryError
from posthog.hogql.query import HogQLQueryExecutor
from posthog.clickhouse.client import sync_execute
@@ -83,6 +84,134 @@ class TestAttributeFilters(APIBaseTest):
# this optimization was premature and needs more thought, and probably has very little benefit anyway
self.assertNotIn("in(resource_fingerprint", query_str)
+ def _to_clickhouse_sql(self, query: LogsQuery) -> str:
+ runner = LogsQueryRunner(query=query, team=self.team)
+ executor = HogQLQueryExecutor(
+ query_type="LogsQuery",
+ query=runner.to_query(),
+ modifiers=runner.modifiers,
+ team=runner.team,
+ workload=Workload.LOGS,
+ timings=runner.timings,
+ limit_context=runner.limit_context,
+ filters=HogQLFilters(dateRange=runner.query.dateRange),
+ settings=runner.settings,
+ )
+ executor.generate_clickhouse_sql()
+ assert executor.clickhouse_prepared_ast is not None
+ return executor.clickhouse_prepared_ast.to_hogql()
+
+ def test_nested_or_group_ors_across_attribute_keys(self):
+ # The person profile Logs tab pins an OR group so one person's distinct_ids
+ # match against every configured distinct-id attribute key. A regression that
+ # drops nested groups would silently return unfiltered logs.
+ query = LogsQuery(
+ dateRange=DateRange(date_from="2024-01-10T00:00:00Z", date_to="2024-01-15T23:59:59Z"),
+ serviceNames=[],
+ severityLevels=[],
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.OR_,
+ values=[
+ LogPropertyFilter(
+ key="posthogDistinctId",
+ operator=PropertyOperator.EXACT,
+ type=LogPropertyFilterType.LOG_ATTRIBUTE,
+ value=["distinct-1", "distinct-2"],
+ ),
+ LogPropertyFilter(
+ key="user.id",
+ operator=PropertyOperator.EXACT,
+ type=LogPropertyFilterType.LOG_ATTRIBUTE,
+ value=["distinct-1", "distinct-2"],
+ ),
+ ],
+ )
+ ],
+ )
+ ],
+ ),
+ kind="LogsQuery",
+ )
+
+ query_str = self._to_clickhouse_sql(query)
+
+ self.assertIn("posthogDistinctId", query_str)
+ self.assertIn("user.id", query_str)
+ self.assertIn("or(", query_str.lower())
+
+ def test_nested_group_with_single_filter_needs_no_or(self):
+ query = LogsQuery(
+ dateRange=DateRange(date_from="2024-01-10T00:00:00Z", date_to="2024-01-15T23:59:59Z"),
+ serviceNames=[],
+ severityLevels=[],
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.OR_,
+ values=[
+ LogPropertyFilter(
+ key="posthogDistinctId",
+ operator=PropertyOperator.EXACT,
+ type=LogPropertyFilterType.LOG_ATTRIBUTE,
+ value="distinct-1",
+ ),
+ ],
+ )
+ ],
+ )
+ ],
+ ),
+ kind="LogsQuery",
+ )
+
+ query_str = self._to_clickhouse_sql(query)
+
+ self.assertIn("posthogDistinctId", query_str)
+
+ def test_nested_group_rejects_non_attribute_filters(self):
+ # Only log_attribute leaves are supported inside nested groups; anything else
+ # must fail loudly rather than be silently dropped from the WHERE clause.
+ query = LogsQuery(
+ dateRange=DateRange(date_from="2024-01-10T00:00:00Z", date_to="2024-01-15T23:59:59Z"),
+ serviceNames=[],
+ severityLevels=[],
+ filterGroup=PropertyGroupFilter(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.AND_,
+ values=[
+ PropertyGroupFilterValue(
+ type=FilterLogicalOperator.OR_,
+ values=[
+ LogPropertyFilter(
+ key="message",
+ operator=PropertyOperator.ICONTAINS,
+ type=LogPropertyFilterType.LOG,
+ value="error",
+ ),
+ ],
+ )
+ ],
+ )
+ ],
+ ),
+ kind="LogsQuery",
+ )
+
+ with self.assertRaises(QueryError):
+ LogsQueryRunner(query=query, team=self.team).to_query()
+
def test_resource_attribute_filters(self):
"""Test that resource attribute filters are properly handled"""
query = LogsQuery(
diff --git a/products/logs/backend/test/test_models.py b/products/logs/backend/test/test_models.py
index b5ef2a77a325..ae0cf0943901 100644
--- a/products/logs/backend/test/test_models.py
+++ b/products/logs/backend/test/test_models.py
@@ -1,8 +1,10 @@
+import importlib
from datetime import UTC, datetime, timedelta
from freezegun import freeze_time
from posthog.test.base import BaseTest
+from django.apps import apps
from django.core.exceptions import ValidationError
from parameterized import parameterized
@@ -233,14 +235,31 @@ class TestTeamLogsConfig(BaseTest):
# 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"
+ assert config.logs_distinct_id_attribute_keys == ["posthogDistinctId"]
- def test_custom_attribute_key_persists(self):
+ def test_custom_attribute_keys_persist(self):
config = get_or_create_team_extension(self.team, TeamLogsConfig)
- config.logs_distinct_id_attribute_key = "user.id"
+ config.logs_distinct_id_attribute_keys = ["user.id", "posthogDistinctId"]
config.save()
refetched = get_or_create_team_extension(self.team, TeamLogsConfig)
- assert refetched.logs_distinct_id_attribute_key == "user.id"
+ assert refetched.logs_distinct_id_attribute_keys == ["user.id", "posthogDistinctId"]
+
+ def test_migration_backfill_carries_customized_single_key_into_array(self):
+ # Simulate the post-AddField state: a team that customized the singular key
+ # before the plural column existed has the ADD COLUMN default in the array.
+ customized = get_or_create_team_extension(self.team, TeamLogsConfig)
+ customized.logs_distinct_id_attribute_key = "user.id"
+ customized.logs_distinct_id_attribute_keys = ["posthogDistinctId"]
+ customized.save()
+
+ backfill_module = importlib.import_module(
+ "products.logs.backend.migrations.0019_backfill_logs_distinct_id_attribute_keys"
+ )
+ backfill_module.backfill_distinct_id_attribute_keys(apps, None)
+
+ customized.refresh_from_db()
+ assert customized.logs_distinct_id_attribute_keys == ["user.id"]
def test_cascade_delete_with_team(self):
get_or_create_team_extension(self.team, TeamLogsConfig)
diff --git a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
index ff03f8b32bde..3e482cbb63bb 100644
--- a/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/Filters/logsViewerFiltersLogic.ts
@@ -45,8 +45,8 @@ export interface LogsViewerFiltersLogicProps {
// a distinct_id filter so the tab can't fall back to project-wide logs). Kept
// entirely separate from the user-editable `filterGroup` — combined with it only
// at query-build time via `queryFilterGroup` so the chips never see them and
- // can't drift when the pinned shape changes (e.g. `logs_distinct_id_attribute_key`
- // resolves to a non-default key after mount).
+ // can't drift when the pinned shape changes (e.g. `logs_distinct_id_attribute_keys`
+ // resolves to non-default keys after mount).
pinnedFilters?: UniversalFiltersGroup
}
diff --git a/products/logs/frontend/components/LogsViewer/LogAttributes.tsx b/products/logs/frontend/components/LogsViewer/LogAttributes.tsx
index 0c41ee706dc2..2d8e2fefc5dd 100644
--- a/products/logs/frontend/components/LogsViewer/LogAttributes.tsx
+++ b/products/logs/frontend/components/LogsViewer/LogAttributes.tsx
@@ -28,7 +28,7 @@ export interface LogAttributesProps {
export function LogAttributes({ attributes, type, logUuid, title }: LogAttributesProps): JSX.Element {
const { expandedAttributeBreakdowns, id, isAttributeColumn } = useValues(logsViewerLogic)
- const { configuredSessionIdKeys } = useValues(logsConfigLogic)
+ const { configuredDistinctIdKeys, configuredSessionIdKeys } = useValues(logsConfigLogic)
const { addFilter, toggleAttributeColumn, toggleAttributeBreakdown } = useActions(logsViewerLogic)
const expandedBreakdownsForThisLog = expandedAttributeBreakdowns[logUuid] || []
@@ -136,7 +136,7 @@ export function LogAttributes({ attributes, type, logUuid, title }: LogAttribute
selectable
className="gap-1 font-mono text-xs"
>
- {isDistinctIdKey(record.key) ? (
+ {isDistinctIdKey(record.key, configuredDistinctIdKeys) ? (
<span onClick={(e) => e.stopPropagation()}>
<PersonDisplay person={{ distinct_id: record.value }} noEllipsis inline />
</span>
diff --git a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
index dac1a99efa92..97a863c0cc9a 100644
--- a/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
+++ b/products/logs/frontend/components/LogsViewer/data/logsViewerDataLogic.ts
@@ -960,7 +960,7 @@ export const logsViewerDataLogic = kea<logsViewerDataLogicType>([
subscriptions(({ actions }) => ({
// Subscribe to the combined query view rather than the user-editable filterGroup
- // so the query reruns when pinned filters change (e.g. team `logs_distinct_id_attribute_key`
+ // so the query reruns when pinned filters change (e.g. team `logs_distinct_id_attribute_keys`
// resolves after mount), not just when the user edits filters.
queryFilterGroup: (filterGroup: UniversalFiltersGroup, oldFilterGroup: UniversalFiltersGroup | undefined) => {
if (shouldSkipFilterGroupChange(filterGroup, oldFilterGroup)) {
diff --git a/products/logs/frontend/logsConfigLogic.ts b/products/logs/frontend/logsConfigLogic.ts
index 5bdf0687ea4e..b38b589cfa57 100644
--- a/products/logs/frontend/logsConfigLogic.ts
+++ b/products/logs/frontend/logsConfigLogic.ts
@@ -10,18 +10,23 @@ import { teamLogic } from 'scenes/teamLogic'
// SDK convention before `logs_config` resolves.
export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY = 'posthogDistinctId'
+export const DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEYS = [DEFAULT_LOGS_DISTINCT_ID_ATTRIBUTE_KEY]
+
// 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 {
+ // 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[]
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface logsConfigLogicValues {
currentTeamId: number | null // teamLogic
+ configuredDistinctIdKeys: string[] | undefined
configuredSessionIdKeys: string[] | undefined
logsConfig: LogsConfig | null
logsConfigLoading: boolean
@@ -64,6 +69,7 @@ export interface logsConfigLogicActions {
// 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
}
}
@@ -94,6 +100,12 @@ export const logsConfigLogic = kea<logsConfigLogicType>([
],
})),
selectors({
+ // Undefined until logs_config resolves — distinct-id detection falls back to its
+ // 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,
+ ],
// Undefined until logs_config resolves — session detection falls back to its
// built-in convention list (which contains the default) in the meantime.
configuredSessionIdKeys: [
diff --git a/products/logs/frontend/utils.test.ts b/products/logs/frontend/utils.test.ts
index b0d8d704f8f8..72752b2f3373 100644
--- a/products/logs/frontend/utils.test.ts
+++ b/products/logs/frontend/utils.test.ts
@@ -43,6 +43,18 @@ describe('logs utils', () => {
})
})
+ describe('isDistinctIdKey with configured keys', () => {
+ it('matches a configured key exactly, without dot-suffix expansion', () => {
+ expect(isDistinctIdKey('user.id', ['user.id'])).toBe(true)
+ expect(isDistinctIdKey('prefixed.user.id', ['user.id'])).toBe(false)
+ })
+
+ it('keeps matching the built-in conventions alongside configured keys', () => {
+ expect(isDistinctIdKey('posthogDistinctId', ['user.id'])).toBe(true)
+ expect(isDistinctIdKey('unrelated', ['user.id'])).toBe(false)
+ })
+ })
+
describe.each([
// Exact matches
['session.id', true],
diff --git a/products/logs/frontend/utils.tsx b/products/logs/frontend/utils.tsx
index 4e30f5c2294a..8050dc8002a0 100644
--- a/products/logs/frontend/utils.tsx
+++ b/products/logs/frontend/utils.tsx
@@ -97,8 +97,10 @@ function matchesKey(key: string, candidates: string[]): boolean {
return candidates.some((candidate) => key === candidate || key.endsWith(`.${candidate}`))
}
-export function isDistinctIdKey(key: string): boolean {
- return matchesKey(key, DISTINCT_ID_KEYS)
+// Configured keys (the team's `logs_distinct_id_attribute_keys` setting) match exactly;
+// only the built-in convention list gets dot-suffix matching.
+export function isDistinctIdKey(key: string, configuredKeys?: string[]): boolean {
+ return (configuredKeys ?? []).includes(key) || matchesKey(key, DISTINCT_ID_KEYS)
}
// Configured keys (the team's `logs_session_id_attribute_keys` setting) match exactly;
diff --git a/products/logs/mcp/prompts/query-logs.md b/products/logs/mcp/prompts/query-logs.md
index f48c456b4a13..5b0dc486d878 100644
--- a/products/logs/mcp/prompts/query-logs.md
+++ b/products/logs/mcp/prompts/query-logs.md
@@ -50,9 +50,9 @@ The `value` field accepts a string, number, or array of strings depending on the
## Filtering logs by a PostHog person
-When the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via a `log_attribute` filter. The attribute key is configurable per project (it defaults to `distinct_id`); read `logs_distinct_id_attribute_key` from the team config (returned on `projects-retrieve` / `environments-retrieve`, or via the `/api/projects/:id/logs_config/` endpoint) and use that as the filter `key`.
+When the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `["posthogDistinctId"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.
-If the team has not configured a custom key, use `distinct_id`. If a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them).
+If a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):
```json
{
@@ -60,7 +60,7 @@ If the team has not configured a custom key, use `distinct_id`. If a person has
"serviceNames": ["<service>"],
"filterGroup": [
{
- "key": "distinct_id",
+ "key": "posthogDistinctId",
"operator": "exact",
"type": "log_attribute",
"value": ["<distinct_id_1>", "<distinct_id_2>"]
@@ -70,7 +70,9 @@ If the team has not configured a custom key, use `distinct_id`. If a person has
}
```
-Do not invent a different attribute key based on what looks plausible — use the configured key. If the configured key returns zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.
+Entries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.
+
+Do not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.
## Time period
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index ec8083a3e1d9..4326252178e4 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -7238,7 +7238,7 @@
"system_prompt_hint": "LLM/AI trace listing and inspection"
},
"query-logs": {
- "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via a `log_attribute` filter. The attribute key is configurable per project (it defaults to `distinct_id`); read `logs_distinct_id_attribute_key` from the team config (returned on `projects-retrieve` / `environments-retrieve`, or via the `/api/projects/:id/logs_config/` endpoint) and use that as the filter `key`.\n\nIf the team has not configured a custom key, use `distinct_id`. If a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them).\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"distinct_id\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nDo not invent a different attribute key based on what looks plausible — use the configured key. If the configured key returns zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",
+ "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",
"category": "Logs",
"feature": "logs",
"summary": "Query logs",
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index c05d7eb2d4ae..f70d30537a7e 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -7773,7 +7773,7 @@
"system_prompt_hint": "LLM/AI trace listing and inspection"
},
"query-logs": {
- "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via a `log_attribute` filter. The attribute key is configurable per project (it defaults to `distinct_id`); read `logs_distinct_id_attribute_key` from the team config (returned on `projects-retrieve` / `environments-retrieve`, or via the `/api/projects/:id/logs_config/` endpoint) and use that as the filter `key`.\n\nIf the team has not configured a custom key, use `distinct_id`. If a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them).\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"distinct_id\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nDo not invent a different attribute key based on what looks plausible — use the configured key. If the configured key returns zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",
+ "description": "Query log entries with filtering by severity, service name, date range, search term, and structured attribute filters. Supports cursor-based pagination. The response schema (see the tool's typed output) lists every returned field — prefer `severity_text` over `severity_number` / `level`, and be aware that `trace_id` and `span_id` return zero-padded strings rather than null when unset.\n\nUse `logs-attributes-list` and `logs-attribute-values-list` to discover available attributes before building filters.\n\n# Workflow — follow this order every time\n\n1. **Discover services first.** Call `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to see available services.\n2. **Explore resource attributes.** Call `logs-attributes-list` with `attribute_type: \"resource\"` to discover resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`). Then call `logs-attribute-values-list` with `attribute_type: \"resource\"` for relevant attributes to validate what data exists.\n3. **Explore log attributes if needed.** Call `logs-attributes-list` (defaults to log attributes) and `logs-attribute-values-list` to discover log-level attributes.\n4. **Size the total volume with `logs-count`.** Call `logs-count` with the discovered `serviceNames` and filters. If it exceeds `query-logs`'s max `limit` of 1000 — or if the user's question is about _when_ something happened — continue to step 5.\n5. **Find where the volume sits with `logs-count-ranges`.** Call `logs-count-ranges` to get time-bucketed counts. Each bucket carries explicit `date_from`/`date_to` you can pass straight back as the next call's `dateRange` to drill into a sub-range. Recurse up to 3–4 levels to narrow onto a spike or a specific window. Stop when the bucket width drops below your precision goal (e.g. 1 minute).\n6. **Only then query logs.** Once the count is in range and the window is right-sized, call `query-logs` with `serviceNames` and any additional filters.\n\nMany cheap calls (attribute/value queries, counts, count-ranges) beat one expensive `query-logs`. Prefer thorough exploration over speculative log searches.\n\nCRITICAL: Be minimalist. Only include filters and settings that are essential to answer the user's specific question. Default settings are usually sufficient unless the user explicitly requests customization.\n\nMANDATORY: Never call query-logs without setting `serviceNames` or at least one `log_resource_attribute` filter. Unfiltered log queries are too broad, expensive, and noisy. If the user hasn't specified a service, use the workflow above to discover services first, then ask or infer.\n\nMANDATORY: Always pass `query.dateRange` explicitly (e.g. `{ \"date_from\": \"-1h\" }`). Omitting it fails with a 400 `parse_error` (\"Input should be a valid dictionary or instance of DateRange\") — the server does not fall back to a default window.\n\nAll parameters must be nested inside a `query` object.\n\n# Data narrowing\n\n## Property filters\n\nUse property filters via the `query.filterGroup` field to narrow results. Only include property filters when they are essential to directly answer the user's question.\n\nWhen using a property filter, you should:\n\n- **Choose the right type.** Log property types are:\n - `log` — filters the log body/message. Use key \"message\" for this type.\n - `log_attribute` — filters log-level attributes (e.g. \"k8s.container.name\", \"http.method\").\n - `log_resource_attribute` — filters resource-level attributes (e.g. k8s labels, deployment info).\n- **Use `logs-attributes-list` to discover available attribute keys** before building filters.\n- **Use `logs-attribute-values-list` to discover valid values** for a specific attribute key.\n- **Find the suitable operator for the value type** (see supported operators below).\n\n**Important:** The `logs-attributes-list` and `logs-attribute-values-list` tools default to `attribute_type: \"log\"` (log-level attributes). To search resource-level attributes (e.g. `k8s.pod.name`, `k8s.namespace.name`), you must explicitly pass `attribute_type: \"resource\"`. Forgetting this will return log-level attributes when you intended resource-level ones.\n\nSupported operators:\n\n- String: `exact`, `is_not`, `icontains`, `not_icontains`, `regex`, `not_regex`\n- Numeric: `exact`, `gt`, `lt`\n- Date: `is_date_exact`, `is_date_before`, `is_date_after`\n- Existence (no value needed): `is_set`, `is_not_set`\n\nThe `value` field accepts a string, number, or array of strings depending on the operator. Omit `value` for `is_set`/`is_not_set`.\n\n## Filtering logs by a PostHog person\n\nWhen the user references a person — by `distinct_id`, name, email, or via a prior `persons-retrieve` call — filter logs to that person via `log_attribute` filters. The attribute keys are configurable per project (they default to `[\"posthogDistinctId\"]`); read `logs_distinct_id_attribute_keys` from the `/api/projects/:id/logs_config/` endpoint and use those as the filter `key`s.\n\nIf a person has multiple `distinct_ids`, pass the array as the filter `value` with operator `exact` (matches any of them):\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [\n {\n \"key\": \"posthogDistinctId\",\n \"operator\": \"exact\",\n \"type\": \"log_attribute\",\n \"value\": [\"<distinct_id_1>\", \"<distinct_id_2>\"]\n }\n ]\n }\n}\n```\n\nEntries in the `filterGroup` array are combined with AND, so never put two distinct-id keys in one call — a log only carries one of them. When the team has multiple keys configured, run one query per key and merge the results.\n\nDo not invent a different attribute key based on what looks plausible — use the configured keys. If the configured keys return zero results, the customer's logs pipeline may not stamp person identity at all; tell the user rather than guessing.\n\n## Time period\n\nUse the `query.dateRange` field to control the time window — pass it on every call. If the question doesn't mention time, use the last hour: `{ \"date_from\": \"-1h\" }`. Examples of relative dates: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n\n# Parameters\n\nAll parameters go inside `query`.\n\n## query.severityLevels\n\nFilter by log severity: `trace`, `debug`, `info`, `warn`, `error`, `fatal`. Omit to include all levels.\n\nThis filter is an **exact match against the response's `severity_text` field** using these six lowercase buckets — it is _not_ a numeric range and _not_ case-insensitive. If a service ingests non-canonical severity strings (e.g. `\"ERROR\"`, `\"Warning\"`, `\"err\"`), `severityLevels: [\"error\"]` will not match them and you will get zero rows. When a severity filter returns nothing unexpectedly, discover the actual stored values with `logs-attribute-values-list { key: \"severity_text\" }` and either filter on the value you find or fall back to a `searchTerm`. See \"Severity fields in the response\" below for the `severity_text` / `severity_number` / `level` mapping.\n\n## query.serviceNames\n\nFilter by service names. Use `logs-attribute-values-list` with `key: \"service.name\"` and `attribute_type: \"resource\"` to discover available services.\n\n## query.searchTerm\n\nFull-text search across log bodies. Use this when the user is looking for specific text in log messages.\n\n## query.orderBy\n\nSort by timestamp: `latest` (default) or `earliest`.\n\n## query.filterGroup\n\nA list of property filters to narrow results. Each filter specifies `key`, `operator`, `type` (log/log_attribute/log_resource_attribute), and optionally `value`. See the \"Property filters\" section above.\n\n## query.dateRange\n\nDate range to filter results. Required in practice: omitting it fails with a 400 `parse_error`, so always pass it (use `{ \"date_from\": \"-1h\" }` when the question doesn't mention time).\n\n- `date_from`: Start of the range. Accepts ISO 8601 timestamps or relative formats: `-1h`, `-6h`, `-1d`, `-7d`, `-30d`.\n- `date_to`: End of the range. Same format. Omit or null for \"now\".\n\n## query.limit\n\nMaximum number of results (1-1000). Defaults to 100.\n\n## query.after\n\nCursor for pagination. Use the `nextCursor` value from the previous response.\n\n## query.excludeAttributes\n\nSet `true` to drop the per-log `attributes` and `resource_attributes` maps from results (the maps stay present but empty). These maps can hold large values, so excluding them keeps big result sets compact — set it when you only need `body`, `severity_text`, `timestamp`, and `service`-level fields and not the full attribute maps. Defaults to false.\n\n# Examples\n\n## List recent error logs\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\", \"fatal\"],\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Search for a specific log message\n\n```json\n{\n \"query\": {\n \"searchTerm\": \"connection refused\",\n \"serviceNames\": [\"<service>\"],\n \"dateRange\": { \"date_from\": \"-6h\" }\n }\n}\n```\n\n## Filter logs from a specific service\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"api-gateway\"],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Filter by a log attribute\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"http.status_code\", \"operator\": \"exact\", \"type\": \"log_attribute\", \"value\": \"500\" }],\n \"dateRange\": { \"date_from\": \"-1d\" }\n }\n}\n```\n\n## Combine severity and attribute filters\n\n```json\n{\n \"query\": {\n \"severityLevels\": [\"error\"],\n \"filterGroup\": [\n { \"key\": \"k8s.container.name\", \"operator\": \"exact\", \"type\": \"log_resource_attribute\", \"value\": \"web\" }\n ],\n \"dateRange\": { \"date_from\": \"-12h\" }\n }\n}\n```\n\n## Filter by log body content using property filter\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"message\", \"operator\": \"icontains\", \"type\": \"log\", \"value\": \"timeout\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n## Check if an attribute exists\n\n```json\n{\n \"query\": {\n \"serviceNames\": [\"<service>\"],\n \"filterGroup\": [{ \"key\": \"trace_id\", \"operator\": \"is_set\", \"type\": \"log_attribute\" }],\n \"dateRange\": { \"date_from\": \"-1h\" }\n }\n}\n```\n\n# Severity fields in the response\n\nEach returned log row carries three overlapping severity fields. Read and report `severity_text`; treat the other two as redundant:\n\n| Field | What it is | Use it for |\n| ----------------- | --------------------------------------------------------------- | --------------------------------------------------------------------- |\n| `severity_text` | Canonical severity string. **Prefer this.** | Filtering (`severityLevels`), grouping, and anything you show a user. |\n| `severity_number` | OpenTelemetry numeric severity (1–24). Redundant with the text. | Sorting by exact severity, or interop with OTel tooling. |\n| `level` | ClickHouse alias for `severity_text`. Redundant. | Ignore — prefer `severity_text`. |\n\n`severity_number` maps to the `severityLevels` buckets by OTel range. Use this when you only have a number and need the bucket, or vice-versa:\n\n| Bucket | `severity_number` range | Canonical `severity_text` |\n| ------- | ----------------------- | ------------------------- |\n| `trace` | 1–4 | `trace` |\n| `debug` | 5–8 | `debug` |\n| `info` | 9–12 | `info` |\n| `warn` | 13–16 | `warn` |\n| `error` | 17–20 | `error` |\n| `fatal` | 21–24 | `fatal` |\n\nWhen the user asks for \"warnings and above\", that is `severityLevels: [\"warn\", \"error\", \"fatal\"]` — there is no numeric `>=` operator on the top-level severity filter.\n\n# If the query fails (500 / timeout)\n\nA `query-logs` call that returns a 500 almost always means the query scanned too much data and timed out server-side — it is rarely a bug in your filters. Do not retry the same call. Instead, narrow and re-size:\n\n1. Shorten `dateRange` (e.g. `-1h` instead of `-1d`).\n2. Add `serviceNames` or a `log_resource_attribute` filter to reduce the scan.\n3. Size the volume with `logs-count`, then locate the busy window with `logs-count-ranges`, before pulling rows again.\n\n# Reminders\n\n- Always set `serviceNames` or a resource attribute filter. Never run a broad unfiltered log query.\n- Limit `dateRange` to at most `-1d` (24 hours) unless the user explicitly requests a longer range.\n- When using `logs-attributes-list` or `logs-attribute-values-list`, remember they default to `attribute_type: \"log\"`. Pass `attribute_type: \"resource\"` to search resource-level attributes.\n- Ensure that any property filters are directly relevant to the user's question. Avoid unnecessary filtering.\n- Use `logs-attributes-list` and `logs-attribute-values-list` to discover attributes before guessing filter keys/values.\n- Prefer `searchTerm` for simple text matching; use `filterGroup` with type `log` and key `message` for regex or exact matching.",
"category": "Logs",
"feature": "logs",
"summary": "Query logs",