File: sentry.py

package info (click to toggle)
python-django-guid 3.5.2-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 664 kB
  • sloc: python: 1,267; makefile: 16
file content (45 lines) | stat: -rw-r--r-- 1,519 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import logging
from typing import Any

from django.core.exceptions import ImproperlyConfigured

from django_guid.integrations import Integration

logger = logging.getLogger('django_guid')


class SentryIntegration(Integration):
    """
    Ensures that each request's correlation ID is passed on to Sentry exception logs as a `transaction_id`.
    """

    identifier = 'SentryIntegration'

    def setup(self) -> None:
        """
        Verifies that the sentry_sdk dependency is installed.
        """
        # Makes sure the client has installed the `sentry_sdk` package, and that the header is appropriately named.
        try:
            import sentry_sdk  # noqa: F401
        except ModuleNotFoundError:
            raise ImproperlyConfigured(
                'The package `sentry-sdk` is required for extending your tracing IDs to Sentry. '
                'Please run `pip install sentry-sdk` if you wish to include this integration.'
            )

    def run(self, guid: str, **kwargs: Any) -> None:
        """
        Sets the Sentry transaction_id.
        """
        import sentry_sdk
        from packaging import version

        if version.parse(sentry_sdk.VERSION) >= version.parse('2.12.0'):
            with sentry_sdk.isolation_scope() as scope:
                scope.set_tag('transaction_id', guid)
        else:
            with sentry_sdk.configure_scope() as scope:
                scope.set_tag('transaction_id', guid)

        logger.debug('Setting Sentry transaction_id to %s', guid)