From 629f54cafe5a81927ffb9a12d7425d182b6efa42 Mon Sep 17 00:00:00 2001 From: "Vincent (Wen Yu) Ge" Date: Thu, 12 Nov 2026 13:36:11 -0500 Subject: [PATCH] docs: preserve Python reference details --- posthog/client.py | 10 +++++-- posthog/request.py | 5 ++-- references/posthog-python-8.md | 53 +++++++++++++++++++++++++++++++--- 3 files changed, 60 insertions(+), 8 deletions(-) diff --git a/posthog/client.py b/posthog/client.py index 2d0006036..9e3083d84 100644 --- a/posthog/client.py +++ b/posthog/client.py @@ -1344,8 +1344,11 @@ def __init__( ``super_properties`` stops the SDK adding either ID. Exception events (``capture_exception``) always attach these IDs regardless of this setting. Defaults to False. - traces: Config dict for distributed tracing: ``service_name``, - ``service_version``, ``environment``, ``resource_attributes``, + traces: Config dict for distributed tracing. Non-empty string values for + ``service.name``, ``service.version`` and ``deployment.environment`` + in ``resource_attributes`` take precedence over ``service_name``, + ``service_version`` and ``environment``, respectively. Options include + ``service_name``, ``service_version``, ``environment``, ``resource_attributes``, ``flush_interval`` (5 s), ``max_queue_size`` (2048), ``max_export_batch_size`` (512), ``max_live_spans`` (10000), ``max_span_age`` (3600 s), ``max_attributes_per_span`` (128), @@ -3448,6 +3451,9 @@ def start_span( """ Start a span for distributed tracing. Alpha. + The span API is experimental and can change in a minor release. Spans + already sent are kept; the SDK API isn't frozen yet. + Returns a span handle. Use it as a context manager to make it the active span for the block and end it on exit (recording a raised exception on the way out); or call ``end()`` yourself for a span that cannot wrap a diff --git a/posthog/request.py b/posthog/request.py index efd749f3c..e3aa43a97 100644 --- a/posthog/request.py +++ b/posthog/request.py @@ -178,8 +178,9 @@ def enable_keep_alive() -> None: This helps prevent idle pooled connections from being dropped by network infrastructure. Call during initialization, before making API requests. - It uses a 60 second idle time, a 60 second probe interval and 3 probes - before timeout. + Where the platform supports the corresponding socket options, it uses + a 60 second idle time, a 60 second probe interval and 3 probes before + timeout. Unsupported settings keep their system defaults. """ set_socket_options(KEEP_ALIVE_SOCKET_OPTIONS) diff --git a/references/posthog-python-8.md b/references/posthog-python-8.md index 8f9198f3a..dbec7fac7 100644 --- a/references/posthog-python-8.md +++ b/references/posthog-python-8.md @@ -120,6 +120,29 @@ posthog.shutdown() In an asyncio app, use `AsyncPosthog` as an async context manager instead. See [AsyncClient](#asyncclient). +### Use AsyncPosthog in FastAPI + +Keep one `AsyncPosthog` client for the lifetime of your app. A FastAPI lifespan handler does this. + +```python +from contextlib import asynccontextmanager + +from fastapi import FastAPI +from posthog import AsyncPosthog + +@asynccontextmanager +async def lifespan(app: FastAPI): + async with AsyncPosthog("", host="") as posthog: + app.state.posthog = posthog + yield + +app = FastAPI(lifespan=lifespan) +``` + +### The posthoganalytics package + +`posthoganalytics` is the same SDK under another module name. Use it when another module named `posthog` is on your import path. + ## Setup ### `Client(...)` @@ -172,7 +195,7 @@ Name | Type | Description | Default `flag_definition_cache_provider` | `Optional[FlagDefinitionCacheProvider]` | Optional external cache provider for sharing feature flag definitions across workers. | `None` `capture_exception_code_variables` | | Capture local variable values on exception stack frames. | `False` `capture_trace_context` | | When OpenTelemetry is installed and a valid span is active at capture time, add its trace and span IDs as `$trace_id` and `$span_id` properties to events captured with `capture()` and `capture_ai()`, so they can be correlated with backend traces. They fill after context tags and `super_properties`, before `before_send`. A `$trace_id` or `$span_id` from the event, a context tag or `super_properties` stops the SDK adding either ID. Exception events (`capture_exception`) always attach these IDs regardless of this setting. Defaults to False. | `False` -`traces` | `Optional[dict]` | Config dict for distributed tracing: `service_name`, `service_version`, `environment`, `resource_attributes`, `flush_interval` (5 s), `max_queue_size` (2048), `max_export_batch_size` (512), `max_live_spans` (10000), `max_span_age` (3600 s), `max_attributes_per_span` (128), `max_events_per_span` (128), `max_attribute_value_length` (8192). `before_span_send` is a callable, or a list run in order, that receives each finished span as a dict (`trace_id`, `span_id` and `parent_span_id` are read-only) and returns it, edited, or `None` to drop it; a hook that raises drops the span. Tracing is off until this is provided. Spans export on a background timer even with `sync_mode`; serverless handlers should call `flush()` before returning. Defaults to None. | `None` +`traces` | `Optional[dict]` | Config dict for distributed tracing. Non-empty string values for `service.name`, `service.version` and `deployment.environment` in `resource_attributes` take precedence over `service_name`, `service_version` and `environment`, respectively. Options include `service_name`, `service_version`, `environment`, `resource_attributes`, `flush_interval` (5 s), `max_queue_size` (2048), `max_export_batch_size` (512), `max_live_spans` (10000), `max_span_age` (3600 s), `max_attributes_per_span` (128), `max_events_per_span` (128), `max_attribute_value_length` (8192). `before_span_send` is a callable, or a list run in order, that receives each finished span as a dict (`trace_id`, `span_id` and `parent_span_id` are read-only) and returns it, edited, or `None` to drop it; a hook that raises drops the span. The span dict has `name`, `kind`, `status`, `attributes`, `events`, `start_time_ns`, `end_time_ns`, `trace_id`, `span_id` and `parent_span_id`, and its attributes are plain Python values. The hook runs after `posthogDistinctId` and `sessionId` are attached, so it can scrub them. It must be a regular function. An `async` hook drops every span. In a list of hooks, the first one to return `None` stops the chain. An entry that isn't callable turns tracing off for the client. Past a per-span cap, the earliest attributes and events are kept and the span reports how many were dropped. `posthogDistinctId` and `sessionId` don't count toward the attribute cap and are never dropped. `max_attribute_value_length` also applies to strings nested in lists and dictionaries. All caps are applied again after `before_span_send`. Spans beyond `max_queue_size` are dropped. An invalid value falls back to its default with a warning. Tracing is off until this is provided. Spans export on a background timer even with `sync_mode`; serverless handlers should call `flush()` before returning. Defaults to None. | `None` `code_variables_mask_patterns` | | Variable-name patterns to mask when capturing code variables. | `None` `code_variables_ignore_patterns` | | Variable-name patterns to omit when capturing code variables. | `None` `code_variables_mask_url_credentials` | | Scrub credentials embedded in URLs/DSNs (e.g. `user:pass@host`) from captured code variables, regardless of the surrounding variable name. Defaults to True. | `None` @@ -317,12 +340,17 @@ start_span(name: str, *, kind: Optional[str] = None, attributes: Optional[Mappin Start a span for distributed tracing. Alpha. +The span API is experimental and can change in a minor release. Spans +already sent are kept; the SDK API isn't frozen yet. + Returns a span handle. Use it as a context manager to make it the active span for the block and end it on exit (recording a raised exception on the way out); or call `end()` yourself for a span that cannot wrap a block. Spans started inside the block nest under it automatically. Always returns a usable handle, even when tracing is off, so calling -code never branches. +code never branches. Once `max_live_spans` spans are open, the +returned span isn't recorded. Spans open longer than `max_span_age` +seconds are then treated as leaked and never exported. **Parameters:** @@ -331,9 +359,9 @@ Name | Type | Description | Default `name` | `str` | A low-cardinality operation name, e.g. `GET /users/:id`. Variable values belong in attributes, not the name. | *required* `kind` | `Optional[str]` | `internal` (default), `server`, `client`, `producer` or `consumer`. | `None` `attributes` | `Optional[Mapping[str, Any]]` | Initial attributes. | `None` -`parent` | `Union[Span, str, None]` | A span handle, or an inbound W3C `traceparent` header value to continue a remote trace. Defaults to the active span. A forked child starts with no active span; pass the parent span to continue a trace across a fork. | `None` +`parent` | `Union[Span, str, None]` | A span handle, or an inbound W3C `traceparent` header value to continue a remote trace. Defaults to the active span. A forked child starts with no active span; pass the parent span to continue a trace across a fork. The active span is tracked with `contextvars`, so it carries across `await`. Threads don't reliably inherit it, so pass `parent=span` in a thread or a `ThreadPoolExecutor` task. A malformed `traceparent` starts a new trace and doesn't raise. A continued trace propagates the sampled flag it received. PostHog doesn't sample, so the span is exported whichever way the flag is set. | `None` `tracestate` | `Optional[str]` | The inbound `tracestate` header accompanying a `traceparent` string `parent`; preserved and propagated. | `None` -`start_time` | `Union[datetime, float, None]` | A `datetime` or epoch seconds, to backdate the span. | `None` +`start_time` | `Union[datetime, float, None]` | A `datetime` or epoch seconds, to backdate the span. PostHog clamps a start time more than 24 hours old to the receive time. | `None` **Examples:** @@ -902,6 +930,8 @@ server receipt. Event draining has no timeout. Queued spans get one final flush with up to 30 seconds waiting for an in-flight flush, then a fresh 30-second drain budget; the last HTTP request is not cut short. Any spans it cannot send are discarded with a warning, as are spans still open. +A script that exits without calling `shutdown()` gets only a brief +best-effort span flush, so don't rely on it. Lifecycle cleanup is attempted once, and cleanup failures are logged without retry. When called directly from an SDK callback such as `on_error`, shutdown is deferred to avoid blocking the worker that @@ -1619,6 +1649,12 @@ PosthogASGIMiddleware(app: _ASGIApp, client: Optional[Client] = None, capture_ex Add PostHog context and automatic exception capture to an ASGI app. +It creates a context for each HTTP or WebSocket request and captures +exceptions that escape the app. In FastAPI or Starlette, add it with +`app.add_middleware(PosthogASGIMiddleware, client=posthog)`. For Litestar, +another ASGI framework or a raw ASGI app, wrap the app with +`app = PosthogASGIMiddleware(app, client=posthog)`. + **Parameters:** Name | Type | Description | Default @@ -1827,6 +1863,9 @@ Enable TCP keepalive for SDK HTTP connections. This helps prevent idle pooled connections from being dropped by network infrastructure. Call during initialization, before making API requests. +Where the platform supports the corresponding socket options, it uses +a 60 second idle time, a 60 second probe interval and 3 probes before +timeout. Unsupported settings keep their system defaults. ### `posthog.request.disable_connection_reuse` @@ -3789,6 +3828,12 @@ may lose its cause). Returns the span, so calls chain. Inside `with span:` a raised `Exception` is recorded automatically, so this is for exceptions that are caught and handled. +The stack trace contains file paths from your server. Remove +`exception.stacktrace` in `before_span_send` to keep them in your +process. The `exception` event uses one of the span's event slots. A +span that fills its events and then raises keeps its `error` status +and loses the exception detail. + **Examples:** ```python