: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(hogbox-preview): send the preview's analytics, logs, traces and metrics to itself (#113181)
Frank Hamandca620b9dc47b
diff --git a/posthog/apps.py b/posthog/apps.pyindex 60e33ce666bf..39f4eb5e1b78 100644--- a/posthog/apps.py+++ b/posthog/apps.py@@ -100,7 +100,7 @@ class PostHogConfig(AppConfig):posthoganalytics.personal_api_key = Noneelif settings.TEST or os.environ.get("OPT_OUT_CAPTURE", False):posthoganalytics.disabled = True # ty: ignore[invalid-assignment]- elif settings.DEBUG:+ elif settings.DEBUG or settings.SELF_CAPTURE:# In dev, analytics is by default turned to self-capture, i.e. data going into this very instance of PostHog# Due to ASGI's workings, we can't query for the right project token in this `ready()` method# Instead, we configure self-capture with `self_capture_wrapper()` in posthog/asgi.py - see that filediff --git a/posthog/settings/base_variables.py b/posthog/settings/base_variables.pyindex 1dbe9dfb416a..99700badcc37 100644--- a/posthog/settings/base_variables.py+++ b/posthog/settings/base_variables.py@@ -49,6 +49,7 @@ Possible values:"""COMPACT_IN_REGION: str = get_from_env("COMPACT_IN_REGION", "US")SELF_CAPTURE: bool = get_from_env("SELF_CAPTURE", DEBUG and not DEMO, type_cast=str_to_bool)+SELF_CAPTURE_HOST: str = get_from_env("SELF_CAPTURE_HOST", "")E2E_TESTING: bool = get_from_env("E2E_TESTING", False, type_cast=str_to_bool) # whether the app is currently running for E2E testsdiff --git a/posthog/test/test_utils.py b/posthog/test/test_utils.pyindex f81aba1e013e..04d37a758894 100644--- a/posthog/test/test_utils.py+++ b/posthog/test/test_utils.py@@ -19,6 +19,8 @@ from django.test import SimpleTestCase, TestCase, override_settingsfrom django.test.client import RequestFactoryfrom django.utils.timezone import now+import posthoganalytics+from asgiref.sync import async_to_syncfrom parameterized import parameterizedfrom rest_framework.request import Request@@ -53,6 +55,7 @@ from posthog.utils import (get_js_url,get_self_capture_team_id,get_short_user_agent,+ initialize_self_capture_api_token,load_data_from_request,refresh_requested_by_client,relative_date_parse,@@ -1406,6 +1409,33 @@ class TestBuildFlagProvider(TestCase):assert _build_flag_provider()._resolve_team_id() == 5+class TestInitializeSelfCaptureHost(SimpleTestCase):+ def setUp(self):+ for name in ("disabled", "api_key", "host"):+ self.addCleanup(setattr, posthoganalytics, name, getattr(posthoganalytics, name))+ for target, value in (+ ("posthog.utils.resolve_self_capture_team", Team(api_token="phc_self_capture_test")),+ ("posthog.utils._build_flag_provider", None),+ ("posthoganalytics.feature_flag_definitions", {}),+ ):+ mocked = patch(target, return_value=value)+ mocked.start()+ self.addCleanup(mocked.stop)++ @parameterized.expand(+ [+ ("explicit host", "http://static-proxy:8000", "http://static-proxy:8000"),+ ("falls back to site url", "", "https://preview.example.com"),+ ]+ )+ def test_backend_sends_to_self_capture_host(self, _name, self_capture_host, expected_host):+ with override_settings(SELF_CAPTURE_HOST=self_capture_host, SITE_URL="https://preview.example.com"):+ async_to_sync(initialize_self_capture_api_token)()++ assert posthoganalytics.host == expected_host+ assert posthoganalytics.api_key == "phc_self_capture_test"++class TestSelfCaptureBrowserFlagToken(TestCase):PASSWORD = "testpassword12345"diff --git a/posthog/utils.py b/posthog/utils.pyindex 53787274ec3c..8ac9e2f37cd5 100644--- a/posthog/utils.py+++ b/posthog/utils.py@@ -974,7 +974,7 @@ async def initialize_self_capture_api_token():if local_api_key is not None:posthoganalytics.disabled = Falseposthoganalytics.api_key = local_api_key- posthoganalytics.host = settings.SITE_URL+ posthoganalytics.host = settings.SELF_CAPTURE_HOST or settings.SITE_URL# ready() wires the flag-definition provider only when posthoganalytics is enabled at# that point — true for WSGI but NOT for ASGI, where self-capture is deferred to here.diff --git a/tools/hogbox-preview/README.md b/tools/hogbox-preview/README.mdindex 5af5531f5b2e..7969909f5414 100644--- a/tools/hogbox-preview/README.md+++ b/tools/hogbox-preview/README.md@@ -54,6 +54,10 @@ print(url) # https://pen-….boxes.hogland.prod-us.posthog.dev/ (stable acrossA Caddy container (`static-proxy`) takes the exposed port.It serves `/static/*` from `staticfiles/` and sends all other requests to web, so asset requests do not use Django threads.A non-frontend PR copies `staticfiles/` out of the image. A file that is not there falls through to Django.+8. **Self-telemetry** - the preview sends its own data to its demo project, so its product pages show real data from the preview itself.+ Analytics: web runs with `SELF_CAPTURE=1`. posthog-js sends to the preview's own origin, the backend sends to `static-proxy`, and Caddy routes capture and flag paths to `capture` and `feature-flags`. `ingestion-general` writes the events to ClickHouse.+ Logs, traces and metrics: web, the temporal worker and the Node services export OTLP to `otel-collector`. The collector also reads every container's log file. It sends everything to `capture-logs` with the demo project's token, and `ingestion-logs`, `ingestion-traces` and `ingestion-metrics` write it to ClickHouse.+ The collector skips the telemetry pipeline's own containers, so their logs do not feed back into themselves.Driven entirely by the **`posthog-hogland` Python SDK** over hogplane's HTTP API— **keyless** (GitHub OIDC → hogplane token over the tailnet), no `hogland` CLIdiff --git a/tools/hogbox-preview/hogbox_preview/stack.py b/tools/hogbox-preview/hogbox_preview/stack.pyindex 820ddf2b37c3..9dd7f35c027a 100644--- a/tools/hogbox-preview/hogbox_preview/stack.py+++ b/tools/hogbox-preview/hogbox_preview/stack.py@@ -55,6 +55,18 @@ _CSRF_TRUSTED_ORIGINS = ",".join(f"https://*.boxes.hogland.{env}.posthog.dev" fo# the seed defaults ever change, change these too._STATIC_PROXY_CADDYFILE = """\:8000 {+ @capture path /e /e/* /i/v0 /i/v0/* /i/v1/analytics/events /batch /batch/* /capture /capture/*+ handle @capture {+ reverse_proxy capture:3000+ }+ @flags path /flags /flags/* /api/feature_flag/local_evaluation /api/feature_flag/local_evaluation/*+ handle @flags {+ reverse_proxy feature-flags:3001+ }+ @otlp path /i/v1/logs /i/v1/logs/* /i/v1/traces /i/v1/traces/* /i/v1/metrics /i/v1/metrics/*+ handle @otlp {+ reverse_proxy capture-logs:4318+ }@static {path /static/*file {@@ -73,6 +85,108 @@ _STATIC_PROXY_CADDYFILE = """\}}"""+_TELEMETRY_PIPELINE = ("otel-collector", "capture-logs", "ingestion-logs", "ingestion-traces", "ingestion-metrics")++_OTEL_COLLECTOR_CONFIG = """\+extensions:+ docker_observer:+ health_check:++receivers:+ receiver_creator:+ watch_observers: [docker_observer]+ receivers:+ filelog:+ rule: type == "container" and labels["com.docker.compose.project"] == "${{env:COMPOSE_PROJECT}}" and not (name matches "{pipeline}")+ config:+ include:+ - '`"/var/lib/docker/containers/" + container_id + "/*.log"`'+ operators:+ - type: regex_replace+ regex_name: ansi_control_sequences+ field: body+ - type: json_parser+ timestamp:+ parse_from: attributes.time+ layout: '%Y-%m-%dT%H:%M:%S.%LZ'+ on_error: drop+ - type: move+ from: attributes["log"]+ to: body+ - type: add+ field: resource["service.name"]+ value: '`labels["com.docker.compose.service"]`'+ - type: add+ field: resource["container.name"]+ value: '`name`'+ - type: json_parser+ parse_from: body+ on_error: send_quiet+ if: "hasPrefix(body, '{{')"+ otlp:+ protocols:+ grpc:+ endpoint: 0.0.0.0:4317+ http:+ endpoint: 0.0.0.0:4318+ prometheus:+ config:+ scrape_configs:+ - job_name: plugins+ scrape_interval: 15s+ metrics_path: /_metrics+ static_configs:+ - targets: ['plugins:6738']+ - job_name: ingestion-general+ scrape_interval: 15s+ metrics_path: /_metrics+ static_configs:+ - targets: ['ingestion-general:6738']++exporters:+ otlphttp:+ endpoint: http://capture-logs:4318+ compression: none+ tls:+ insecure: true+ headers:+ authorization: Bearer {token}+ retry_on_failure:+ max_elapsed_time: 30s++processors:+ memory_limiter:+ check_interval: 1s+ limit_mib: 512+ spike_limit_mib: 128+ batch:++service:+ pipelines:+ traces:+ receivers: [otlp]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]+ logs:+ receivers: [otlp, receiver_creator]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]+ metrics:+ receivers: [otlp, prometheus]+ processors: [memory_limiter, batch]+ exporters: [otlphttp]+ extensions: [docker_observer, health_check]+"""++_OTEL_ENV = [+ " - OTEL_SDK_DISABLED=false",+ " - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317",+ " - OTEL_TRACES_SAMPLER=parentbased_traceidratio",+ " - OTEL_TRACES_SAMPLER_ARG=1",+ " - OTEL_METRICS_EXPORT_URL=http://otel-collector:4318/v1/metrics",+ " - OTEL_METRICS_EXPORT_TOKEN=collector-adds-the-project-token",+]+_DEMO_EMAIL = "[email protected]"_DEMO_PASSWORD = "12345678"@@ -96,6 +210,10 @@ class PostHogPreviewStack:CDP_IMAGE = "ghcr.io/posthog/posthog-node:master"STATIC_PROXY_IMAGE = "caddy:2-alpine"STATIC_PROXY_CADDYFILE = "preview-static.Caddyfile"+ OTEL_COLLECTOR_CONFIG = "preview-otel-collector.yaml"+ COMPOSE_PROJECT = "posthog"+ SELF_CAPTURE_SERVICES = ["capture", "feature-flags", "property-defs-rs", "ingestion-general"]+ TELEMETRY_SERVICES = ["capture-logs", "ingestion-logs", "ingestion-traces", "ingestion-metrics", "otel-collector"]REPO_DIR = "/home/hog/posthog"COMPOSE = "docker-compose.dev-full.yml"OVERRIDE = "docker-compose.preview.yml"@@ -141,6 +259,8 @@ class PostHogPreviewStack:("ee", "/code/ee"),("products", "/code/products"),("packages/personhog-proto/personhog", "/code/personhog"),+ ("rust/persons_migrations", "/code/rust/persons_migrations"),+ ("frontend/src/lib/constants.tsx", "/code/frontend/src/lib/constants.tsx"),]def __init__(@@ -218,11 +338,12 @@ class PostHogPreviewStack:# run before up_web so the fresh web container reads the new index# template + collected statics.self.swap_frontend()- elif self.image:- self.export_image_static()+ if self.image:+ self.export_image_files(static=not self.frontend_dist_tar)self.up_web()self.wait_for_health()self.deep_health()+ self.report_pipeline_health()return urldef swap_frontend_only(self) -> str:@@ -420,6 +541,10 @@ class PostHogPreviewStack:# split-DNS), and the seeded demo user is staff, so /admin is as exposed# as the rest of the preview and no more." - ADMIN_PORTAL_ENABLED=1",+ " - SELF_CAPTURE=1",+ " - SELF_CAPTURE_HOST=http://static-proxy:8000",+ " - OTEL_SERVICE_NAME=posthog-web",+ *_OTEL_ENV,]lines += [" static-proxy:",@@ -446,7 +571,9 @@ class PostHogPreviewStack:" - ENCRYPTION_SALT_KEYS=00beef0000beef0000beef0000beef00"," - PERSONHOG_ADDR=personhog-router:50052"," - PERSONHOG_ENABLED=true",+ *_OTEL_ENV,]+ lines += self._self_capture_services() + self._telemetry_services()# Mirror the bake script's personhog service definitions (hogland# scripts/posthog-preview-setup.sh): dev-full.yml carries NO personhog# services (dev runs them via hogli), so define them here the way HOBBY@@ -568,9 +695,99 @@ class PostHogPreviewStack:# doesn't start. Values mirror the bake." - TEMPORAL_HEALTH_PORT=7999"," - TEMPORAL_HEALTH_MAX_IDLE_SECONDS=86400",+ " - OTEL_SERVICE_NAME=posthog-temporal-worker",+ " - TEMPORAL_OTEL_PLUGIN_ENABLED=true",+ *_OTEL_ENV,]self.backend.write_file(f"{self.repo_dir}/{self.OVERRIDE}", "\n".join(lines) + "\n")+ def _self_capture_services(self) -> list[str]:+ return [+ " ingestion-general:",+ " extends:",+ " file: docker-compose.base.yml",+ " service: ingestion-general",+ f" image: {self.CDP_IMAGE}",+ " environment:",+ " - PERSONHOG_ADDR=personhog-router:50052",+ " - PERSONHOG_ENABLED=true",+ *_OTEL_ENV,+ " depends_on:",+ " - db",+ " - redis7",+ " - clickhouse",+ " - kafka",+ " - objectstorage",+ " - personhog-router",+ ]++ def _telemetry_services(self) -> list[str]:+ node_consumer = [" depends_on:", " - db", " - redis7", " - kafka"]+ return [+ " capture-logs:",+ " extends:",+ " file: docker-compose.base.yml",+ " service: capture-logs",+ " depends_on:",+ " - kafka",+ " ingestion-logs:",+ " extends:",+ " file: docker-compose.base.yml",+ " service: ingestion-logs",+ f" image: {self.CDP_IMAGE}",+ " environment:",+ " - LOGS_REDIS_TLS=false",+ *node_consumer,+ " ingestion-traces:",+ " extends:",+ " file: docker-compose.base.yml",+ " service: ingestion-traces",+ f" image: {self.CDP_IMAGE}",+ " environment:",+ " - TRACES_REDIS_TLS=false",+ *node_consumer,+ " ingestion-metrics:",+ f" image: {self.CDP_IMAGE}",+ " command: node nodejs/dist/index.js",+ " restart: on-failure",+ " environment:",+ " - PLUGIN_SERVER_MODE=ingestion-metrics",+ " - DATABASE_URL=postgres://posthog:posthog@db:5432/posthog",+ " - KAFKA_HOSTS=kafka:9092",+ " - REDIS_URL=redis://redis7:6379/",+ " - METRICS_REDIS_HOST=redis7",+ " - METRICS_REDIS_TLS=false",+ *node_consumer,+ " otel-collector:",+ " depends_on: !reset []",+ " volumes:",+ f" - ./{self.OTEL_COLLECTOR_CONFIG}:/etc/otel-collector-config.yaml:ro",+ " environment:",+ f" - COMPOSE_PROJECT={self.COMPOSE_PROJECT}",+ " networks:",+ " - default",+ " - otel_network",+ ]++ def _demo_project_token(self) -> str:+ query = (+ "SELECT api_token FROM posthog_team ORDER BY "+ f"id = (SELECT current_team_id FROM posthog_user WHERE email = '{_DEMO_EMAIL}') DESC NULLS LAST, id LIMIT 1"+ )+ result = self.backend.exec(+ self._compose(f'exec -T db psql -U posthog -d posthog -tAc "{query}"'),+ timeout=120,+ )+ token = result.stdout.strip()+ if not token:+ sys.stderr.write(f"[hogbox-preview] demo project token lookup returned nothing: {result.stderr.strip()}\n")+ return token++ def write_otel_collector_config(self) -> None:+ token = self._demo_project_token()+ config = _OTEL_COLLECTOR_CONFIG.format(pipeline="|".join(_TELEMETRY_PIPELINE), token=token)+ self.backend.write_file(f"{self.repo_dir}/{self.OTEL_COLLECTOR_CONFIG}", config)+def build_app(self) -> None:# `build: .` from the checkout — bakes the PR's code (front + back) into# the image. Cold this is ~15-25 min; on a restored golden the Docker@@ -643,9 +860,11 @@ class PostHogPreviewStack:# mounts — the frontend mounts are web-only), so it just costs one more# container recreate on the deferred-swap path.timing.stage("start web + temporal worker containers")- self.backend.run_long(- self._compose("up -d --no-build web temporal-django-worker static-proxy"), name="up-web", timeout=900+ self.write_otel_collector_config()+ services = " ".join(+ ["web", "temporal-django-worker", "static-proxy", *self.SELF_CAPTURE_SERVICES, *self.TELEMETRY_SERVICES])+ self.backend.run_long(self._compose(f"up -d --no-build {services}"), name="up-web", timeout=1800)def migrate(self) -> None:# PostHog needs both: Postgres (schema) and ClickHouse (events DB +@@ -657,6 +876,17 @@ class PostHogPreviewStack:name="migrate",timeout=1800,)+ self.backend.run_long(+ self._compose("run --rm -T web python manage.py apply_persons_migrations --hobby"),+ name="migrate-persons",+ timeout=900,+ )+ index = "CREATE UNIQUE INDEX IF NOT EXISTS posthog_person_team_id_uuid_uniq ON posthog_person (team_id, uuid)"+ self.backend.run_long(+ self._compose(f'exec -T db psql -U posthog -d posthog -v ON_ERROR_STOP=1 -c "{index}"'),+ name="person-uuid-index",+ timeout=900,+ )self.backend.run_long(self._compose("run --rm -T web python manage.py migrate_clickhouse"),name="migrate-clickhouse",@@ -757,15 +987,17 @@ class PostHogPreviewStack:self.backend.run_long(script, name="frontend", timeout=900)timing.stage("frontend swap done (collectstatic done)")- def export_image_static(self) -> None:+ def export_image_files(self, *, static: bool) -> None:assert self.image is not None- timing.stage("export image static files for the static proxy")+ timing.stage("export image files for the static proxy and feature-flags")+ copies = ['docker cp "$cid":/code/share/GeoLite2-City.mmdb ./share/GeoLite2-City.mmdb']+ if static:+ copies.insert(0, 'rm -rf staticfiles && docker cp "$cid":/code/staticfiles ./staticfiles')self.backend.run_long(- f"cd {self.repo_dir} && rm -rf staticfiles && "- f"cid=$(docker create {self.image}) && "- 'docker cp "$cid":/code/staticfiles ./staticfiles; status=$?; '+ f"cd {self.repo_dir} && mkdir -p share && cid=$(docker create {self.image}) && "+ f"{{ {' && '.join(copies)}; }}; status=$?; "'docker rm "$cid" >/dev/null; exit $status',- name="export-static",+ name="export-image-files",timeout=600,)@@ -775,6 +1007,26 @@ class PostHogPreviewStack:with timing.span("health-poll"):self.backend.wait_http_ok("/_health", expect=200, timeout=900)+ def report_pipeline_health(self, settle_seconds: int = 90) -> None:+ services = " ".join([*self.SELF_CAPTURE_SERVICES, *self.TELEMETRY_SERVICES])+ compose = f"docker compose -f {self.COMPOSE} -f {self.OVERRIDE}"+ report = "/tmp/hogbox-pipeline-health.txt"+ script = (+ f"cd {self.repo_dir} && sleep {settle_seconds}; exec > {report} 2>&1; "+ f"for svc in {services}; do "+ f'cid=$({compose} ps -aq "$svc"); '+ 'if [ -z "$cid" ]; then echo "PIPELINE $svc missing"; continue; fi; '+ "state=$(docker inspect -f '{{.State.Status}} restarts={{.RestartCount}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}}' \"$cid\"); "+ 'echo "PIPELINE $svc $state"; '+ 'case "$state" in "running restarts=0 "*) ;; *) docker logs --tail 25 "$cid" 2>&1 | cut -c1-400 | sed "s/^/ $svc | /";; esac; '+ "done; free -m | sed 's/^/ memory | /'"+ )+ try:+ self.backend.run_long(script, name="pipeline-health", timeout=settle_seconds + 300)+ sys.stderr.write(f"{self.backend.exec(f'cat {report}', timeout=60).stdout}\n")+ except RuntimeError as e:+ sys.stderr.write(f"[hogbox-preview] pipeline health report failed: {e}\n")+def deep_health(self) -> None:# /_health is UNAUTHENTICATED — it passed the whole time previews were# 500ing on /api/projects/@current/ (the personhog drift), so "healthy"