:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): ship pipeline logs into the Logs product (#71314)
Arno Hillen2c210875a318
diff --git a/posthog/otel_logs.py b/posthog/otel_logs.pynew file mode 100644index 000000000000..fd49df75dc36--- /dev/null+++ b/posthog/otel_logs.py@@ -0,0 +1,171 @@+"""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.+"""++import os+import logging+import threading+from typing import TYPE_CHECKING++from django.conf import settings++if TYPE_CHECKING:+ 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]" = {}+_providers_pid: int | None = None++_severity_by_levelno: "dict[int, tuple[str, SeverityNumber]] | None" = None+++def _ensure_provider(service_name: str) -> "LoggerProvider | None":+ global _providers, _providers_pid+ pid = os.getpid()+ with _lock:+ if _providers_pid != pid:+ _providers = {}+ _providers_pid = pid+ if service_name not in _providers:+ _providers[service_name] = _build_provider(service_name)+ return _providers[service_name]+++def _build_provider(service_name: str) -> "LoggerProvider | None":+ if not settings.OTLP_LOGS_INGEST_ENDPOINT or not settings.OTLP_LOGS_INGEST_TOKEN:+ return None++ # Deferred to keep the OTLP SDK off the django.setup() path.+ from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter # noqa: PLC0415+ from opentelemetry.sdk._logs import LoggerProvider # noqa: PLC0415+ from opentelemetry.sdk._logs.export import BatchLogRecordProcessor # noqa: PLC0415+ from opentelemetry.sdk.resources import Resource # noqa: PLC0415++ from posthog.security.outbound_proxy import internal_requests_session # noqa: PLC0415++ exporter = OTLPLogExporter(+ endpoint=settings.OTLP_LOGS_INGEST_ENDPOINT,+ headers={"authorization": f"Bearer {settings.OTLP_LOGS_INGEST_TOKEN}"},+ # Bypass the Smokescreen egress proxy (capture-logs is a private ClusterIP it 407s).+ session=internal_requests_session(),+ )+ provider = LoggerProvider(resource=Resource.create({"service.name": service_name}))+ provider.add_log_record_processor(BatchLogRecordProcessor(exporter))+ return provider+++def _severity(levelno: int) -> "tuple[str, SeverityNumber]":+ global _severity_by_levelno+ if _severity_by_levelno is None:+ from opentelemetry._logs import SeverityNumber # noqa: PLC0415++ _severity_by_levelno = {+ 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),+ }+ 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.+ """+ 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).+ try:+ provider = _ensure_provider(self._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(+ LogRecord(+ timestamp=timestamp,+ observed_timestamp=timestamp,+ severity_text=severity_text,+ severity_number=severity_number,+ body=body,+ attributes={**self._static_attributes, **extra},+ resource=self._resource,+ )+ )+ except Exception:+ pass+++def reset_otel_logs_for_tests() -> None:+ """Shut down and forget cached providers so a test can exercise gating with patched settings."""+ global _providers, _providers_pid, _severity_by_levelno+ with _lock:+ for provider in _providers.values():+ if provider is not None:+ provider.shutdown()+ _providers = {}+ _providers_pid = None+ _severity_by_levelno = Nonediff --git a/posthog/settings/ingestion.py b/posthog/settings/ingestion.pyindex ffff3fb7f2dc..0a389058c0a8 100644--- a/posthog/settings/ingestion.py+++ b/posthog/settings/ingestion.py@@ -60,6 +60,10 @@ CAPTURE_REPLAY_INTERNAL_URL = os.getenv("CAPTURE_REPLAY_INTERNAL_URL", "http://l# empty = emission disabled (the activity skips/raises rather than shipping to the wrong place); set# per-region via charts in prod, and to the local capture proxy when testing locally.OTLP_LOGS_INGEST_ENDPOINT = os.getenv("OTLP_LOGS_INGEST_ENDPOINT", "")+# Project token used as the OTLP Bearer for first-party log emission to a fixed internal project+# (dogfooding a product's own backend logs), not a per-team token. Pairs with+# OTLP_LOGS_INGEST_ENDPOINT. Both empty means emission is disabled. Mirrors OTEL_METRICS_EXPORT_TOKEN.+OTLP_LOGS_INGEST_TOKEN = os.getenv("OTLP_LOGS_INGEST_TOKEN", "")# Internal OTLP/HTTP endpoint for first-party metric emission into the Metrics product (the# `capture-logs` service, path `/i/v1/metrics`), with a project token as the OTLP Bearer.diff --git a/posthog/test/test_otel_logs.py b/posthog/test/test_otel_logs.pynew file mode 100644index 000000000000..1b3bcac7e552--- /dev/null+++ b/posthog/test/test_otel_logs.py@@ -0,0 +1,180 @@+import sys+import logging+from typing import Any++from unittest import mock++from django.test import SimpleTestCase, override_settings++from opentelemetry._logs import SeverityNumber+from opentelemetry.sdk._logs import LoggerProvider+from opentelemetry.sdk._logs.export import InMemoryLogExporter, SimpleLogRecordProcessor+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+ )+++class TestOtelLogs(SimpleTestCase):+ def setUp(self) -> None:+ reset_otel_logs_for_tests()+ self.addCleanup(reset_otel_logs_for_tests)++ def _emit(+ self,+ record: logging.LogRecord,+ *,+ 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)+ 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"},+ )+ 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 record.resource.attributes["service.name"] == "replay-vision"++ @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),+ ]+ )+ 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_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"},+ )+ assert records[0].body == "invalid_response"+ assert records[0].attributes["observation_id"] == "obs_1"+ assert "response_preview" 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"})+ 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.+ provider = mock.MagicMock()+ provider.get_logger.side_effect = RuntimeError("exporter down")+ with mock.patch("posthog.otel_logs._build_provider", return_value=provider):+ OtelLogHandler("replay-vision").emit(_structlog_record({"event": "x"}))+ assert provider.get_logger.called++ 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.+ 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:+ provider = otel_logs._build_provider("replay-vision")+ assert mock_otlp.call_args.kwargs["endpoint"] == endpoint+ assert mock_otlp.call_args.kwargs["headers"] == {"authorization": "Bearer phc_x"}+ assert mock_otlp.call_args.kwargs["session"].trust_env is False+ if provider is not None:+ provider.shutdown()diff --git a/products/replay_vision/backend/temporal/__init__.py b/products/replay_vision/backend/temporal/__init__.pyindex 1965c50bb463..658fc0104731 100644--- a/products/replay_vision/backend/temporal/__init__.py+++ b/products/replay_vision/backend/temporal/__init__.py@@ -38,6 +38,7 @@ 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_bridgefrom products.replay_vision.backend.temporal.reconciler import ReconcileScannerSchedulesWorkflowfrom products.replay_vision.backend.temporal.sweep_workflow import SweepScannerWorkflowfrom products.replay_vision.backend.temporal.vision_actions import (@@ -52,6 +53,10 @@ 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.pynew file mode 100644index 000000000000..4983bec55102--- /dev/null+++ b/products/replay_vision/backend/temporal/logs.py@@ -0,0 +1,54 @@+"""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.+"""++import logging++from posthog.otel_logs import OtelLogHandler++VISION_LOGS_SERVICE_NAME = "replay-vision"++# Every Replay Vision Temporal logger falls under this namespace, so a handler here catches them all.+_TEMPORAL_LOGGER_NAME = "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.+VISION_LOG_ATTRIBUTE_ALLOWLIST = frozenset(+ {+ "observation_id",+ "scanner_id",+ "scanner_type",+ "vision_action_id",+ "schedule_id",+ "team_id",+ "session_id",+ "workflow_id",+ "gemini_file_name",+ "redis_key",+ "status",+ "kind",+ "attempt",+ "step",+ "count",+ "duration_ms",+ "model",+ "skipped_temporal_error",+ }+)++_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 = Truediff --git a/products/replay_vision/backend/tests/test_logs_bridge.py b/products/replay_vision/backend/tests/test_logs_bridge.pynew file mode 100644index 000000000000..7f9988fcd3e3--- /dev/null+++ b/products/replay_vision/backend/tests/test_logs_bridge.py@@ -0,0 +1,62 @@+import logging++from unittest import mock++from django.test import SimpleTestCase++from opentelemetry.sdk._logs import LoggerProvider+from opentelemetry.sdk._logs.export import InMemoryLogExporter, SimpleLogRecordProcessor+from opentelemetry.sdk.resources import Resource++from posthog.otel_logs import OtelLogHandler, reset_otel_logs_for_tests++from products.replay_vision.backend.temporal import logs as bridge+++class TestVisionLogBridge(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+ 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)++ 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 = [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)