Subchapter 81.8
references/python.mdMarkdown4 KBView on GitHub
AI agents: this is one page from PostHog’s docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt (opens in a new tab)
Note: Metrics is in open alpha. Any team can turn it on — open Metrics (opens in a new tab) and select Enable metrics in the onboarding view. Setup details may change before general availability.
The posthog-python (opens in a new tab) SDK includes the posthog.metrics API, so you can record metrics with the same client you use for events and feature flags.
1
Required
Terminal
pip install posthogMetrics requires an up-to-date SDK version, so upgrade if you’re on an older release.
2
Required
Set a service name so metrics from different systems stay easy to tell apart. It’s attached to every series and used by the Metrics UI for filtering.
Python
from posthog import Posthog
posthog = Posthog(
"<ph_project_token>",
host="https://us.i.posthog.com",
metrics={"service_name": "billing-worker"},
)Use your project token (the same one you use for capturing events), not a personal API key (opens in a new tab).
3
Required
Use the metric type that matches what you’re measuring:
Python
# Counters only go up: things you count
posthog.metrics.count("invoices.processed", 1, attributes={"plan": "pro"})
# Gauges go up and down: current values
posthog.metrics.gauge("queue.depth", 42)
4
Optional
If your service already records metrics with Prometheus, StatsD, or another system, don’t rip it out. Add the PostHog call next to the existing one, reusing the same metric name and attributes, so both systems chart the same series while you evaluate.
5
Required
For short-lived processes (cron jobs, CLIs, serverless functions), flush before exiting so the last aggregation window isn’t lost:
Python
posthog.metrics.flush()6
Recommended
Checkpoint
What you can do with your metrics
| Action | Description |
|---|---|
| Why you need metrics (opens in a new tab) | What metrics show you that events and logs don’t |
| Getting started guide (opens in a new tab) | Pick the right metric type, add attributes carefully, and chart what matters |
| Group and filter | Group by an attribute for one line per value, or filter with key=value chips |
| How metrics works |
Ask PostHog AI
HelpfulCould be better
The client is thread-safe and pre-aggregates: samples fold into per-series aggregates in memory and flush as one OTLP data point per series every few seconds, so recording in hot paths is cheap. A burst of 10k count() calls costs one data point on the wire.
Keep attribute values small and bounded: route, status, and plan are good attributes; user IDs, session IDs, and request IDs are not. Every unique combination creates a new series.
| How metrics are ingested, stored, and queried |
| Query with SQL | Every metric lands in the posthog.metrics table, queryable from the SQL tab |