Python error tracking installation
- 1
Install the package
RequiredInstall the PostHog Python library using pip:
Terminal - 2
Initialize PostHog
RequiredInitialize the PostHog client with your project token and host from your project settings:
PythonDjango integrationIf you're using Django, check out our Django integration for automatic request tracking.
- 3
Send events
RecommendedOnce 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 Verify PostHog is initialized
RecommendedBefore proceeding, enable debug and call
posthog.capture('test_event')to make sure you can capture events.- 4
Setting up exception autocapture
RecommendedException 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.PythonWe 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
OptionalFor exceptions handled by your application that you would still like sent to PostHog, you can manually call the capture method:
PythonYou can find a full example of all of this in our Python (and Flask) error tracking tutorial.
- 6
Framework-specific exception capture
OptionalPython frameworks often have built-in error handlers. This means PostHog's default exception autocapture won't work and we need to manually capture errors instead. The exact process depends on the framework:
The Python SDK provides a Django middleware that automatically wraps all requests with a context. Add the middleware to your Django settings:
PythonBy default, the middleware captures exceptions and sends them to PostHog. Disable with
POSTHOG_MW_CAPTURE_EXCEPTIONS = False. UsePOSTHOG_MW_EXTRA_TAGS,POSTHOG_MW_REQUEST_FILTER, andPOSTHOG_MW_TAG_MAPto customize. See the Django integration docs for full configuration.PythonPython

