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(observability): link backend logs and spans to the frontend session (#114137)

Daniel Visca2ea750cde35a
diff --git a/posthog/middleware.py b/posthog/middleware.py
index 8e6d7c3286ad..812e391e8180 100644
--- a/posthog/middleware.py
+++ b/posthog/middleware.py
@@ -856,6 +856,14 @@ def per_request_logging_context_middleware(
if mcp_conversation_id:
span.set_attribute("mcp.conversation_id", mcp_conversation_id)
+ # posthog-js `tracing_headers` sends the browser session on app API calls. The key is
+ # `sessionId` because the Logs and Tracing session links look for that key by default,
+ # and the PostHog SDKs use it on their own spans. Caller-asserted, like the MCP headers.
+ frontend_session_id = sanitize_header_value(request.headers.get("X-Posthog-Session-Id"))
+ if frontend_session_id:
+ structlog.contextvars.bind_contextvars(sessionId=frontend_session_id)
+ trace.get_current_span().set_attribute("sessionId", frontend_session_id)
+
response: HttpResponse | None = None
try:
response = get_response(request)
@@ -916,14 +924,21 @@ def user_logging_context_middleware(
get_response: Callable[[HttpRequest], HttpResponse],
) -> Callable[[HttpRequest], HttpResponse]:
"""
- This middleware adds the team_id to the logging context if it exists. Note
- that this should be added after we have performed authentication, as we
- need the user to be authenticated to get the team_id.
+ This middleware adds the team_id and the user's distinct_id to the logging
+ context if they exist, and the distinct_id to the request span. Note that
+ this should be added after we have performed authentication, as we need
+ the user to be authenticated to get them.
"""
def middleware(request: HttpRequest) -> HttpResponse:
if request.user.is_authenticated:
structlog.contextvars.bind_contextvars(team_id=request.user.current_team_id)
+ # `posthogDistinctId` is the key that the Logs and Tracing person links look for by default.
+ # The span gets no team_id here, because current_team_id can differ from the team in the URL.
+ # TeamAndOrgViewSetMixin tags the span with the team that the view resolves.
+ if distinct_id := request.user.distinct_id:
+ structlog.contextvars.bind_contextvars(posthogDistinctId=distinct_id)
+ trace.get_current_span().set_attribute("posthogDistinctId", distinct_id)
return get_response(request)
diff --git a/posthog/test/test_middleware.py b/posthog/test/test_middleware.py
index dfd971818e71..8874102bc6cf 100644
--- a/posthog/test/test_middleware.py
+++ b/posthog/test/test_middleware.py
@@ -10,6 +10,7 @@ from posthog.test.base import APIBaseTest, FuzzyInt, override_settings
from unittest.mock import MagicMock, patch
from django.conf import settings
+from django.contrib.auth.models import AnonymousUser
from django.core.cache import cache
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.test import (
@@ -36,6 +37,7 @@ from posthog.middleware import (
ManagedProxyClientIPMiddleware,
SignedClientIPOutcome,
per_request_logging_context_middleware,
+ user_logging_context_middleware,
)
from posthog.models.activity_logging.activity_log import ActivityLog
from posthog.models.organization import Organization, OrganizationMembership
@@ -2877,4 +2879,60 @@ class TestPerRequestLoggingContextMiddlewareMcpHeaders(SimpleTestCase):
assert "mcp_session_id" not in ctx
assert "mcp_conversation_id" not in ctx
+ assert "sessionId" not in ctx
+ span.set_attribute.assert_not_called()
+
+ @parameterized.expand(
+ [
+ ("plain", "01a11c97-2437-72c0-b147-66a8e9f56ec3", "01a11c97-2437-72c0-b147-66a8e9f56ec3"),
+ ("control_chars_stripped", "01a11c97-2437\n-72c0", "01a11c97-2437-72c0"),
+ ("blank", " ", None),
+ ]
+ )
+ def test_binds_frontend_session_id(self, _name: str, header_value: str, expected: str | None) -> None:
+ with patch("posthog.middleware.trace") as mock_trace:
+ span = MagicMock()
+ mock_trace.get_current_span.return_value = span
+ ctx = self._run_middleware(HTTP_X_POSTHOG_SESSION_ID=header_value)
+
+ if expected is None:
+ assert "sessionId" not in ctx
+ span.set_attribute.assert_not_called()
+ else:
+ assert ctx["sessionId"] == expected
+ span.set_attribute.assert_any_call("sessionId", expected)
+
+
+class TestUserLoggingContextMiddleware(APIBaseTest):
+ def _run_middleware(self, user: User | AnonymousUser) -> tuple[dict[str, Any], MagicMock]:
+ captured: dict[str, Any] = {}
+
+ def get_response(request: HttpRequest) -> HttpResponse:
+ captured["ctx"] = dict(structlog.contextvars.get_contextvars())
+ return HttpResponse()
+
+ request = RequestFactory().get("/")
+ request.user = user
+ try:
+ structlog.contextvars.clear_contextvars()
+ with patch("posthog.middleware.trace") as mock_trace:
+ span = MagicMock()
+ mock_trace.get_current_span.return_value = span
+ user_logging_context_middleware(get_response)(request)
+ finally:
+ structlog.contextvars.clear_contextvars()
+ return captured["ctx"], span
+
+ def test_binds_team_and_distinct_id_for_authenticated_user(self) -> None:
+ ctx, span = self._run_middleware(self.user)
+
+ assert ctx["team_id"] == self.team.pk
+ assert ctx["posthogDistinctId"] == self.user.distinct_id
+ span.set_attribute.assert_called_once_with("posthogDistinctId", self.user.distinct_id)
+
+ def test_binds_nothing_for_anonymous_user(self) -> None:
+ ctx, span = self._run_middleware(AnonymousUser())
+
+ assert "team_id" not in ctx
+ assert "posthogDistinctId" not in ctx
span.set_attribute.assert_not_called()