|
| 1 | +"""Optional Sentry integration for error tracking and monitoring. |
| 2 | +
|
| 3 | +This module provides optional Sentry instrumentation that can be enabled |
| 4 | +via environment variables. It's designed to be non-invasive and vendor-neutral, |
| 5 | +allowing users to opt-in to Sentry monitoring without forcing a dependency. |
| 6 | +
|
| 7 | +Environment Variables: |
| 8 | + SENTRY_DSN: Sentry Data Source Name (required to enable Sentry) |
| 9 | + SENTRY_ENVIRONMENT: Environment name (e.g., production, development) |
| 10 | + SENTRY_RELEASE: Release version or commit SHA |
| 11 | + SENTRY_TRACES_SAMPLE_RATE: Sampling rate for performance traces (0.0 to 1.0) |
| 12 | + SENTRY_PROFILES_SAMPLE_RATE: Sampling rate for profiling (0.0 to 1.0) |
| 13 | +""" |
| 14 | + |
| 15 | +import logging |
| 16 | +import os |
| 17 | +from typing import Any |
| 18 | + |
| 19 | +logger = logging.getLogger(__name__) |
| 20 | + |
| 21 | + |
| 22 | +def init_sentry() -> bool: |
| 23 | + """ |
| 24 | + Initialize Sentry SDK if configured via environment variables. |
| 25 | +
|
| 26 | + This function attempts to import and configure Sentry SDK only if |
| 27 | + SENTRY_DSN is provided. It gracefully handles missing sentry-sdk |
| 28 | + installation and logs appropriate messages. |
| 29 | +
|
| 30 | + Returns: |
| 31 | + bool: True if Sentry was successfully initialized, False otherwise |
| 32 | +
|
| 33 | + Example: |
| 34 | + >>> import os |
| 35 | + >>> os.environ["SENTRY_DSN"] = "https://..." |
| 36 | + >>> init_sentry() |
| 37 | + True |
| 38 | + """ |
| 39 | + dsn = os.environ.get("SENTRY_DSN") |
| 40 | + |
| 41 | + if not dsn: |
| 42 | + logger.debug("SENTRY_DSN not configured, skipping Sentry initialization") |
| 43 | + return False |
| 44 | + |
| 45 | + try: |
| 46 | + import sentry_sdk |
| 47 | + from sentry_sdk.integrations.logging import LoggingIntegration |
| 48 | + except ImportError: |
| 49 | + logger.warning("Sentry SDK not installed") |
| 50 | + return False |
| 51 | + |
| 52 | + # Get optional configuration from environment |
| 53 | + environment = os.environ.get("SENTRY_ENVIRONMENT", "production") |
| 54 | + release = os.environ.get("SENTRY_RELEASE") |
| 55 | + traces_sample_rate = float(os.environ.get("SENTRY_TRACES_SAMPLE_RATE", "0.1")) |
| 56 | + profiles_sample_rate = float(os.environ.get("SENTRY_PROFILES_SAMPLE_RATE", "0.1")) |
| 57 | + |
| 58 | + # Configure logging integration |
| 59 | + logging_integration = LoggingIntegration( |
| 60 | + level=logging.INFO, # Capture info and above as breadcrumbs |
| 61 | + event_level=logging.ERROR, # Send errors as events |
| 62 | + ) |
| 63 | + |
| 64 | + try: |
| 65 | + sentry_sdk.init( |
| 66 | + dsn=dsn, |
| 67 | + environment=environment, |
| 68 | + release=release, |
| 69 | + traces_sample_rate=traces_sample_rate, |
| 70 | + profiles_sample_rate=profiles_sample_rate, |
| 71 | + integrations=[logging_integration], |
| 72 | + # Automatically capture unhandled exceptions |
| 73 | + send_default_pii=False, # Don't send personally identifiable information by default |
| 74 | + ) |
| 75 | + |
| 76 | + logger.info( |
| 77 | + f"Sentry initialized successfully for environment: {environment}" |
| 78 | + + (f", release: {release}" if release else "") |
| 79 | + ) |
| 80 | + return True |
| 81 | + |
| 82 | + except Exception as e: |
| 83 | + logger.error(f"Failed to initialize Sentry: {str(e)}") |
| 84 | + return False |
| 85 | + |
| 86 | + |
| 87 | +def set_sentry_context(key: str, value: Any) -> None: |
| 88 | + """ |
| 89 | + Set additional context for Sentry error reporting. |
| 90 | +
|
| 91 | + This is a convenience wrapper that safely sets context even if |
| 92 | + Sentry is not initialized. |
| 93 | +
|
| 94 | + Args: |
| 95 | + key: Context key (e.g., "user", "workspace", "api_token") |
| 96 | + value: Context value (can be dict, string, etc.) |
| 97 | +
|
| 98 | + Example: |
| 99 | + >>> set_sentry_context("workspace", {"id": "123", "name": "acme"}) |
| 100 | + """ |
| 101 | + try: |
| 102 | + import sentry_sdk |
| 103 | + |
| 104 | + sentry_sdk.set_context(key, value) |
| 105 | + except ImportError: |
| 106 | + # Sentry not installed, silently skip |
| 107 | + pass |
| 108 | + except Exception as e: |
| 109 | + logger.debug(f"Failed to set Sentry context: {str(e)}") |
| 110 | + |
| 111 | + |
| 112 | +def set_sentry_user(user_info: dict[str, Any]) -> None: |
| 113 | + """ |
| 114 | + Set user information for Sentry error reporting. |
| 115 | +
|
| 116 | + This is a convenience wrapper that safely sets user info even if |
| 117 | + Sentry is not initialized. |
| 118 | +
|
| 119 | + Args: |
| 120 | + user_info: Dictionary with user information (id, email, username, etc.) |
| 121 | +
|
| 122 | + Example: |
| 123 | + >>> set_sentry_user({"id": "123", "email": "user@example.com"}) |
| 124 | + """ |
| 125 | + try: |
| 126 | + import sentry_sdk |
| 127 | + |
| 128 | + sentry_sdk.set_user(user_info) |
| 129 | + except ImportError: |
| 130 | + # Sentry not installed, silently skip |
| 131 | + pass |
| 132 | + except Exception as e: |
| 133 | + logger.debug(f"Failed to set Sentry user: {str(e)}") |
| 134 | + |
| 135 | + |
| 136 | +def capture_exception(exception: Exception, **kwargs) -> None: |
| 137 | + """ |
| 138 | + Manually capture an exception to Sentry. |
| 139 | +
|
| 140 | + This is useful for handled exceptions that you still want to track. |
| 141 | +
|
| 142 | + Args: |
| 143 | + exception: The exception to capture |
| 144 | + **kwargs: Additional context to attach to the event |
| 145 | +
|
| 146 | + Example: |
| 147 | + >>> try: |
| 148 | + ... risky_operation() |
| 149 | + ... except ValueError as e: |
| 150 | + ... capture_exception(e, extra={"operation": "risky_operation"}) |
| 151 | + ... handle_error(e) |
| 152 | + """ |
| 153 | + try: |
| 154 | + import sentry_sdk |
| 155 | + |
| 156 | + sentry_sdk.capture_exception(exception, **kwargs) |
| 157 | + except ImportError: |
| 158 | + # Sentry not installed, silently skip |
| 159 | + pass |
| 160 | + except Exception as e: |
| 161 | + logger.debug(f"Failed to capture exception in Sentry: {str(e)}") |
0 commit comments