references/python.md · 24000
d).
LLM analytics
Our Python SDK includes a built-in LLM analytics feature. It enables you to capture LLM usage, performance, and more. Check out our analytics docs for more details on setting it up.
Error tracking
You can autocapture exceptions by setting the enable_exception_autocapture argument to True when initializing the PostHog client.
Python
PostHog AI
from posthog import Posthog
posthog = Posthog("<ph_project_token>", enable_exception_autocapture=True, ...)
You can also manually capture exceptions using the capture_exception method:
Python
PostHog AI
posthog.capture_exception(e, 'user_distinct_id', properties=additional_properties)
Contexts automatically capture exceptions thrown inside them, unless disable it by passing capture_exceptions=False to new_context().
Code variables capture
The Python SDK can automatically capture the state of local variables when an exception occurs. This gives you a debugger-like view of your application state at the time of the error:
Python
PostHog AI
posthog = Posthog(
"<ph_project_token>",
enable_exception_autocapture=True,
capture_exception_code_variables=True,
)
You can configure which variables are captured, masked, or ignored. See the code variables documentation for detailed configuration options.
GeoIP properties
Before posthog-python v3.0, we added GeoIP properties to all incoming events by default. We also used these properties for feature flag evaluation, based on the IP address of the request. This isn't ideal since they are created based on your server IP address, rather than the user's, leading to incorrect location resolution.
As of posthog-python v3.0, the default now is to disregard the server IP, not add the GeoIP properties, and not use the values for feature flag evaluations.
You can go back to previous behavior by doing setting the disable_geoip argument in your initialization to False:
Python
PostHog AI
posthog = Posthog('api_key', disable_geoip=False)
The list of properties that this overrides:
$geoip_city_name$geoip_country_name$geoip_country_code$geoip_continent_name$geoip_continent_code$geoip_postal_code$geoip_time_zone
You can also explicitly chose to enable or disable GeoIP for a single capture request like so:
Python
PostHog AI
posthog.capture('test_event', disable_geoip=True|False)
Debug mode
If you're not seeing the expected events being captured, the feature flags being evaluated, or the surveys being shown, you can enable debug mode to see what's happening.
You can enable debug mode by setting the debug option to True in the PostHog object. This will enable verbose logs about the inner workings of the SDK.
Python
PostHog AI
posthog.debug = True # +
Disabling requests during tests
You can disable requests during tests by setting the disabled option to True in the PostHog object. This means no events will be captured or no requests will be sent to PostHog.
Python
PostHog AI
if settings.TEST:
posthog.disabled = True
Connection configuration
The SDK uses HTTP connection pooling internally for better performance. These settings typically need not be changed, but in some environments, such as when running behind NAT gateways, pooled connections may be terminated non-gracefully, causing request failures.
You can configure connection behavior in several ways. The following settings should be called during initialization, before any API requests are made.
Enable TCP keepalive
TCP keepalive probes help prevent idle connections from being dropped by network infrastructure. This is the recommended approach for most cases where idle connections are terminated.
Python
PostHog AI
import posthog
posthog.enable_keep_alive()
This enables TCP keepalive with sensible defaults (60 second idle time, 60 second probe interval, 3 probes before timeout).
Disable connection pooling
If you need each request to use a fresh connection, you can disable connection reuse entirely. This will incur additional overhead per request but may be desirable in some circumstances.
Python
PostHog AI
import posthog
posthog.disable_connection_reuse()
Custom HTTP socket options
For advanced use cases, you can configure arbitrary socket options on the underlying HTTP connection.
Python
PostHog AI
import socket
import posthog
posthog.set_socket_options([
(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1),
# Add additional socket options as needed
])
Pass None to set_socket_options() to reset to default behavior.
Historical migrations
You can use the Python or Node SDK to run historical migrations of data into PostHog. To do so, set the historical_migration option to true when initializing the client.
PostHog AI
Python
from posthog import Posthog
from datetime import datetime
posthog = Posthog(
'<ph_project_token>',
host='https://us.i.posthog.com',
debug=True,
historical_migration=True
)
events = [
{
"event": "batched_event_name",
"properties": {
"distinct_id": "user_id",
"timestamp": datetime.fromisoformat("2024-04-02T12:00:00")
}
},
{
"event": "batched_event_name",
"properties": {
"distinct_id": "used_id",
"timestamp": datetime.fromisoformat("2024-04-02T12:00:00")
}
}
]
for event in events:
posthog.capture(
distinct_id=event["properties"]["distinct_id"],
event=event["event"],
properties=event["properties"],
timestamp=event["properties"]["timestamp"],
)
Node.js
import { PostHog } from 'posthog-node'
const client = new PostHog(
'<ph_project_token>',
{
host: 'https://us.i.posthog.com',
historicalMigration: true
}
)
client.debug()
client.capture({
event: "batched_event_name",
distinctId: "user_id",
properties: {},
timestamp: "2024-04-03T12:00:00Z"
})
client.capture({
event: "batched_event_name",
distinctId: "user_id",
properties: {},
timestamp: "2024-04-03T13:00:00Z"
})
await client.shutdown()
Serverless environments (Render/Lambda/...)
By default, the library buffers events before sending them to the capture endpoint, for better performance. This can lead to lost events in serverless environments, if the Python process is terminated by the platform before the buffer is fully flushed. To avoid this, you can either:
- Ensure that
posthog.shutdown()is called after processing every request by adding a middleware to your server. This allowsposthog.capture()to remain asynchronous for better performance.posthog.shutdown()is blocking. - Enable the
sync_modeoption when initializing the client, so that all calls toposthog.capture()become synchronous.
Django
See our Django docs for how to set up PostHog in Django. Our library includes a contexts middleware that can automatically capture distinct IDs, session IDs, and other properties you can set up with tags.
Alternative name
As our open source project PostHog shares the same module name, we created a special posthoganalytics package, mostly for internal use to avoid module collision. It is the exact same.
Thank you
This library is largely based on the analytics-python package.
Community questions
Ask a question
Was this page useful?
HelpfulCould be better