references/python.md
AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt
Python Error Tracking installation
Canonical URL: https://posthog.com/docs/error-tracking/installation/python
Cloud region: This page uses US Cloud hosts. For an EU Cloud project, use
https://eu.i.posthog.cominstead ofhttps://us.i.posthog.com(ingestion host), and usehttps://eu.posthog.cominstead ofhttps://app.posthog.com(app host for links).
On this page
- Install with the wizard
- Install the package
- Initialize PostHog
- Send events
- Verify PostHog is initialized
- Setting up exception autocapture
- Manually capturing exceptions
- Framework-specific exception capture
- Verify error tracking
- Link releases
- Web framework integrations
Install with the wizard
Run this command in your project directory to add PostHog to your Python project. The wizard detects your framework, installs the SDK, and sets up your first events.
npx @posthog/wizard
Or set it up manually by following the rest of this guide.
-
1
Install the package
Required
Install the PostHog Python library using pip:
Terminal
pip install posthog -
2
Initialize PostHog
Required
Initialize the PostHog client with your project token and host from your project settings:
Python
from posthog import Posthog posthog = Posthog( project_api_key='<ph_project_token>', host='https://us.i.posthog.com' )Django integration
If you're using Django, check out our Django integration for automatic request tracking.
-
3
Send events
Recommended
Once installed, PostHog will automatically start capturing events. You can also manually send events to test your integration:
Capture custom events by calling the
capturemethod with an event name and properties:Python
import posthog posthog.capture('user_signed_up', distinct_id='user_123', properties={'example_property': 'example_value'}) -
Verify PostHog is initialized
Recommended
Before proceeding, enable debug and call
posthog.capture('test_event')to make sure you can capture events. -
4
Setting up exception autocapture
Recommended
Exception autocapture can be enabled during initialization of the PostHog client to automatically capture any unhandled exceptions thrown by your Python application. It works by setting Python's built-in exception hooks, such as
sys.excepthookandthreading.excepthook.Python
from posthog import Posthog posthog = Posthog("<ph_project_token>", enable_exception_autocapture=True, ...)We recommend setting up and using contexts so that exceptions automatically include distinct IDs, session IDs, and other properties you can set up with tags.
You can also enable code variables capture to automatically capture the state of local variables when exceptions occur, giving you a debugger-like view of your application.
-
5
Manually capturing exceptions
Optional
For exceptions handled by your application that you would still like sent to PostHog, you can manually call the capture method:
Python
posthog.capture_exception(e, distinct_id="user_distinct_id", properties=additional_properties)You can find a full example of all of this in our Python (and Flask) error tracking tutorial.
-
6
Framework-specific exception capture
Recommended
Web frameworks catch exceptions raised in your routes and turn them into error responses, so these exceptions never reach the hooks that exception autocapture uses. The Python SDK includes integrations for Django, Flask, and ASGI frameworks such as FastAPI. They capture these exceptions and add request properties to every event captured during a request. The Flask, ASGI, and Django REST Framework integrations require version
7.69.0or later of the Python SDK.Django
Add the Django middleware to your settings. It wraps each request in a context and captures exceptions raised by your views.
The middleware sends exceptions through the global
posthogclient. When you create your own client withPosthog(...), set it asPOSTHOG_MW_CLIENT. Otherwise the middleware sends exceptions to the unconfigured global client, and they don't reach PostHog:settings.py
from posthog import Posthog POSTHOG_MW_CLIENT = Posthog( '<ph_project_token>', host='https://us.i.posthog.com', enable_exception_autocapture=True, ) MIDDLEWARE = [ # ... other middleware 'posthog.integrations.django.PosthogContextMiddleware', ]If you configure the global client instead, with
posthog.api_keyandposthog.host, leavePOSTHOG_MW_CLIENTunset.Django REST Framework converts exceptions into error responses before the middleware sees them. If you use it, also add the DRF exception handler:
settings.py
REST_FRAMEWORK = { # ... other DRF settings 'EXCEPTION_HANDLER': 'posthog.integrations.drf.exception_handler', }Set
POSTHOG_MW_CAPTURE_EXCEPTIONS = Falseto keep the request context without exception capture. See the Django integration docs for all settings.Flask
Register the Flask integration with your app and your client. It captures unhandled exceptions raised by your routes:
Python
from flask import Flask from posthog import Posthog from posthog.integrations.flask import PosthogFlaskIntegration app = Flask(__name__) posthog = Posthog( '<ph_project_token>', host='https://us.i.posthog.com', enable_exception_autocapture=True, ) PosthogFlaskIntegration(app, client=posthog)The integration doesn't capture expected HTTP exceptions, such as
404 Not Found, or exceptions that your own error handlers consume. To report an exception that you handle, callposthog.capture_exception(e)in the handler. See the Flask integration docs.FastAPI
Add the ASGI middleware to your app. It captures exceptions that escape your routes. It works the same way for Starlette, Litestar, and other ASGI frameworks:
Python
from fastapi import FastAPI from posthog import Posthog from posthog.integrations.asgi import PosthogASGIMiddleware posthog = Posthog( '<ph_project_token>', host='https://us.i.posthog.com', enable_exception_autocapture=True, ) app = FastAPI() app.add_middleware(PosthogASGIMiddleware, client=posthog)The middleware still captures an exception that an
@app.exception_handler(Exception)catch-all handles. A handler for a specific exception class, such as@app.exception_handler(ValueError), turns that exception into a response before the middleware sees it. To report those exceptions, callposthog.capture_exception(exc)in the handler. See the ASGI middleware docs. -
Verify error tracking
Recommended
Confirm events are being sent to PostHog
Before proceeding, let's make sure exception events are being captured and sent to PostHog. You should see events appear in the activity feed.
Activity feed with events
-
7
Link releases
Optional
Great, you're capturing exceptions! To see which release each exception comes from, give your app the release ID when you deploy.
Let's continue to the next section.
Web framework integrations
The Python SDK includes request context and error tracking integrations for common web frameworks: