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(replay-vision): ship pipeline logs to Logs via a structlog mirror (#72030)

Arno Hillene8fa3943d1e4
diff --git a/posthog/management/commands/start_temporal_worker.py b/posthog/management/commands/start_temporal_worker.py
index 043e45c261c9..d573014763cc 100644
--- a/posthog/management/commands/start_temporal_worker.py
+++ b/posthog/management/commands/start_temporal_worker.py
@@ -220,6 +220,7 @@ from products.replay_vision.backend.temporal import (
ACTIVITIES as REPLAY_VISION_ACTIVITIES,
WORKFLOWS as REPLAY_VISION_WORKFLOWS,
)
+from products.replay_vision.backend.temporal.logs import build_vision_log_mirror
from products.review_hog.backend.temporal import (
ACTIVITIES as REVIEW_HOG_ACTIVITIES,
WORKFLOWS as REVIEW_HOG_WORKFLOWS,
@@ -706,7 +707,8 @@ class Command(BaseCommand):
with asyncio.Runner() as runner:
loop = runner.get_loop()
- configure_logger(loop=loop)
+ otel_log_mirror = build_vision_log_mirror() if task_queue == settings.REPLAY_VISION_TASK_QUEUE else None
+ configure_logger(loop=loop, otel_log_mirror=otel_log_mirror)
logger = LOGGER.bind(
host=temporal_host,
diff --git a/posthog/otel_logs.py b/posthog/otel_logs.py
index fd49df75dc36..58125077ef1d 100644
--- a/posthog/otel_logs.py
+++ b/posthog/otel_logs.py
@@ -1,12 +1,14 @@
"""OTLP log push into the PostHog Logs product (the logs counterpart of `posthog/otel_metrics.py`).
-Attach `OtelLogHandler` to a stdlib logger (a product's namespace) to mirror its records into Logs
-without touching any call sites. A no-op unless OTLP_LOGS_INGEST_ENDPOINT and OTLP_LOGS_INGEST_TOKEN
-are set. Providers are lazy and per-process (fork-safe) and keyed by service name, which becomes the
-`service.name` the Logs read side filters on.
+`otel_log_mirror_processor(...)` is a structlog processor, not a stdlib `logging.Handler`: the Temporal
+workers log through a non-stdlib structlog factory that a stdlib handler never sees. A no-op unless
+OTLP_LOGS_INGEST_ENDPOINT and OTLP_LOGS_INGEST_TOKEN are set. Providers are lazy, per-process
+(fork-safe), and keyed by service name, which becomes the `service.name` the Logs read side filters on.
"""
import os
+import sys
+import time
import logging
import threading
from typing import TYPE_CHECKING
@@ -14,9 +16,9 @@ from typing import TYPE_CHECKING
from django.conf import settings
if TYPE_CHECKING:
+ import structlog
from opentelemetry._logs import SeverityNumber
from opentelemetry.sdk._logs import LoggerProvider
- from opentelemetry.sdk.resources import Resource
_lock = threading.Lock()
_providers: "dict[str, LoggerProvider | None]" = {}
@@ -24,6 +26,17 @@ _providers_pid: int | None = None
_severity_by_levelno: "dict[int, tuple[str, SeverityNumber]] | None" = None
+_LEVELNO_BY_LEVEL_NAME = {
+ "debug": logging.DEBUG,
+ "info": logging.INFO,
+ "warning": logging.WARNING,
+ "warn": logging.WARNING,
+ "error": logging.ERROR,
+ "exception": logging.ERROR,
+ "critical": logging.CRITICAL,
+ "fatal": logging.CRITICAL,
+}
+
def _ensure_provider(service_name: str) -> "LoggerProvider | None":
global _providers, _providers_pid
@@ -75,88 +88,107 @@ def _severity(levelno: int) -> "tuple[str, SeverityNumber]":
return _severity_by_levelno.get(levelno, _severity_by_levelno[logging.INFO])
-def _body_and_attributes(record: logging.LogRecord, allowlist: frozenset[str] | None) -> tuple[str, dict[str, str]]:
- """Message and stringified, scalar-only attributes for one record (the queryable map is string-only).
-
- structlog leaves the event dict on `record.msg` (message under `event`). With `allowlist` set the
- handler is fail-closed: only those keys ship and an exception contributes just its type, so
- payload-derived fields (previews, prompts, tracebacks) stay in the process. None forwards everything.
+def _scalar_attributes(event_dict: "structlog.types.EventDict", allowlist: frozenset[str]) -> dict[str, str]:
+ """Logger name plus stringified allowlisted scalars. Fail-closed: non-allowlisted keys never ship."""
+ attributes: dict[str, str] = {}
+ name = event_dict.get("logger")
+ if name:
+ attributes["logger"] = str(name)
+ for key, value in event_dict.items():
+ if key in ("event", "logger", "exc_info") or key not in allowlist:
+ continue
+ if isinstance(value, str | int | float | bool):
+ attributes[key] = str(value)
+ return attributes
+
+
+def _exception_type(event_dict: "structlog.types.EventDict") -> dict[str, str]:
+ """Only the exception's type name. The message and traceback can embed payload data."""
+ exc_info = event_dict.get("exc_info")
+ if not exc_info:
+ return {}
+ if exc_info is True:
+ exc_info = sys.exc_info()
+ if isinstance(exc_info, BaseException):
+ return {"exception_type": type(exc_info).__name__}
+ if isinstance(exc_info, tuple) and exc_info and exc_info[0] is not None:
+ return {"exception_type": exc_info[0].__name__}
+ return {}
+
+
+def _passthrough(
+ logger: "structlog.types.WrappedLogger", method_name: str, event_dict: "structlog.types.EventDict"
+) -> "structlog.types.EventDict":
+ return event_dict
+
+
+def otel_log_mirror_processor(
+ service_name: str,
+ *,
+ logger_prefix: str,
+ attribute_allowlist: "set[str] | frozenset[str]",
+) -> "structlog.types.Processor":
+ """Structlog processor that mirrors records under `logger_prefix` into Logs over OTLP as
+ `service.name`. Fail-soft, a no-op until OTLP_LOGS_INGEST_* are set, always fail-closed (only
+ `attribute_allowlist` keys ship). Insert before the terminal renderer, message still under `event`.
"""
- attributes: dict[str, str] = {"logger": record.name}
- msg = record.msg
- if isinstance(msg, dict):
- body = str(msg.get("event", ""))
- for key, value in msg.items():
- if key == "event" or (allowlist is not None and key not in allowlist):
- continue
- if isinstance(value, str | int | float | bool):
- attributes[key] = str(value)
- else:
- body = record.getMessage()
- if record.exc_info and record.exc_info[0] is not None:
- if allowlist is None:
- attributes["exception"] = logging.Formatter().formatException(record.exc_info)
- else:
- # The type is operational. The message and traceback can embed payload data.
- attributes["exception_type"] = record.exc_info[0].__name__
- return body, attributes
-
-
-class OtelLogHandler(logging.Handler):
- """A logging handler that mirrors each record into the PostHog Logs product over OTLP.
-
- Fail-soft and a no-op until OTLP_LOGS_INGEST_* are configured, so it is safe to attach
- unconditionally. `service_name` becomes the record's `service.name` resource, and
- `static_attributes` ride every record. Pass `attribute_allowlist` to run fail-closed (only those
- keys ship, and exceptions contribute just their type). Omit it to forward every scalar field.
- """
-
- def __init__(
- self,
- service_name: str,
- *,
- attribute_allowlist: set[str] | frozenset[str] | None = None,
- static_attributes: dict[str, str] | None = None,
- level: int = logging.INFO,
- ) -> None:
- super().__init__(level=level)
- self._service_name = service_name
- self._attribute_allowlist = frozenset(attribute_allowlist) if attribute_allowlist is not None else None
- self._static_attributes = {key: str(value) for key, value in (static_attributes or {}).items()}
- self._resource: Resource | None = None
-
- def emit(self, record: logging.LogRecord) -> None:
- # Fail-soft: never let telemetry break the pipeline, and never log here (it would recurse
- # back through this handler).
+ allowlist = frozenset(attribute_allowlist)
+ try:
+ # Warm the provider at startup so the exporter's thread isn't spawned inside the workflow
+ # sandbox, and resolve SDK types + the pinned resource once, off the per-log path. Without a
+ # pinned resource the record would default to the pod's OTEL_SERVICE_NAME and the Logs
+ # service.name filter would miss it.
+ _ensure_provider(service_name)
+
+ from opentelemetry.sdk._logs import LogRecord # noqa: PLC0415
+ from opentelemetry.sdk.resources import Resource # noqa: PLC0415
+ from opentelemetry.trace import TraceFlags # noqa: PLC0415
+
+ resource = Resource.create({"service.name": service_name})
+ trace_flags = TraceFlags(TraceFlags.DEFAULT)
+ except Exception:
+ # Telemetry setup must never break worker startup; degrade to a no-op.
+ return _passthrough
+
+ def mirror(
+ logger: "structlog.types.WrappedLogger",
+ method_name: str,
+ event_dict: "structlog.types.EventDict",
+ ) -> "structlog.types.EventDict":
+ # Fail-soft: telemetry must never break the pipeline, and never log here (it would recurse).
try:
- provider = _ensure_provider(self._service_name)
+ name = event_dict.get("logger") or getattr(logger, "name", "") or ""
+ if not name.startswith(logger_prefix):
+ return event_dict
+ provider = _ensure_provider(service_name)
if provider is None:
- return
-
- from opentelemetry.sdk._logs import LogRecord # noqa: PLC0415
- from opentelemetry.sdk.resources import Resource # noqa: PLC0415
-
- if self._resource is None:
- self._resource = Resource.create({"service.name": self._service_name})
-
- body, extra = _body_and_attributes(record, self._attribute_allowlist)
- severity_text, severity_number = _severity(record.levelno)
- timestamp = int(record.created * 1_000_000_000)
- # Pin the resource: a record built without it defaults to the pod's OTEL_SERVICE_NAME, so
- # the Logs filter on service.name would miss these records.
- provider.get_logger(self._service_name, version="1").emit(
+ return event_dict
+
+ level_name = event_dict.get("level") or method_name
+ severity_text, severity_number = _severity(_LEVELNO_BY_LEVEL_NAME.get(level_name, logging.INFO))
+ attributes = _scalar_attributes(event_dict, allowlist)
+ attributes.update(_exception_type(event_dict))
+ timestamp = time.time_ns()
+ # Zero trace/span ids: the OTLP encoder serializes them as bytes and crashes on the default None.
+ provider.get_logger(service_name, version="1").emit(
LogRecord(
timestamp=timestamp,
observed_timestamp=timestamp,
+ trace_id=0,
+ span_id=0,
+ trace_flags=trace_flags,
severity_text=severity_text,
severity_number=severity_number,
- body=body,
- attributes={**self._static_attributes, **extra},
- resource=self._resource,
+ body=str(event_dict.get("event", "")),
+ attributes=attributes,
+ resource=resource,
)
)
except Exception:
pass
+ return event_dict
+
+ return mirror
def reset_otel_logs_for_tests() -> None:
diff --git a/posthog/temporal/common/logger.py b/posthog/temporal/common/logger.py
index a70e81e0cb90..2f877c561a97 100644
--- a/posthog/temporal/common/logger.py
+++ b/posthog/temporal/common/logger.py
@@ -493,6 +493,7 @@ def configure_logger(
loop: asyncio.AbstractEventLoop | None = None,
file: typing.TextIO | None = None,
raise_on_producer_error: bool = False,
+ otel_log_mirror: structlog.types.Processor | None = None,
) -> None:
"""Configure a structlog for Temporal workflows.
@@ -522,6 +523,8 @@ def configure_logger(
raise_on_producer_error: Raise any producer startup errors when `True`,
otherwise only log them. Set to `False` as in production environments, we
prefer only logging as most products can survive without logs.
+ otel_log_mirror: Optionally, a processor inserted before the renderer to mirror
+ records to the Logs product over OTLP.
"""
base_processors: list[structlog.types.Processor] = [
structlog.stdlib.add_log_level,
@@ -540,6 +543,10 @@ def configure_logger(
),
]
+ # Before the renderers, so the mirror sees the structured event dict (message still under `event`).
+ if otel_log_mirror is not None:
+ base_processors.append(otel_log_mirror)
+
log_queue = queue if queue is not None else asyncio.Queue(maxsize=0)
log_producer = None
log_producer_error = None
diff --git a/posthog/test/test_otel_logs.py b/posthog/test/test_otel_logs.py
index 1b3bcac7e552..792a24b91048 100644
--- a/posthog/test/test_otel_logs.py
+++ b/posthog/test/test_otel_logs.py
@@ -1,5 +1,4 @@
import sys
-import logging
from typing import Any
from unittest import mock
@@ -13,162 +12,119 @@ from opentelemetry.sdk.resources import Resource
from parameterized import parameterized
from posthog import otel_logs
-from posthog.otel_logs import OtelLogHandler, reset_otel_logs_for_tests
-
-
-def _structlog_record(
- event_dict: dict[str, Any],
- *,
- level: int = logging.INFO,
- name: str = "products.replay_vision.backend.temporal.activities.call_scanner_provider",
- exc_info: Any = None,
-) -> logging.LogRecord:
- # structlog's ProcessorFormatter path leaves the event dict on record.msg.
- return logging.LogRecord(
- name=name, level=level, pathname=__file__, lineno=1, msg=event_dict, args=(), exc_info=exc_info
- )
+from posthog.otel_logs import otel_log_mirror_processor, reset_otel_logs_for_tests
+
+_PREFIX = "products.replay_vision.backend.temporal"
+_ALLOWLIST = frozenset({"observation_id", "team_id"})
-class TestOtelLogs(SimpleTestCase):
+class TestOtelLogMirror(SimpleTestCase):
def setUp(self) -> None:
reset_otel_logs_for_tests()
self.addCleanup(reset_otel_logs_for_tests)
- def _emit(
+ def _run(
self,
- record: logging.LogRecord,
+ event_dict: dict[str, Any],
*,
+ method_name: str = "info",
+ allowlist: set[str] | frozenset[str] = _ALLOWLIST,
service_name: str = "replay-vision",
- static_attributes: dict[str, str] | None = None,
- attribute_allowlist: set[str] | None = None,
) -> list[Any]:
exporter = InMemoryLogExporter()
provider = LoggerProvider(resource=Resource.create({"service.name": service_name}))
provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))
with mock.patch("posthog.otel_logs._build_provider", return_value=provider):
- OtelLogHandler(
- service_name, attribute_allowlist=attribute_allowlist, static_attributes=static_attributes
- ).emit(record)
+ mirror = otel_log_mirror_processor(service_name, logger_prefix=_PREFIX, attribute_allowlist=allowlist)
+ mirror(None, method_name, dict(event_dict))
return [item.log_record for item in exporter.get_finished_logs()]
- @parameterized.expand(
- [("both_empty", "", ""), ("endpoint_only", "http://c/i/v1/logs", ""), ("token_only", "", "phc_x")]
- )
- def test_noop_when_unconfigured(self, _name: str, endpoint: str, token: str) -> None:
- # A half- or un-configured lane must never build a provider (an unauthenticated export would
- # 401 and drop records) and emit must not crash the worker.
- with override_settings(OTLP_LOGS_INGEST_ENDPOINT=endpoint, OTLP_LOGS_INGEST_TOKEN=token):
- OtelLogHandler("replay-vision").emit(_structlog_record({"event": "hello"}))
- assert otel_logs._providers.get("replay-vision") is None
-
- def test_maps_event_dict_to_body_and_stringified_attributes(self) -> None:
- # The core contract: `event` becomes the body, scalar fields become stringified attributes, the
- # logger name rides along, and the resource is pinned to the service (not the pod's
- # OTEL_SERVICE_NAME, which the service.name read filter would otherwise miss).
- with mock.patch.dict("os.environ", {"OTEL_SERVICE_NAME": "temporal-worker-general-purpose"}):
- records = self._emit(
- _structlog_record(
- {"event": "scanner_call_failed", "observation_id": "obs_1", "team_id": 42, "attempt": 2}
- ),
- static_attributes={"region": "us"},
- )
+ def test_mirrors_event_and_allowlisted_attributes(self) -> None:
+ records = self._run(
+ {
+ "event": "scanner_call_failed",
+ "logger": f"{_PREFIX}.activities.call_scanner_provider",
+ "observation_id": "obs_1",
+ "team_id": 42,
+ "response_preview": "customer session text",
+ }
+ )
assert len(records) == 1
record = records[0]
assert record.body == "scanner_call_failed"
assert record.attributes["observation_id"] == "obs_1"
assert record.attributes["team_id"] == "42"
- assert record.attributes["attempt"] == "2"
- assert record.attributes["region"] == "us"
- assert record.attributes["logger"] == "products.replay_vision.backend.temporal.activities.call_scanner_provider"
+ assert "response_preview" not in record.attributes
+ assert record.attributes["logger"] == f"{_PREFIX}.activities.call_scanner_provider"
assert record.resource.attributes["service.name"] == "replay-vision"
+ def test_ignores_loggers_outside_the_prefix(self) -> None:
+ records = self._run({"event": "shutting down", "logger": "temporalio.worker"})
+ assert records == []
+
@parameterized.expand(
[
- (logging.DEBUG, "DEBUG", SeverityNumber.DEBUG),
- (logging.INFO, "INFO", SeverityNumber.INFO),
- (logging.WARNING, "WARN", SeverityNumber.WARN),
- (logging.ERROR, "ERROR", SeverityNumber.ERROR),
- (logging.CRITICAL, "FATAL", SeverityNumber.FATAL),
+ ("debug", SeverityNumber.DEBUG, "DEBUG"),
+ ("info", SeverityNumber.INFO, "INFO"),
+ ("warning", SeverityNumber.WARN, "WARN"),
+ ("error", SeverityNumber.ERROR, "ERROR"),
+ ("critical", SeverityNumber.FATAL, "FATAL"),
]
)
- def test_severity_mapping(self, levelno: int, expected_text: str, expected_number: SeverityNumber) -> None:
- # The Logs UI filters and sorts on severity. A broken level map degrades triage silently.
- records = self._emit(_structlog_record({"event": "x"}, level=levelno))
- assert records[0].severity_text == expected_text
- assert records[0].severity_number == expected_number
+ def test_severity_mapping(self, level_name: str, number: SeverityNumber, text: str) -> None:
+ records = self._run({"event": "x", "logger": f"{_PREFIX}.x", "level": level_name}, method_name=level_name)
+ assert records[0].severity_text == text
+ assert records[0].severity_number == number
def test_drops_non_scalar_attributes(self) -> None:
- # OTEL attributes accept scalars only. A Mapping/list value must be dropped, not crash or
- # serialize garbage, while scalar attributes survive.
- records = self._emit(_structlog_record({"event": "x", "count": 1, "nested": {"a": 1}, "items": [1, 2]}))
- assert records[0].attributes["count"] == "1"
- assert "nested" not in records[0].attributes
- assert "items" not in records[0].attributes
-
- def test_plain_stdlib_message_becomes_body(self) -> None:
- # A third-party library logging under the namespace passes a format string, not an event dict.
- # It must render into a real body rather than str(dict) garbage.
- record = logging.LogRecord(
- name="products.replay_vision.backend.temporal.x",
- level=logging.INFO,
- pathname=__file__,
- lineno=1,
- msg="uploaded %s bytes",
- args=(1024,),
- exc_info=None,
- )
- records = self._emit(record)
- assert records[0].body == "uploaded 1024 bytes"
-
- def test_exception_info_is_attached(self) -> None:
- # Shipping the pipeline's logs is worthless for debugging if stack traces are dropped.
- try:
- raise ValueError("boom")
- except ValueError:
- record = _structlog_record({"event": "scan_failed"}, level=logging.ERROR, exc_info=sys.exc_info())
- records = self._emit(record)
- assert "ValueError: boom" in records[0].attributes["exception"]
-
- def test_attribute_allowlist_drops_payload_derived_fields(self) -> None:
- # Fail-closed: shipping to a shared project forwards only allowlisted operational fields. A
- # content field like response_preview (model output derived from customer sessions) must never
- # leave the process. Guards the cross-tenant content-exposure fix.
- records = self._emit(
- _structlog_record(
- {"event": "invalid_response", "observation_id": "obs_1", "response_preview": "customer session text"}
- ),
- attribute_allowlist={"observation_id"},
+ # OTEL attributes are scalars only; an allowlisted key with a Mapping/list value is dropped.
+ records = self._run(
+ {"event": "x", "logger": f"{_PREFIX}.x", "team_id": {"nested": 1}, "observation_id": "obs_1"}
)
- assert records[0].body == "invalid_response"
assert records[0].attributes["observation_id"] == "obs_1"
- assert "response_preview" not in records[0].attributes
+ assert "team_id" not in records[0].attributes
def test_restricted_mode_ships_exception_type_not_traceback(self) -> None:
- # With an allowlist the exception contributes only its class name, not the message or
- # traceback, which can embed customer data.
try:
raise ValueError("customer data in message")
except ValueError:
- record = _structlog_record({"event": "scan_failed"}, level=logging.ERROR, exc_info=sys.exc_info())
- records = self._emit(record, attribute_allowlist={"observation_id"})
+ exc_info = sys.exc_info()
+ records = self._run(
+ {"event": "scan_failed", "logger": f"{_PREFIX}.x", "exc_info": exc_info}, method_name="error"
+ )
assert records[0].attributes["exception_type"] == "ValueError"
assert "exception" not in records[0].attributes
assert all("customer data" not in str(value) for value in records[0].attributes.values())
- def test_emit_is_fail_soft(self) -> None:
- # A telemetry throw must never propagate out of emit, which would crash the activity it rode in on.
+ def test_mirror_is_fail_soft(self) -> None:
provider = mock.MagicMock()
provider.get_logger.side_effect = RuntimeError("exporter down")
+ event_dict = {"event": "x", "logger": f"{_PREFIX}.x"}
with mock.patch("posthog.otel_logs._build_provider", return_value=provider):
- OtelLogHandler("replay-vision").emit(_structlog_record({"event": "x"}))
+ mirror = otel_log_mirror_processor("replay-vision", logger_prefix=_PREFIX, attribute_allowlist=_ALLOWLIST)
+ result = mirror(None, "info", event_dict)
assert provider.get_logger.called
+ assert result == event_dict
+
+ def test_factory_is_fail_soft_when_provider_build_fails(self) -> None:
+ # Provider construction failing at warm-up must not break worker startup: the factory returns a
+ # no-op processor instead of propagating out of configure_logger.
+ event_dict = {"event": "x", "logger": f"{_PREFIX}.x"}
+ with mock.patch("posthog.otel_logs._build_provider", side_effect=RuntimeError("boom")):
+ mirror = otel_log_mirror_processor("replay-vision", logger_prefix=_PREFIX, attribute_allowlist=_ALLOWLIST)
+ assert mirror(None, "info", dict(event_dict)) == event_dict
+
+ @parameterized.expand(
+ [("both_empty", "", ""), ("endpoint_only", "http://c/i/v1/logs", ""), ("token_only", "", "phc_x")]
+ )
+ def test_noop_when_unconfigured(self, _name: str, endpoint: str, token: str) -> None:
+ with override_settings(OTLP_LOGS_INGEST_ENDPOINT=endpoint, OTLP_LOGS_INGEST_TOKEN=token):
+ mirror = otel_log_mirror_processor("replay-vision", logger_prefix=_PREFIX, attribute_allowlist=_ALLOWLIST)
+ mirror(None, "info", {"event": "x", "logger": f"{_PREFIX}.x"})
+ assert otel_logs._providers.get("replay-vision") is None
def test_production_exporter_bypasses_egress_proxy(self) -> None:
- # The endpoint+token path builds the real OTLP exporter, whose requests.Session must have
- # trust_env=False: capture-logs is an in-cluster private ClusterIP and the worker's
- # HTTP_PROXY Smokescreen egress proxy denies private-range hosts (407), silently dropping every
- # batch. This branch is otherwise untested (the rest inject providers), which is how the same
- # 407 shipped unnoticed on the metrics/CI-logs lanes.
+ # trust_env=False, else the worker's Smokescreen proxy 407s the in-cluster ClusterIP.
endpoint = "http://capture-logs.posthog.svc.cluster.local:4318/i/v1/logs"
with override_settings(OTLP_LOGS_INGEST_ENDPOINT=endpoint, OTLP_LOGS_INGEST_TOKEN="phc_x"):
with mock.patch("opentelemetry.exporter.otlp.proto.http._log_exporter.OTLPLogExporter") as mock_otlp:
diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.py
index 658fc0104731..1965c50bb463 100644
--- a/products/replay_vision/backend/temporal/__init__.py
+++ b/products/replay_vision/backend/temporal/__init__.py
@@ -38,7 +38,6 @@ from products.replay_vision.backend.temporal.gemini_cleanup_sweep import (
ReplayVisionGeminiCleanupSweepWorkflow,
sweep_gemini_files_activity,
)
-from products.replay_vision.backend.temporal.logs import install_vision_log_bridge
from products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflow
from products.replay_vision.backend.temporal.sweep_workflow import SweepScannerWorkflow
from products.replay_vision.backend.temporal.vision_actions import (
@@ -53,10 +52,6 @@ from products.replay_vision.backend.temporal.vision_actions import (
)
from products.replay_vision.backend.temporal.workflow import ApplyScannerWorkflow
-# Ship this package's pipeline logs into the PostHog Logs product wherever the worker imports it.
-# A no-op until OTLP_LOGS_INGEST_* are configured.
-install_vision_log_bridge()
-
WORKFLOWS = [
ApplyScannerWorkflow,
EvaluatePromptSuggestionWorkflow,
diff --git a/products/replay_vision/backend/temporal/logs.py b/products/replay_vision/backend/temporal/logs.py
index 4983bec55102..7eab02915cd9 100644
--- a/products/replay_vision/backend/temporal/logs.py
+++ b/products/replay_vision/backend/temporal/logs.py
@@ -1,22 +1,21 @@
"""Mirror the Replay Vision Temporal pipeline's logs into the PostHog Logs product (dogfooding).
-Attaching an `OtelLogHandler` to the `products.replay_vision.backend.temporal` namespace ships those
-records into Logs under `service.name = replay-vision` with no new call sites. A no-op until
-OTLP_LOGS_INGEST_* are configured, so it is safe to install at worker import.
+`build_vision_log_mirror()` returns the structlog processor the worker start command inserts into the
+log chain for the Replay Vision task queue. A no-op until OTLP_LOGS_INGEST_* are configured.
"""
-import logging
+from typing import TYPE_CHECKING
-from posthog.otel_logs import OtelLogHandler
+from posthog.otel_logs import otel_log_mirror_processor
-VISION_LOGS_SERVICE_NAME = "replay-vision"
+if TYPE_CHECKING:
+ import structlog
-# Every Replay Vision Temporal logger falls under this namespace, so a handler here catches them all.
-_TEMPORAL_LOGGER_NAME = "products.replay_vision.backend.temporal"
+VISION_LOGS_SERVICE_NAME = "replay-vision"
+VISION_LOGS_LOGGER_PREFIX = "products.replay_vision.backend.temporal"
-# Fail-closed allowlist: only these operational fields ship to the shared Logs project. Anything else
-# (previews, prompts, exception messages, payload-derived values) is dropped so no team's
-# session-derived content crosses in.
+# Fail-closed: only these operational fields ship. Payload-derived values (previews, prompts,
+# exception messages) are dropped so no team's session content crosses into the shared project.
VISION_LOG_ATTRIBUTE_ALLOWLIST = frozenset(
{
"observation_id",
@@ -40,15 +39,10 @@ VISION_LOG_ATTRIBUTE_ALLOWLIST = frozenset(
}
)
-_installed = False
-
-def install_vision_log_bridge() -> None:
- """Attach the OTLP log handler to the Replay Vision Temporal logger. Idempotent and cheap."""
- global _installed
- if _installed:
- return
- logger = logging.getLogger(_TEMPORAL_LOGGER_NAME)
- if not any(isinstance(handler, OtelLogHandler) for handler in logger.handlers):
- logger.addHandler(OtelLogHandler(VISION_LOGS_SERVICE_NAME, attribute_allowlist=VISION_LOG_ATTRIBUTE_ALLOWLIST))
- _installed = True
+def build_vision_log_mirror() -> "structlog.types.Processor":
+ return otel_log_mirror_processor(
+ VISION_LOGS_SERVICE_NAME,
+ logger_prefix=VISION_LOGS_LOGGER_PREFIX,
+ attribute_allowlist=VISION_LOG_ATTRIBUTE_ALLOWLIST,
+ )
diff --git a/products/replay_vision/backend/temporal/state.py b/products/replay_vision/backend/temporal/state.py
index 03ec433c53a8..9ad2e0c754d1 100644
--- a/products/replay_vision/backend/temporal/state.py
+++ b/products/replay_vision/backend/temporal/state.py
@@ -66,9 +66,10 @@ async def get_data_str_from_redis(redis_client: aioredis.Redis, redis_key: str)
try:
return decompress(raw)
except Exception as err:
- msg = f"Failed to decompress Redis payload at {redis_key}: {err}"
- logger.exception(msg, redis_key=redis_key)
- raise ValueError(msg) from err
+ # Keep the log event a fixed identifier: the exception detail can embed payload-derived text,
+ # so it rides the raised error (Temporal-internal), not the log body mirrored to Logs.
+ logger.exception("replay_vision.redis_payload_decompress_failed", redis_key=redis_key)
+ raise ValueError(f"Failed to decompress Redis payload at {redis_key}: {err}") from err
async def get_data_class_from_redis(
@@ -83,9 +84,13 @@ async def get_data_class_from_redis(
return target_class.model_validate_json(data_str)
except ValidationError as err:
# Stale-schema payloads will never parse — fail-fast instead of retrying for the full Redis TTL.
- msg = f"Failed to parse Redis payload at {redis_key} into {target_class.__name__}: {err}"
- logger.exception(msg, redis_key=redis_key)
- raise ApplicationError(msg, non_retryable=True) from err
+ # Fixed log event: the ValidationError text embeds the offending input_value, so it rides the
+ # raised error (Temporal-internal), not the log body mirrored to Logs.
+ logger.exception("replay_vision.redis_payload_parse_failed", redis_key=redis_key)
+ raise ApplicationError(
+ f"Failed to parse Redis payload at {redis_key} into {target_class.__name__}: {err}",
+ non_retryable=True,
+ ) from err
async def load_scanner_llm_inputs(observation_id: str) -> ScannerLlmInputs | None:
diff --git a/products/replay_vision/backend/tests/test_logs_bridge.py b/products/replay_vision/backend/tests/test_logs_bridge.py
index 7f9988fcd3e3..7d2b35a6dadd 100644
--- a/products/replay_vision/backend/tests/test_logs_bridge.py
+++ b/products/replay_vision/backend/tests/test_logs_bridge.py
@@ -1,62 +1,72 @@
-import logging
+import io
from unittest import mock
-from django.test import SimpleTestCase
+from django.test import SimpleTestCase, override_settings
-from opentelemetry.sdk._logs import LoggerProvider
-from opentelemetry.sdk._logs.export import InMemoryLogExporter, SimpleLogRecordProcessor
-from opentelemetry.sdk.resources import Resource
+import structlog
+from opentelemetry.proto.collector.logs.v1.logs_service_pb2 import ExportLogsServiceRequest
-from posthog.otel_logs import OtelLogHandler, reset_otel_logs_for_tests
+from posthog import otel_logs
+from posthog.otel_logs import reset_otel_logs_for_tests
+from posthog.temporal.common.logger import configure_logger
-from products.replay_vision.backend.temporal import logs as bridge
+from products.replay_vision.backend.temporal.logs import (
+ VISION_LOG_ATTRIBUTE_ALLOWLIST,
+ VISION_LOGS_LOGGER_PREFIX,
+ VISION_LOGS_SERVICE_NAME,
+ build_vision_log_mirror,
+)
-class TestVisionLogBridge(SimpleTestCase):
+class TestVisionLogMirror(SimpleTestCase):
def setUp(self) -> None:
- self.logger = logging.getLogger(bridge._TEMPORAL_LOGGER_NAME)
- self._orig_handlers = list(self.logger.handlers)
- self._orig_installed = bridge._installed
- self._orig_level = self.logger.level
+ reset_otel_logs_for_tests()
+ self._structlog_config = structlog.get_config()
self.addCleanup(self._restore)
- # Clean slate: the package __init__ already installed the bridge at import time.
- self.logger.handlers = [handler for handler in self.logger.handlers if not isinstance(handler, OtelLogHandler)]
- bridge._installed = False
def _restore(self) -> None:
- self.logger.handlers = self._orig_handlers
- self.logger.setLevel(self._orig_level)
- bridge._installed = self._orig_installed
-
- def test_install_is_idempotent_and_attaches_one_handler(self) -> None:
- # Double-install would ship every record twice. A wrong service name would land the logs where
- # the Logs read filter (service.name = replay-vision) can't find them.
- bridge.install_vision_log_bridge()
- bridge.install_vision_log_bridge()
- handlers = [handler for handler in self.logger.handlers if isinstance(handler, OtelLogHandler)]
- assert len(handlers) == 1
- assert handlers[0]._service_name == bridge.VISION_LOGS_SERVICE_NAME
- # Fail-closed allowlist must be wired so payload-derived fields never reach the shared project.
- assert handlers[0]._attribute_allowlist == bridge.VISION_LOG_ATTRIBUTE_ALLOWLIST
- assert "response_preview" not in bridge.VISION_LOG_ATTRIBUTE_ALLOWLIST
-
- def test_pipeline_logs_reach_the_logs_product_under_the_service_name(self) -> None:
- # The load-bearing claim of the bridge: a record from any logger under the pipeline namespace
- # propagates to the handler and ships under service.name = replay-vision, with no call-site
- # change. A wrong namespace string would silently ship nothing.
- exporter = InMemoryLogExporter()
- provider = LoggerProvider(resource=Resource.create({"service.name": bridge.VISION_LOGS_SERVICE_NAME}))
- provider.add_log_record_processor(SimpleLogRecordProcessor(exporter))
reset_otel_logs_for_tests()
- self.addCleanup(reset_otel_logs_for_tests)
- self.logger.setLevel(logging.INFO)
+ # configure_logger calls structlog.reset_defaults(), so restore the process-wide config.
+ structlog.configure(**self._structlog_config)
+
+ @override_settings(
+ OTLP_LOGS_INGEST_ENDPOINT="http://capture-logs.posthog.svc.cluster.local:4318/i/v1/logs",
+ OTLP_LOGS_INGEST_TOKEN="phc_x",
+ TEMPORAL_LOG_LEVEL="DEBUG",
+ )
+ def test_pipeline_logs_serialize_and_export_through_the_real_worker_chain(self) -> None:
+ # Real configure_logger chain + real OTLPLogExporter (only the network session mocked), so it
+ # catches an unwired mirror and a record that fails to serialize (in-memory exporters don't).
+ mock_session = mock.MagicMock()
+ mock_session.post.return_value = mock.MagicMock(status_code=200)
+
+ with mock.patch("posthog.security.outbound_proxy.internal_requests_session", return_value=mock_session):
+ configure_logger(
+ otel_log_mirror=build_vision_log_mirror(), cache_logger_on_first_use=False, file=io.StringIO()
+ )
+ logger = structlog.get_logger(f"{VISION_LOGS_LOGGER_PREFIX}.activities.call_scanner_provider")
+ logger.info("scanner_call_failed", observation_id="obs_1", response_preview="customer session text")
+ provider = otel_logs._ensure_provider(VISION_LOGS_SERVICE_NAME)
+ assert provider is not None
+ provider.force_flush(5000)
+
+ assert mock_session.post.called, "real OTLP exporter never POSTed (serialization or transport failed)"
+ data = mock_session.post.call_args.kwargs.get("data") or mock_session.post.call_args.args[0]
+ request = ExportLogsServiceRequest.FromString(data)
- with mock.patch("posthog.otel_logs._build_provider", return_value=provider):
- bridge.install_vision_log_bridge()
- child = logging.getLogger(f"{bridge._TEMPORAL_LOGGER_NAME}.activities.call_scanner_provider")
- child.info("scanner_call_failed")
+ records = [record for rl in request.resource_logs for sl in rl.scope_logs for record in sl.log_records]
+ matched = [record for record in records if record.body.string_value == "scanner_call_failed"]
+ assert len(matched) == 1
+ record = matched[0]
+ service_name = next(
+ kv.value.string_value for kv in request.resource_logs[0].resource.attributes if kv.key == "service.name"
+ )
+ attributes = {kv.key: kv.value.string_value for kv in record.attributes}
+ assert service_name == VISION_LOGS_SERVICE_NAME
+ assert attributes["observation_id"] == "obs_1"
+ assert "response_preview" not in attributes
- records = [item.log_record for item in exporter.get_finished_logs()]
- assert any(record.body == "scanner_call_failed" for record in records)
- assert all(record.resource.attributes["service.name"] == bridge.VISION_LOGS_SERVICE_NAME for record in records)
+ def test_allowlist_excludes_payload_derived_fields(self) -> None:
+ assert "response_preview" not in VISION_LOG_ATTRIBUTE_ALLOWLIST
+ assert "observation_id" in VISION_LOG_ATTRIBUTE_ALLOWLIST