|
| 1 | +from sentry_sdk._types import MYPY |
| 2 | +from sentry_sdk.hub import Hub |
| 3 | +from sentry_sdk.integrations import Integration |
| 4 | +from sentry_sdk.scope import add_global_event_processor |
| 5 | + |
| 6 | +import posthog |
| 7 | +from posthog.request import DEFAULT_HOST |
| 8 | +from posthog.sentry import POSTHOG_ID_TAG |
| 9 | + |
| 10 | +if MYPY: |
| 11 | + from typing import Any, Dict, Optional |
| 12 | + |
| 13 | + from sentry_sdk._types import Event, Hint |
| 14 | + |
| 15 | + |
| 16 | +class PostHogIntegration(Integration): |
| 17 | + identifier = "posthog-python" |
| 18 | + organization = None # The Sentry organization, used to send a direct link from PostHog to Sentry |
| 19 | + project_id = None # The Sentry project id, used to send a direct link from PostHog to Sentry |
| 20 | + prefix = "https://sentry.io/organizations/" # Url of a self-hosted sentry instance (default: https://sentry.io/organizations/) |
| 21 | + |
| 22 | + @staticmethod |
| 23 | + def setup_once(): |
| 24 | + @add_global_event_processor |
| 25 | + def processor(event, hint): |
| 26 | + # type: (Event, Optional[Hint]) -> Optional[Event] |
| 27 | + if Hub.current.get_integration(PostHogIntegration) is not None: |
| 28 | + if event.get("level") != "error": |
| 29 | + return event |
| 30 | + |
| 31 | + if event.get("tags", {}).get(POSTHOG_ID_TAG): |
| 32 | + posthog_distinct_id = event["tags"][POSTHOG_ID_TAG] |
| 33 | + event["tags"]["PostHog URL"] = f"{posthog.host or DEFAULT_HOST}/person/{posthog_distinct_id}" |
| 34 | + |
| 35 | + properties = { |
| 36 | + "$sentry_event_id": event["event_id"], |
| 37 | + "$sentry_exception": event["exception"], |
| 38 | + } |
| 39 | + |
| 40 | + if PostHogIntegration.organization and PostHogIntegration.project_id: |
| 41 | + properties[ |
| 42 | + "$sentry_url" |
| 43 | + ] = f"{PostHogIntegration.prefix}{PostHogIntegration.organization}/issues/?project={PostHogIntegration.project_id}&query={event['event_id']}" |
| 44 | + |
| 45 | + posthog.capture(posthog_distinct_id, "$exception", properties) |
| 46 | + |
| 47 | + return event |
0 commit comments