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): word native logs alert messages in logs terms (#114219)

Jimmy Zhu901cbbb5e77a
diff --git a/products/alerts_platform/backend/tests/test_delivery_message.py b/products/alerts_platform/backend/tests/test_delivery_message.py
index d4493a0056bc..5ee143425c28 100644
--- a/products/alerts_platform/backend/tests/test_delivery_message.py
+++ b/products/alerts_platform/backend/tests/test_delivery_message.py
@@ -1,3 +1,4 @@
+from collections.abc import Iterator
from datetime import UTC, datetime
from typing import Any
@@ -67,6 +68,13 @@ def _build(
class TestAlertMessage:
+ @pytest.fixture(autouse=True)
+ def _platform_wording_only(self) -> Iterator[None]:
+ # Sources register describers at startup. These tests state the platform's own wording, and
+ # the describer tests register theirs on top of this.
+ with patch.dict(describers._describers, {}, clear=True):
+ yield
+
@pytest.mark.parametrize(
"source,expected_headline",
[
diff --git a/products/logs/backend/apps.py b/products/logs/backend/apps.py
index 583694ad3f65..2b69fb627155 100644
--- a/products/logs/backend/apps.py
+++ b/products/logs/backend/apps.py
@@ -7,8 +7,16 @@ class LogsConfig(AppConfig):
label = "logs"
def ready(self) -> None:
- # Connect the logs alert / sampling-rule activity-log receivers at app-population, from a
- # dedicated light module. They must not live in the viewset modules: the lazy API router no
- # longer pulls those, and alerts_api transitively imports the whole query-runner layer,
- # which would drag posthog.schema and HogQL into django.setup() for every process type.
+ # Both imports happen at app-population, from dedicated light modules.
+ # - activity_logging connects the logs alert / sampling-rule activity-log receivers. They must
+ # not live in the viewset modules: the lazy API router no longer pulls those, and alerts_api
+ # transitively imports the whole query-runner layer, which would drag posthog.schema and
+ # HogQL into django.setup() for every process type.
+ # - The alerts platform cannot import this product, so native alert messages get the logs
+ # wording through the describer registered below.
+ from products.alerts_platform.backend.facade.contracts import SourceKind # noqa: PLC0415
+ from products.alerts_platform.backend.facade.delivery import register_source_describer # noqa: PLC0415
from products.logs.backend import activity_logging # noqa: F401, PLC0415
+ from products.logs.backend.platform_alert_wording import describe_logs_transition # noqa: PLC0415
+
+ register_source_describer(SourceKind.LOGS, describe_logs_transition)
diff --git a/products/logs/backend/logs_url_params.py b/products/logs/backend/logs_url_params.py
index 32e9fd76596f..4c4f061af528 100644
--- a/products/logs/backend/logs_url_params.py
+++ b/products/logs/backend/logs_url_params.py
@@ -45,7 +45,7 @@ def build_logs_url_params(
params["serviceNames"] = json.dumps(service_names)
filter_group = filters.get("filterGroup")
- if filter_group and _has_filter_values(filter_group):
+ if filter_group and has_filter_values(filter_group):
params["filterGroup"] = json.dumps(filter_group)
if date_from is not None or date_to is not None:
@@ -62,7 +62,7 @@ def build_logs_url_params(
return urlencode(params)
-def _has_filter_values(filter_group: dict) -> bool:
+def has_filter_values(filter_group: dict) -> bool:
"""True if the filter group contains at least one non-empty property filter."""
for group in filter_group.get("values", []):
if group.get("values"):
diff --git a/products/logs/backend/platform_alert_wording.py b/products/logs/backend/platform_alert_wording.py
new file mode 100644
index 000000000000..aacac6bd0b59
--- /dev/null
+++ b/products/logs/backend/platform_alert_wording.py
@@ -0,0 +1,75 @@
+"""How a logs alert reads in a native platform notification.
+
+The platform words a message generically ("Value: 11"). This gives it the logs wording the legacy
+messages use: a count of logs in a window, the filters the alert watches, and a link to the logs.
+
+Imported from `ready()`, so it stays light: no models, no query layer.
+"""
+
+from datetime import timedelta
+from typing import Any
+
+from posthog.utils import absolute_uri
+
+from products.alerts_platform.backend.facade.contracts import (
+ AlertEventKind,
+ AnnouncedTransition,
+ MessageDetail,
+ MessageLink,
+ SourceDescription,
+)
+from products.logs.backend.logs_url_params import build_logs_url_params, has_filter_values
+
+# A resolve reports the count that ended the firing, so it is not a breach. A held check, which
+# only moves a paging incident, can be either, so it gets a neutral label.
+_LABELS = {
+ AlertEventKind.FIRING: "Threshold breached",
+ AlertEventKind.RESOLVED: "Current count",
+}
+
+
+def describe_logs_transition(*, project_id: int, transition: AnnouncedTransition) -> SourceDescription:
+ # `source_config` holds the alert's filters beside the platform's `condition` key, which none
+ # of the readers below look at.
+ return SourceDescription(
+ details=_details(transition),
+ context=_context(transition.source_config),
+ data_link=MessageLink(label="View logs", url=_logs_url(project_id, transition)),
+ )
+
+
+def _details(transition: AnnouncedTransition) -> tuple[MessageDetail, ...]:
+ if transition.value is None:
+ return ()
+ condition = transition.condition
+ # A count of logs is a whole number, and `:g` would print a million as "1e+06".
+ value = transition.value
+ count = f"{value:,.0f}" if value.is_integer() else f"{value:g}"
+ noun = "log" if count == "1" else "logs"
+ summary = (
+ f"{count} {noun} in {condition['window_minutes']}m "
+ f"(threshold: {condition['threshold_operator']} {condition['threshold_count']})"
+ )
+ return (MessageDetail(label=_LABELS.get(transition.kind, "Count"), value=summary),)
+
+
+def _context(filters: dict[str, Any]) -> tuple[str, ...]:
+ lines: list[str] = []
+ severity_levels = filters.get("severityLevels") or []
+ service_names = filters.get("serviceNames") or []
+ filter_group = filters.get("filterGroup")
+ if severity_levels:
+ lines.append("Severity: " + ", ".join(severity_levels))
+ if service_names:
+ lines.append("Services: " + ", ".join(service_names))
+ if filter_group and has_filter_values(filter_group):
+ lines.append("Property filters applied")
+ return tuple(lines) or ("All log levels and services",)
+
+
+def _logs_url(project_id: int, transition: AnnouncedTransition) -> str:
+ # The window the check counted, so the link opens on the logs that decided it.
+ date_to = transition.occurred_at
+ date_from = date_to - timedelta(minutes=transition.condition["window_minutes"])
+ params = build_logs_url_params(transition.source_config, date_from=date_from, date_to=date_to)
+ return absolute_uri(f"/project/{project_id}/logs" + (f"?{params}" if params else ""))
diff --git a/products/logs/backend/test/test_platform_alert_wording.py b/products/logs/backend/test/test_platform_alert_wording.py
new file mode 100644
index 000000000000..c1031e53e1ee
--- /dev/null
+++ b/products/logs/backend/test/test_platform_alert_wording.py
@@ -0,0 +1,95 @@
+import json
+from datetime import UTC, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlsplit
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.alerts_platform.backend.facade.contracts import AlertEventKind, AnnouncedTransition, MessageDetail
+from products.logs.backend.platform_alert_wording import describe_logs_transition
+
+CONDITION = {"threshold_count": 10, "threshold_operator": "above", "window_minutes": 10}
+OCCURRED = datetime(2026, 10, 8, 18, 5, tzinfo=UTC)
+
+
+def _transition(
+ kind: AlertEventKind = AlertEventKind.FIRING, value: float | None = 11.0, filters: dict[str, Any] | None = None
+) -> AnnouncedTransition:
+ return AnnouncedTransition(
+ grouping_key="",
+ kind=kind,
+ episode_started_at=OCCURRED,
+ value=value,
+ labels={},
+ condition=CONDITION,
+ source_config={**(filters or {}), "condition": CONDITION},
+ error_message=None,
+ occurred_at=OCCURRED,
+ )
+
+
+class TestLogsPlatformAlertWording(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("firing", AlertEventKind.FIRING, 11.0, "Threshold breached", "11 logs in 10m (threshold: above 10)"),
+ ("resolved", AlertEventKind.RESOLVED, 3.0, "Current count", "3 logs in 10m (threshold: above 10)"),
+ ("held_check", AlertEventKind.CHECK, 1.0, "Count", "1 log in 10m (threshold: above 10)"),
+ (
+ "large_count",
+ AlertEventKind.FIRING,
+ 1_250_000.0,
+ "Threshold breached",
+ "1,250,000 logs in 10m (threshold: above 10)",
+ ),
+ ]
+ )
+ def test_a_transition_reads_as_a_count_of_logs(
+ self, _name: str, kind: AlertEventKind, value: float, label: str, summary: str
+ ) -> None:
+ description = describe_logs_transition(project_id=7, transition=_transition(kind, value))
+
+ assert description.details == (MessageDetail(label=label, value=summary),)
+
+ def test_a_check_without_a_value_leaves_the_details_to_the_platform(self) -> None:
+ description = describe_logs_transition(project_id=7, transition=_transition(AlertEventKind.ERRORED, value=None))
+
+ assert description.details == ()
+
+ @parameterized.expand(
+ [
+ (
+ "both",
+ {"severityLevels": ["error", "fatal"], "serviceNames": ["api"]},
+ ("Severity: error, fatal", "Services: api"),
+ ),
+ ("services_only", {"serviceNames": ["api", "worker"]}, ("Services: api, worker",)),
+ (
+ "property_filters_only",
+ {"filterGroup": {"type": "AND", "values": [{"type": "AND", "values": [{"key": "status"}]}]}},
+ ("Property filters applied",),
+ ),
+ ("no_filters", {}, ("All log levels and services",)),
+ ]
+ )
+ def test_the_context_names_the_filters_the_alert_watches(
+ self, _name: str, filters: dict[str, Any], expected: tuple[str, ...]
+ ) -> None:
+ description = describe_logs_transition(project_id=7, transition=_transition(filters=filters))
+
+ assert description.context == expected
+
+ def test_the_link_opens_the_logs_the_check_counted(self) -> None:
+ description = describe_logs_transition(project_id=7, transition=_transition(filters={"serviceNames": ["api"]}))
+
+ assert description.data_link is not None
+ assert description.data_link.label == "View logs"
+ url = urlsplit(description.data_link.url)
+ params = parse_qs(url.query)
+ assert url.path == "/project/7/logs"
+ assert json.loads(params["serviceNames"][0]) == ["api"]
+ assert json.loads(params["dateRange"][0]) == {
+ "date_from": "2026-10-08T17:55:00+00:00",
+ "date_to": "2026-10-08T18:05:00+00:00",
+ }