Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 

1208 rindas
45 KiB

  1. import itertools
  2. from enum import Enum
  3. from typing import TYPE_CHECKING
  4. # up top to prevent circular import due to integration import
  5. # This is more or less an arbitrary large-ish value for now, so that we allow
  6. # pretty long strings (like LLM prompts), but still have *some* upper limit
  7. # until we verify that removing the trimming completely is safe.
  8. DEFAULT_MAX_VALUE_LENGTH = 100_000
  9. DEFAULT_MAX_STACK_FRAMES = 100
  10. DEFAULT_ADD_FULL_STACK = False
  11. # Also needs to be at the top to prevent circular import
  12. class EndpointType(Enum):
  13. """
  14. The type of an endpoint. This is an enum, rather than a constant, for historical reasons
  15. (the old /store endpoint). The enum also preserve future compatibility, in case we ever
  16. have a new endpoint.
  17. """
  18. ENVELOPE = "envelope"
  19. class CompressionAlgo(Enum):
  20. GZIP = "gzip"
  21. BROTLI = "br"
  22. if TYPE_CHECKING:
  23. import sentry_sdk
  24. from typing import Optional
  25. from typing import Callable
  26. from typing import Union
  27. from typing import List
  28. from typing import Type
  29. from typing import Dict
  30. from typing import Any
  31. from typing import Sequence
  32. from typing import Tuple
  33. from typing_extensions import Literal
  34. from typing_extensions import TypedDict
  35. from sentry_sdk._types import (
  36. BreadcrumbProcessor,
  37. ContinuousProfilerMode,
  38. Event,
  39. EventProcessor,
  40. Hint,
  41. Log,
  42. MeasurementUnit,
  43. ProfilerMode,
  44. TracesSampler,
  45. TransactionProcessor,
  46. MetricTags,
  47. MetricValue,
  48. )
  49. # Experiments are feature flags to enable and disable certain unstable SDK
  50. # functionality. Changing them from the defaults (`None`) in production
  51. # code is highly discouraged. They are not subject to any stability
  52. # guarantees such as the ones from semantic versioning.
  53. Experiments = TypedDict(
  54. "Experiments",
  55. {
  56. "max_spans": Optional[int],
  57. "max_flags": Optional[int],
  58. "record_sql_params": Optional[bool],
  59. "continuous_profiling_auto_start": Optional[bool],
  60. "continuous_profiling_mode": Optional[ContinuousProfilerMode],
  61. "otel_powered_performance": Optional[bool],
  62. "transport_zlib_compression_level": Optional[int],
  63. "transport_compression_level": Optional[int],
  64. "transport_compression_algo": Optional[CompressionAlgo],
  65. "transport_num_pools": Optional[int],
  66. "transport_http2": Optional[bool],
  67. "enable_metrics": Optional[bool],
  68. "before_emit_metric": Optional[
  69. Callable[[str, MetricValue, MeasurementUnit, MetricTags], bool]
  70. ],
  71. "metric_code_locations": Optional[bool],
  72. "enable_logs": Optional[bool],
  73. "before_send_log": Optional[Callable[[Log, Hint], Optional[Log]]],
  74. },
  75. total=False,
  76. )
  77. DEFAULT_QUEUE_SIZE = 100
  78. DEFAULT_MAX_BREADCRUMBS = 100
  79. MATCH_ALL = r".*"
  80. FALSE_VALUES = [
  81. "false",
  82. "no",
  83. "off",
  84. "n",
  85. "0",
  86. ]
  87. class INSTRUMENTER:
  88. SENTRY = "sentry"
  89. OTEL = "otel"
  90. class SPANDATA:
  91. """
  92. Additional information describing the type of the span.
  93. See: https://develop.sentry.dev/sdk/performance/span-data-conventions/
  94. """
  95. AI_CITATIONS = "ai.citations"
  96. """
  97. References or sources cited by the AI model in its response.
  98. Example: ["Smith et al. 2020", "Jones 2019"]
  99. """
  100. AI_DOCUMENTS = "ai.documents"
  101. """
  102. Documents or content chunks used as context for the AI model.
  103. Example: ["doc1.txt", "doc2.pdf"]
  104. """
  105. AI_FINISH_REASON = "ai.finish_reason"
  106. """
  107. The reason why the model stopped generating.
  108. Example: "length"
  109. """
  110. AI_FREQUENCY_PENALTY = "ai.frequency_penalty"
  111. """
  112. Used to reduce repetitiveness of generated tokens.
  113. Example: 0.5
  114. """
  115. AI_FUNCTION_CALL = "ai.function_call"
  116. """
  117. For an AI model call, the function that was called. This is deprecated for OpenAI, and replaced by tool_calls
  118. """
  119. AI_GENERATION_ID = "ai.generation_id"
  120. """
  121. Unique identifier for the completion.
  122. Example: "gen_123abc"
  123. """
  124. AI_INPUT_MESSAGES = "ai.input_messages"
  125. """
  126. The input messages to an LLM call.
  127. Example: [{"role": "user", "message": "hello"}]
  128. """
  129. AI_LOGIT_BIAS = "ai.logit_bias"
  130. """
  131. For an AI model call, the logit bias
  132. """
  133. AI_METADATA = "ai.metadata"
  134. """
  135. Extra metadata passed to an AI pipeline step.
  136. Example: {"executed_function": "add_integers"}
  137. """
  138. AI_MODEL_ID = "ai.model_id"
  139. """
  140. The unique descriptor of the model being execugted
  141. Example: gpt-4
  142. """
  143. AI_PIPELINE_NAME = "ai.pipeline.name"
  144. """
  145. Name of the AI pipeline or chain being executed.
  146. DEPRECATED: Use GEN_AI_PIPELINE_NAME instead.
  147. Example: "qa-pipeline"
  148. """
  149. AI_PREAMBLE = "ai.preamble"
  150. """
  151. For an AI model call, the preamble parameter.
  152. Preambles are a part of the prompt used to adjust the model's overall behavior and conversation style.
  153. Example: "You are now a clown."
  154. """
  155. AI_PRESENCE_PENALTY = "ai.presence_penalty"
  156. """
  157. Used to reduce repetitiveness of generated tokens.
  158. Example: 0.5
  159. """
  160. AI_RAW_PROMPTING = "ai.raw_prompting"
  161. """
  162. Minimize pre-processing done to the prompt sent to the LLM.
  163. Example: true
  164. """
  165. AI_RESPONSE_FORMAT = "ai.response_format"
  166. """
  167. For an AI model call, the format of the response
  168. """
  169. AI_RESPONSES = "ai.responses"
  170. """
  171. The responses to an AI model call. Always as a list.
  172. Example: ["hello", "world"]
  173. """
  174. AI_SEARCH_QUERIES = "ai.search_queries"
  175. """
  176. Queries used to search for relevant context or documents.
  177. Example: ["climate change effects", "renewable energy"]
  178. """
  179. AI_SEARCH_REQUIRED = "ai.is_search_required"
  180. """
  181. Boolean indicating if the model needs to perform a search.
  182. Example: true
  183. """
  184. AI_SEARCH_RESULTS = "ai.search_results"
  185. """
  186. Results returned from search queries for context.
  187. Example: ["Result 1", "Result 2"]
  188. """
  189. AI_SEED = "ai.seed"
  190. """
  191. The seed, ideally models given the same seed and same other parameters will produce the exact same output.
  192. Example: 123.45
  193. """
  194. AI_STREAMING = "ai.streaming"
  195. """
  196. Whether or not the AI model call's response was streamed back asynchronously
  197. DEPRECATED: Use GEN_AI_RESPONSE_STREAMING instead.
  198. Example: true
  199. """
  200. AI_TAGS = "ai.tags"
  201. """
  202. Tags that describe an AI pipeline step.
  203. Example: {"executed_function": "add_integers"}
  204. """
  205. AI_TEMPERATURE = "ai.temperature"
  206. """
  207. For an AI model call, the temperature parameter. Temperature essentially means how random the output will be.
  208. Example: 0.5
  209. """
  210. AI_TEXTS = "ai.texts"
  211. """
  212. Raw text inputs provided to the model.
  213. Example: ["What is machine learning?"]
  214. """
  215. AI_TOP_K = "ai.top_k"
  216. """
  217. For an AI model call, the top_k parameter. Top_k essentially controls how random the output will be.
  218. Example: 35
  219. """
  220. AI_TOP_P = "ai.top_p"
  221. """
  222. For an AI model call, the top_p parameter. Top_p essentially controls how random the output will be.
  223. Example: 0.5
  224. """
  225. AI_TOOL_CALLS = "ai.tool_calls"
  226. """
  227. For an AI model call, the function that was called. This is deprecated for OpenAI, and replaced by tool_calls
  228. """
  229. AI_TOOLS = "ai.tools"
  230. """
  231. For an AI model call, the functions that are available
  232. """
  233. AI_WARNINGS = "ai.warnings"
  234. """
  235. Warning messages generated during model execution.
  236. Example: ["Token limit exceeded"]
  237. """
  238. CACHE_HIT = "cache.hit"
  239. """
  240. A boolean indicating whether the requested data was found in the cache.
  241. Example: true
  242. """
  243. CACHE_ITEM_SIZE = "cache.item_size"
  244. """
  245. The size of the requested data in bytes.
  246. Example: 58
  247. """
  248. CACHE_KEY = "cache.key"
  249. """
  250. The key of the requested data.
  251. Example: template.cache.some_item.867da7e2af8e6b2f3aa7213a4080edb3
  252. """
  253. CODE_FILEPATH = "code.filepath"
  254. """
  255. The source code file name that identifies the code unit as uniquely as possible (preferably an absolute file path).
  256. Example: "/app/myapplication/http/handler/server.py"
  257. """
  258. CODE_FUNCTION = "code.function"
  259. """
  260. The method or function name, or equivalent (usually rightmost part of the code unit's name).
  261. Example: "server_request"
  262. """
  263. CODE_LINENO = "code.lineno"
  264. """
  265. The line number in `code.filepath` best representing the operation. It SHOULD point within the code unit named in `code.function`.
  266. Example: 42
  267. """
  268. CODE_NAMESPACE = "code.namespace"
  269. """
  270. The "namespace" within which `code.function` is defined. Usually the qualified class or module name, such that `code.namespace` + some separator + `code.function` form a unique identifier for the code unit.
  271. Example: "http.handler"
  272. """
  273. DB_MONGODB_COLLECTION = "db.mongodb.collection"
  274. """
  275. The MongoDB collection being accessed within the database.
  276. See: https://github.com/open-telemetry/semantic-conventions/blob/main/docs/database/mongodb.md#attributes
  277. Example: public.users; customers
  278. """
  279. DB_NAME = "db.name"
  280. """
  281. The name of the database being accessed. For commands that switch the database, this should be set to the target database (even if the command fails).
  282. Example: myDatabase
  283. """
  284. DB_OPERATION = "db.operation"
  285. """
  286. The name of the operation being executed, e.g. the MongoDB command name such as findAndModify, or the SQL keyword.
  287. See: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md
  288. Example: findAndModify, HMSET, SELECT
  289. """
  290. DB_SYSTEM = "db.system"
  291. """
  292. An identifier for the database management system (DBMS) product being used.
  293. See: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md
  294. Example: postgresql
  295. """
  296. DB_USER = "db.user"
  297. """
  298. The name of the database user used for connecting to the database.
  299. See: https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/database.md
  300. Example: my_user
  301. """
  302. GEN_AI_AGENT_NAME = "gen_ai.agent.name"
  303. """
  304. The name of the agent being used.
  305. Example: "ResearchAssistant"
  306. """
  307. GEN_AI_CHOICE = "gen_ai.choice"
  308. """
  309. The model's response message.
  310. Example: "The weather in Paris is rainy and overcast, with temperatures around 57°F"
  311. """
  312. GEN_AI_OPERATION_NAME = "gen_ai.operation.name"
  313. """
  314. The name of the operation being performed.
  315. Example: "chat"
  316. """
  317. GEN_AI_PIPELINE_NAME = "gen_ai.pipeline.name"
  318. """
  319. Name of the AI pipeline or chain being executed.
  320. Example: "qa-pipeline"
  321. """
  322. GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"
  323. """
  324. Exact model identifier used to generate the response
  325. Example: gpt-4o-mini-2024-07-18
  326. """
  327. GEN_AI_RESPONSE_STREAMING = "gen_ai.response.streaming"
  328. """
  329. Whether or not the AI model call's response was streamed back asynchronously
  330. Example: true
  331. """
  332. GEN_AI_RESPONSE_TEXT = "gen_ai.response.text"
  333. """
  334. The model's response text messages.
  335. Example: ["The weather in Paris is rainy and overcast, with temperatures around 57°F", "The weather in London is sunny and warm, with temperatures around 65°F"]
  336. """
  337. GEN_AI_RESPONSE_TOOL_CALLS = "gen_ai.response.tool_calls"
  338. """
  339. The tool calls in the model's response.
  340. Example: [{"name": "get_weather", "arguments": {"location": "Paris"}}]
  341. """
  342. GEN_AI_REQUEST_AVAILABLE_TOOLS = "gen_ai.request.available_tools"
  343. """
  344. The available tools for the model.
  345. Example: [{"name": "get_weather", "description": "Get the weather for a given location"}, {"name": "get_news", "description": "Get the news for a given topic"}]
  346. """
  347. GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"
  348. """
  349. The frequency penalty parameter used to reduce repetitiveness of generated tokens.
  350. Example: 0.1
  351. """
  352. GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"
  353. """
  354. The maximum number of tokens to generate in the response.
  355. Example: 2048
  356. """
  357. GEN_AI_REQUEST_MESSAGES = "gen_ai.request.messages"
  358. """
  359. The messages passed to the model. The "content" can be a string or an array of objects.
  360. Example: [{role: "system", "content: "Generate a random number."}, {"role": "user", "content": [{"text": "Generate a random number between 0 and 10.", "type": "text"}]}]
  361. """
  362. GEN_AI_REQUEST_MODEL = "gen_ai.request.model"
  363. """
  364. The model identifier being used for the request.
  365. Example: "gpt-4-turbo"
  366. """
  367. GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"
  368. """
  369. The presence penalty parameter used to reduce repetitiveness of generated tokens.
  370. Example: 0.1
  371. """
  372. GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"
  373. """
  374. The temperature parameter used to control randomness in the output.
  375. Example: 0.7
  376. """
  377. GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"
  378. """
  379. The top_p parameter used to control diversity via nucleus sampling.
  380. Example: 1.0
  381. """
  382. GEN_AI_SYSTEM = "gen_ai.system"
  383. """
  384. The name of the AI system being used.
  385. Example: "openai"
  386. """
  387. GEN_AI_TOOL_DESCRIPTION = "gen_ai.tool.description"
  388. """
  389. The description of the tool being used.
  390. Example: "Searches the web for current information about a topic"
  391. """
  392. GEN_AI_TOOL_INPUT = "gen_ai.tool.input"
  393. """
  394. The input of the tool being used.
  395. Example: {"location": "Paris"}
  396. """
  397. GEN_AI_TOOL_NAME = "gen_ai.tool.name"
  398. """
  399. The name of the tool being used.
  400. Example: "web_search"
  401. """
  402. GEN_AI_TOOL_OUTPUT = "gen_ai.tool.output"
  403. """
  404. The output of the tool being used.
  405. Example: "rainy, 57°F"
  406. """
  407. GEN_AI_TOOL_TYPE = "gen_ai.tool.type"
  408. """
  409. The type of tool being used.
  410. Example: "function"
  411. """
  412. GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"
  413. """
  414. The number of tokens in the input.
  415. Example: 150
  416. """
  417. GEN_AI_USAGE_INPUT_TOKENS_CACHED = "gen_ai.usage.input_tokens.cached"
  418. """
  419. The number of cached tokens in the input.
  420. Example: 50
  421. """
  422. GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"
  423. """
  424. The number of tokens in the output.
  425. Example: 250
  426. """
  427. GEN_AI_USAGE_OUTPUT_TOKENS_REASONING = "gen_ai.usage.output_tokens.reasoning"
  428. """
  429. The number of tokens used for reasoning in the output.
  430. Example: 75
  431. """
  432. GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"
  433. """
  434. The total number of tokens used (input + output).
  435. Example: 400
  436. """
  437. GEN_AI_USER_MESSAGE = "gen_ai.user.message"
  438. """
  439. The user message passed to the model.
  440. Example: "What's the weather in Paris?"
  441. """
  442. HTTP_FRAGMENT = "http.fragment"
  443. """
  444. The Fragments present in the URL.
  445. Example: #foo=bar
  446. """
  447. HTTP_METHOD = "http.method"
  448. """
  449. The HTTP method used.
  450. Example: GET
  451. """
  452. HTTP_QUERY = "http.query"
  453. """
  454. The Query string present in the URL.
  455. Example: ?foo=bar&bar=baz
  456. """
  457. HTTP_STATUS_CODE = "http.response.status_code"
  458. """
  459. The HTTP status code as an integer.
  460. Example: 418
  461. """
  462. MESSAGING_DESTINATION_NAME = "messaging.destination.name"
  463. """
  464. The destination name where the message is being consumed from,
  465. e.g. the queue name or topic.
  466. """
  467. MESSAGING_MESSAGE_ID = "messaging.message.id"
  468. """
  469. The message's identifier.
  470. """
  471. MESSAGING_MESSAGE_RECEIVE_LATENCY = "messaging.message.receive.latency"
  472. """
  473. The latency between when the task was enqueued and when it was started to be processed.
  474. """
  475. MESSAGING_MESSAGE_RETRY_COUNT = "messaging.message.retry.count"
  476. """
  477. Number of retries/attempts to process a message.
  478. """
  479. MESSAGING_SYSTEM = "messaging.system"
  480. """
  481. The messaging system's name, e.g. `kafka`, `aws_sqs`
  482. """
  483. NETWORK_PEER_ADDRESS = "network.peer.address"
  484. """
  485. Peer address of the network connection - IP address or Unix domain socket name.
  486. Example: 10.1.2.80, /tmp/my.sock, localhost
  487. """
  488. NETWORK_PEER_PORT = "network.peer.port"
  489. """
  490. Peer port number of the network connection.
  491. Example: 6379
  492. """
  493. PROFILER_ID = "profiler_id"
  494. """
  495. Label identifying the profiler id that the span occurred in. This should be a string.
  496. Example: "5249fbada8d5416482c2f6e47e337372"
  497. """
  498. SERVER_ADDRESS = "server.address"
  499. """
  500. Name of the database host.
  501. Example: example.com
  502. """
  503. SERVER_PORT = "server.port"
  504. """
  505. Logical server port number
  506. Example: 80; 8080; 443
  507. """
  508. SERVER_SOCKET_ADDRESS = "server.socket.address"
  509. """
  510. Physical server IP address or Unix socket address.
  511. Example: 10.5.3.2
  512. """
  513. SERVER_SOCKET_PORT = "server.socket.port"
  514. """
  515. Physical server port.
  516. Recommended: If different than server.port.
  517. Example: 16456
  518. """
  519. THREAD_ID = "thread.id"
  520. """
  521. Identifier of a thread from where the span originated. This should be a string.
  522. Example: "7972576320"
  523. """
  524. THREAD_NAME = "thread.name"
  525. """
  526. Label identifying a thread from where the span originated. This should be a string.
  527. Example: "MainThread"
  528. """
  529. class SPANSTATUS:
  530. """
  531. The status of a Sentry span.
  532. See: https://develop.sentry.dev/sdk/event-payloads/contexts/#trace-context
  533. """
  534. ABORTED = "aborted"
  535. ALREADY_EXISTS = "already_exists"
  536. CANCELLED = "cancelled"
  537. DATA_LOSS = "data_loss"
  538. DEADLINE_EXCEEDED = "deadline_exceeded"
  539. FAILED_PRECONDITION = "failed_precondition"
  540. INTERNAL_ERROR = "internal_error"
  541. INVALID_ARGUMENT = "invalid_argument"
  542. NOT_FOUND = "not_found"
  543. OK = "ok"
  544. OUT_OF_RANGE = "out_of_range"
  545. PERMISSION_DENIED = "permission_denied"
  546. RESOURCE_EXHAUSTED = "resource_exhausted"
  547. UNAUTHENTICATED = "unauthenticated"
  548. UNAVAILABLE = "unavailable"
  549. UNIMPLEMENTED = "unimplemented"
  550. UNKNOWN_ERROR = "unknown_error"
  551. class OP:
  552. ANTHROPIC_MESSAGES_CREATE = "ai.messages.create.anthropic"
  553. CACHE_GET = "cache.get"
  554. CACHE_PUT = "cache.put"
  555. COHERE_CHAT_COMPLETIONS_CREATE = "ai.chat_completions.create.cohere"
  556. COHERE_EMBEDDINGS_CREATE = "ai.embeddings.create.cohere"
  557. DB = "db"
  558. DB_REDIS = "db.redis"
  559. EVENT_DJANGO = "event.django"
  560. FUNCTION = "function"
  561. FUNCTION_AWS = "function.aws"
  562. FUNCTION_GCP = "function.gcp"
  563. GEN_AI_CHAT = "gen_ai.chat"
  564. GEN_AI_EMBEDDINGS = "gen_ai.embeddings"
  565. GEN_AI_EXECUTE_TOOL = "gen_ai.execute_tool"
  566. GEN_AI_HANDOFF = "gen_ai.handoff"
  567. GEN_AI_INVOKE_AGENT = "gen_ai.invoke_agent"
  568. GEN_AI_RESPONSES = "gen_ai.responses"
  569. GRAPHQL_EXECUTE = "graphql.execute"
  570. GRAPHQL_MUTATION = "graphql.mutation"
  571. GRAPHQL_PARSE = "graphql.parse"
  572. GRAPHQL_RESOLVE = "graphql.resolve"
  573. GRAPHQL_SUBSCRIPTION = "graphql.subscription"
  574. GRAPHQL_QUERY = "graphql.query"
  575. GRAPHQL_VALIDATE = "graphql.validate"
  576. GRPC_CLIENT = "grpc.client"
  577. GRPC_SERVER = "grpc.server"
  578. HTTP_CLIENT = "http.client"
  579. HTTP_CLIENT_STREAM = "http.client.stream"
  580. HTTP_SERVER = "http.server"
  581. MIDDLEWARE_DJANGO = "middleware.django"
  582. MIDDLEWARE_LITESTAR = "middleware.litestar"
  583. MIDDLEWARE_LITESTAR_RECEIVE = "middleware.litestar.receive"
  584. MIDDLEWARE_LITESTAR_SEND = "middleware.litestar.send"
  585. MIDDLEWARE_STARLETTE = "middleware.starlette"
  586. MIDDLEWARE_STARLETTE_RECEIVE = "middleware.starlette.receive"
  587. MIDDLEWARE_STARLETTE_SEND = "middleware.starlette.send"
  588. MIDDLEWARE_STARLITE = "middleware.starlite"
  589. MIDDLEWARE_STARLITE_RECEIVE = "middleware.starlite.receive"
  590. MIDDLEWARE_STARLITE_SEND = "middleware.starlite.send"
  591. HUGGINGFACE_HUB_CHAT_COMPLETIONS_CREATE = (
  592. "ai.chat_completions.create.huggingface_hub"
  593. )
  594. LANGCHAIN_PIPELINE = "ai.pipeline.langchain"
  595. LANGCHAIN_RUN = "ai.run.langchain"
  596. LANGCHAIN_TOOL = "ai.tool.langchain"
  597. LANGCHAIN_AGENT = "ai.agent.langchain"
  598. LANGCHAIN_CHAT_COMPLETIONS_CREATE = "ai.chat_completions.create.langchain"
  599. QUEUE_PROCESS = "queue.process"
  600. QUEUE_PUBLISH = "queue.publish"
  601. QUEUE_SUBMIT_ARQ = "queue.submit.arq"
  602. QUEUE_TASK_ARQ = "queue.task.arq"
  603. QUEUE_SUBMIT_CELERY = "queue.submit.celery"
  604. QUEUE_TASK_CELERY = "queue.task.celery"
  605. QUEUE_TASK_RQ = "queue.task.rq"
  606. QUEUE_SUBMIT_HUEY = "queue.submit.huey"
  607. QUEUE_TASK_HUEY = "queue.task.huey"
  608. QUEUE_SUBMIT_RAY = "queue.submit.ray"
  609. QUEUE_TASK_RAY = "queue.task.ray"
  610. SUBPROCESS = "subprocess"
  611. SUBPROCESS_WAIT = "subprocess.wait"
  612. SUBPROCESS_COMMUNICATE = "subprocess.communicate"
  613. TEMPLATE_RENDER = "template.render"
  614. VIEW_RENDER = "view.render"
  615. VIEW_RESPONSE_RENDER = "view.response.render"
  616. WEBSOCKET_SERVER = "websocket.server"
  617. SOCKET_CONNECTION = "socket.connection"
  618. SOCKET_DNS = "socket.dns"
  619. # This type exists to trick mypy and PyCharm into thinking `init` and `Client`
  620. # take these arguments (even though they take opaque **kwargs)
  621. class ClientConstructor:
  622. def __init__(
  623. self,
  624. dsn=None, # type: Optional[str]
  625. *,
  626. max_breadcrumbs=DEFAULT_MAX_BREADCRUMBS, # type: int
  627. release=None, # type: Optional[str]
  628. environment=None, # type: Optional[str]
  629. server_name=None, # type: Optional[str]
  630. shutdown_timeout=2, # type: float
  631. integrations=[], # type: Sequence[sentry_sdk.integrations.Integration] # noqa: B006
  632. in_app_include=[], # type: List[str] # noqa: B006
  633. in_app_exclude=[], # type: List[str] # noqa: B006
  634. default_integrations=True, # type: bool
  635. dist=None, # type: Optional[str]
  636. transport=None, # type: Optional[Union[sentry_sdk.transport.Transport, Type[sentry_sdk.transport.Transport], Callable[[Event], None]]]
  637. transport_queue_size=DEFAULT_QUEUE_SIZE, # type: int
  638. sample_rate=1.0, # type: float
  639. send_default_pii=None, # type: Optional[bool]
  640. http_proxy=None, # type: Optional[str]
  641. https_proxy=None, # type: Optional[str]
  642. ignore_errors=[], # type: Sequence[Union[type, str]] # noqa: B006
  643. max_request_body_size="medium", # type: str
  644. socket_options=None, # type: Optional[List[Tuple[int, int, int | bytes]]]
  645. keep_alive=None, # type: Optional[bool]
  646. before_send=None, # type: Optional[EventProcessor]
  647. before_breadcrumb=None, # type: Optional[BreadcrumbProcessor]
  648. debug=None, # type: Optional[bool]
  649. attach_stacktrace=False, # type: bool
  650. ca_certs=None, # type: Optional[str]
  651. propagate_traces=True, # type: bool
  652. traces_sample_rate=None, # type: Optional[float]
  653. traces_sampler=None, # type: Optional[TracesSampler]
  654. profiles_sample_rate=None, # type: Optional[float]
  655. profiles_sampler=None, # type: Optional[TracesSampler]
  656. profiler_mode=None, # type: Optional[ProfilerMode]
  657. profile_lifecycle="manual", # type: Literal["manual", "trace"]
  658. profile_session_sample_rate=None, # type: Optional[float]
  659. auto_enabling_integrations=True, # type: bool
  660. disabled_integrations=None, # type: Optional[Sequence[sentry_sdk.integrations.Integration]]
  661. auto_session_tracking=True, # type: bool
  662. send_client_reports=True, # type: bool
  663. _experiments={}, # type: Experiments # noqa: B006
  664. proxy_headers=None, # type: Optional[Dict[str, str]]
  665. instrumenter=INSTRUMENTER.SENTRY, # type: Optional[str]
  666. before_send_transaction=None, # type: Optional[TransactionProcessor]
  667. project_root=None, # type: Optional[str]
  668. enable_tracing=None, # type: Optional[bool]
  669. include_local_variables=True, # type: Optional[bool]
  670. include_source_context=True, # type: Optional[bool]
  671. trace_propagation_targets=[ # noqa: B006
  672. MATCH_ALL
  673. ], # type: Optional[Sequence[str]]
  674. functions_to_trace=[], # type: Sequence[Dict[str, str]] # noqa: B006
  675. event_scrubber=None, # type: Optional[sentry_sdk.scrubber.EventScrubber]
  676. max_value_length=DEFAULT_MAX_VALUE_LENGTH, # type: int
  677. enable_backpressure_handling=True, # type: bool
  678. error_sampler=None, # type: Optional[Callable[[Event, Hint], Union[float, bool]]]
  679. enable_db_query_source=True, # type: bool
  680. db_query_source_threshold_ms=100, # type: int
  681. spotlight=None, # type: Optional[Union[bool, str]]
  682. cert_file=None, # type: Optional[str]
  683. key_file=None, # type: Optional[str]
  684. custom_repr=None, # type: Optional[Callable[..., Optional[str]]]
  685. add_full_stack=DEFAULT_ADD_FULL_STACK, # type: bool
  686. max_stack_frames=DEFAULT_MAX_STACK_FRAMES, # type: Optional[int]
  687. ):
  688. # type: (...) -> None
  689. """Initialize the Sentry SDK with the given parameters. All parameters described here can be used in a call to `sentry_sdk.init()`.
  690. :param dsn: The DSN tells the SDK where to send the events.
  691. If this option is not set, the SDK will just not send any data.
  692. The `dsn` config option takes precedence over the environment variable.
  693. Learn more about `DSN utilization <https://docs.sentry.io/product/sentry-basics/dsn-explainer/#dsn-utilization>`_.
  694. :param debug: Turns debug mode on or off.
  695. When `True`, the SDK will attempt to print out debugging information. This can be useful if something goes
  696. wrong with event sending.
  697. The default is always `False`. It's generally not recommended to turn it on in production because of the
  698. increase in log output.
  699. The `debug` config option takes precedence over the environment variable.
  700. :param release: Sets the release.
  701. If not set, the SDK will try to automatically configure a release out of the box but it's a better idea to
  702. manually set it to guarantee that the release is in sync with your deploy integrations.
  703. Release names are strings, but some formats are detected by Sentry and might be rendered differently.
  704. See `the releases documentation <https://docs.sentry.io/platforms/python/configuration/releases/>`_ to learn how the SDK tries to
  705. automatically configure a release.
  706. The `release` config option takes precedence over the environment variable.
  707. Learn more about how to send release data so Sentry can tell you about regressions between releases and
  708. identify the potential source in `the product documentation <https://docs.sentry.io/product/releases/>`_.
  709. :param environment: Sets the environment. This string is freeform and set to `production` by default.
  710. A release can be associated with more than one environment to separate them in the UI (think `staging` vs
  711. `production` or similar).
  712. The `environment` config option takes precedence over the environment variable.
  713. :param dist: The distribution of the application.
  714. Distributions are used to disambiguate build or deployment variants of the same release of an application.
  715. The dist can be for example a build number.
  716. :param sample_rate: Configures the sample rate for error events, in the range of `0.0` to `1.0`.
  717. The default is `1.0`, which means that 100% of error events will be sent. If set to `0.1`, only 10% of
  718. error events will be sent.
  719. Events are picked randomly.
  720. :param error_sampler: Dynamically configures the sample rate for error events on a per-event basis.
  721. This configuration option accepts a function, which takes two parameters (the `event` and the `hint`), and
  722. which returns a boolean (indicating whether the event should be sent to Sentry) or a floating-point number
  723. between `0.0` and `1.0`, inclusive.
  724. The number indicates the probability the event is sent to Sentry; the SDK will randomly decide whether to
  725. send the event with the given probability.
  726. If this configuration option is specified, the `sample_rate` option is ignored.
  727. :param ignore_errors: A list of exception class names that shouldn't be sent to Sentry.
  728. Errors that are an instance of these exceptions or a subclass of them, will be filtered out before they're
  729. sent to Sentry.
  730. By default, all errors are sent.
  731. :param max_breadcrumbs: This variable controls the total amount of breadcrumbs that should be captured.
  732. This defaults to `100`, but you can set this to any number.
  733. However, you should be aware that Sentry has a `maximum payload size <https://develop.sentry.dev/sdk/data-model/envelopes/#size-limits>`_
  734. and any events exceeding that payload size will be dropped.
  735. :param attach_stacktrace: When enabled, stack traces are automatically attached to all messages logged.
  736. Stack traces are always attached to exceptions; however, when this option is set, stack traces are also
  737. sent with messages.
  738. This option means that stack traces appear next to all log messages.
  739. Grouping in Sentry is different for events with stack traces and without. As a result, you will get new
  740. groups as you enable or disable this flag for certain events.
  741. :param send_default_pii: If this flag is enabled, `certain personally identifiable information (PII)
  742. <https://docs.sentry.io/platforms/python/data-management/data-collected/>`_ is added by active integrations.
  743. If you enable this option, be sure to manually remove what you don't want to send using our features for
  744. managing `Sensitive Data <https://docs.sentry.io/data-management/sensitive-data/>`_.
  745. :param event_scrubber: Scrubs the event payload for sensitive information such as cookies, sessions, and
  746. passwords from a `denylist`.
  747. It can additionally be used to scrub from another `pii_denylist` if `send_default_pii` is disabled.
  748. See how to `configure the scrubber here <https://docs.sentry.io/data-management/sensitive-data/#event-scrubber>`_.
  749. :param include_source_context: When enabled, source context will be included in events sent to Sentry.
  750. This source context includes the five lines of code above and below the line of code where an error
  751. happened.
  752. :param include_local_variables: When enabled, the SDK will capture a snapshot of local variables to send with
  753. the event to help with debugging.
  754. :param add_full_stack: When capturing errors, Sentry stack traces typically only include frames that start the
  755. moment an error occurs.
  756. But if the `add_full_stack` option is enabled (set to `True`), all frames from the start of execution will
  757. be included in the stack trace sent to Sentry.
  758. :param max_stack_frames: This option limits the number of stack frames that will be captured when
  759. `add_full_stack` is enabled.
  760. :param server_name: This option can be used to supply a server name.
  761. When provided, the name of the server is sent along and persisted in the event.
  762. For many integrations, the server name actually corresponds to the device hostname, even in situations
  763. where the machine is not actually a server.
  764. :param project_root: The full path to the root directory of your application.
  765. The `project_root` is used to mark frames in a stack trace either as being in your application or outside
  766. of the application.
  767. :param in_app_include: A list of string prefixes of module names that belong to the app.
  768. This option takes precedence over `in_app_exclude`.
  769. Sentry differentiates stack frames that are directly related to your application ("in application") from
  770. stack frames that come from other packages such as the standard library, frameworks, or other dependencies.
  771. The application package is automatically marked as `inApp`.
  772. The difference is visible in [sentry.io](https://sentry.io), where only the "in application" frames are
  773. displayed by default.
  774. :param in_app_exclude: A list of string prefixes of module names that do not belong to the app, but rather to
  775. third-party packages.
  776. Modules considered not part of the app will be hidden from stack traces by default.
  777. This option can be overridden using `in_app_include`.
  778. :param max_request_body_size: This parameter controls whether integrations should capture HTTP request bodies.
  779. It can be set to one of the following values:
  780. - `never`: Request bodies are never sent.
  781. - `small`: Only small request bodies will be captured. The cutoff for small depends on the SDK (typically
  782. 4KB).
  783. - `medium`: Medium and small requests will be captured (typically 10KB).
  784. - `always`: The SDK will always capture the request body as long as Sentry can make sense of it.
  785. Please note that the Sentry server [limits HTTP request body size](https://develop.sentry.dev/sdk/
  786. expected-features/data-handling/#variable-size). The server always enforces its size limit, regardless of
  787. how you configure this option.
  788. :param max_value_length: The number of characters after which the values containing text in the event payload
  789. will be truncated.
  790. WARNING: If the value you set for this is exceptionally large, the event may exceed 1 MiB and will be
  791. dropped by Sentry.
  792. :param ca_certs: A path to an alternative CA bundle file in PEM-format.
  793. :param send_client_reports: Set this boolean to `False` to disable sending of client reports.
  794. Client reports allow the client to send status reports about itself to Sentry, such as information about
  795. events that were dropped before being sent.
  796. :param integrations: List of integrations to enable in addition to `auto-enabling integrations (overview)
  797. <https://docs.sentry.io/platforms/python/integrations>`_.
  798. This setting can be used to override the default config options for a specific auto-enabling integration
  799. or to add an integration that is not auto-enabled.
  800. :param disabled_integrations: List of integrations that will be disabled.
  801. This setting can be used to explicitly turn off specific `auto-enabling integrations (list)
  802. <https://docs.sentry.io/platforms/python/integrations/#available-integrations>`_ or
  803. `default <https://docs.sentry.io/platforms/python/integrations/default-integrations/>`_ integrations.
  804. :param auto_enabling_integrations: Configures whether `auto-enabling integrations (configuration)
  805. <https://docs.sentry.io/platforms/python/integrations/#available-integrations>`_ should be enabled.
  806. When set to `False`, no auto-enabling integrations will be enabled by default, even if the corresponding
  807. framework/library is detected.
  808. :param default_integrations: Configures whether `default integrations
  809. <https://docs.sentry.io/platforms/python/integrations/default-integrations/>`_ should be enabled.
  810. Setting `default_integrations` to `False` disables all default integrations **as well as all auto-enabling
  811. integrations**, unless they are specifically added in the `integrations` option, described above.
  812. :param before_send: This function is called with an SDK-specific message or error event object, and can return
  813. a modified event object, or `null` to skip reporting the event.
  814. This can be used, for instance, for manual PII stripping before sending.
  815. By the time `before_send` is executed, all scope data has already been applied to the event. Further
  816. modification of the scope won't have any effect.
  817. :param before_send_transaction: This function is called with an SDK-specific transaction event object, and can
  818. return a modified transaction event object, or `null` to skip reporting the event.
  819. One way this might be used is for manual PII stripping before sending.
  820. :param before_breadcrumb: This function is called with an SDK-specific breadcrumb object before the breadcrumb
  821. is added to the scope.
  822. When nothing is returned from the function, the breadcrumb is dropped.
  823. To pass the breadcrumb through, return the first argument, which contains the breadcrumb object.
  824. The callback typically gets a second argument (called a "hint") which contains the original object from
  825. which the breadcrumb was created to further customize what the breadcrumb should look like.
  826. :param transport: Switches out the transport used to send events.
  827. How this works depends on the SDK. It can, for instance, be used to capture events for unit-testing or to
  828. send it through some more complex setup that requires proxy authentication.
  829. :param transport_queue_size: The maximum number of events that will be queued before the transport is forced to
  830. flush.
  831. :param http_proxy: When set, a proxy can be configured that should be used for outbound requests.
  832. This is also used for HTTPS requests unless a separate `https_proxy` is configured. However, not all SDKs
  833. support a separate HTTPS proxy.
  834. SDKs will attempt to default to the system-wide configured proxy, if possible. For instance, on Unix
  835. systems, the `http_proxy` environment variable will be picked up.
  836. :param https_proxy: Configures a separate proxy for outgoing HTTPS requests.
  837. This value might not be supported by all SDKs. When not supported the `http-proxy` value is also used for
  838. HTTPS requests at all times.
  839. :param proxy_headers: A dict containing additional proxy headers (usually for authentication) to be forwarded
  840. to `urllib3`'s `ProxyManager <https://urllib3.readthedocs.io/en/1.24.3/reference/index.html#urllib3.poolmanager.ProxyManager>`_.
  841. :param shutdown_timeout: Controls how many seconds to wait before shutting down.
  842. Sentry SDKs send events from a background queue. This queue is given a certain amount to drain pending
  843. events. The default is SDK specific but typically around two seconds.
  844. Setting this value too low may cause problems for sending events from command line applications.
  845. Setting the value too high will cause the application to block for a long time for users experiencing
  846. network connectivity problems.
  847. :param keep_alive: Determines whether to keep the connection alive between requests.
  848. This can be useful in environments where you encounter frequent network issues such as connection resets.
  849. :param cert_file: Path to the client certificate to use.
  850. If set, supersedes the `CLIENT_CERT_FILE` environment variable.
  851. :param key_file: Path to the key file to use.
  852. If set, supersedes the `CLIENT_KEY_FILE` environment variable.
  853. :param socket_options: An optional list of socket options to use.
  854. These provide fine-grained, low-level control over the way the SDK connects to Sentry.
  855. If provided, the options will override the default `urllib3` `socket options
  856. <https://urllib3.readthedocs.io/en/stable/reference/urllib3.connection.html#urllib3.connection.HTTPConnection>`_.
  857. :param traces_sample_rate: A number between `0` and `1`, controlling the percentage chance a given transaction
  858. will be sent to Sentry.
  859. (`0` represents 0% while `1` represents 100%.) Applies equally to all transactions created in the app.
  860. Either this or `traces_sampler` must be defined to enable tracing.
  861. If `traces_sample_rate` is `0`, this means that no new traces will be created. However, if you have
  862. another service (for example a JS frontend) that makes requests to your service that include trace
  863. information, those traces will be continued and thus transactions will be sent to Sentry.
  864. If you want to disable all tracing you need to set `traces_sample_rate=None`. In this case, no new traces
  865. will be started and no incoming traces will be continued.
  866. :param traces_sampler: A function responsible for determining the percentage chance a given transaction will be
  867. sent to Sentry.
  868. It will automatically be passed information about the transaction and the context in which it's being
  869. created, and must return a number between `0` (0% chance of being sent) and `1` (100% chance of being
  870. sent).
  871. Can also be used for filtering transactions, by returning `0` for those that are unwanted.
  872. Either this or `traces_sample_rate` must be defined to enable tracing.
  873. :param trace_propagation_targets: An optional property that controls which downstream services receive tracing
  874. data, in the form of a `sentry-trace` and a `baggage` header attached to any outgoing HTTP requests.
  875. The option may contain a list of strings or regex against which the URLs of outgoing requests are matched.
  876. If one of the entries in the list matches the URL of an outgoing request, trace data will be attached to
  877. that request.
  878. String entries do not have to be full matches, meaning the URL of a request is matched when it _contains_
  879. a string provided through the option.
  880. If `trace_propagation_targets` is not provided, trace data is attached to every outgoing request from the
  881. instrumented client.
  882. :param functions_to_trace: An optional list of functions that should be set up for tracing.
  883. For each function in the list, a span will be created when the function is executed.
  884. Functions in the list are represented as strings containing the fully qualified name of the function.
  885. This is a convenient option, making it possible to have one central place for configuring what functions
  886. to trace, instead of having custom instrumentation scattered all over your code base.
  887. To learn more, see the `Custom Instrumentation <https://docs.sentry.io/platforms/python/tracing/instrumentation/custom-instrumentation/#define-span-creation-in-a-central-place>`_ documentation.
  888. :param enable_backpressure_handling: When enabled, a new monitor thread will be spawned to perform health
  889. checks on the SDK.
  890. If the system is unhealthy, the SDK will keep halving the `traces_sample_rate` set by you in 10 second
  891. intervals until recovery.
  892. This down sampling helps ensure that the system stays stable and reduces SDK overhead under high load.
  893. This option is enabled by default.
  894. :param enable_db_query_source: When enabled, the source location will be added to database queries.
  895. :param db_query_source_threshold_ms: The threshold in milliseconds for adding the source location to database
  896. queries.
  897. The query location will be added to the query for queries slower than the specified threshold.
  898. :param custom_repr: A custom `repr <https://docs.python.org/3/library/functions.html#repr>`_ function to run
  899. while serializing an object.
  900. Use this to control how your custom objects and classes are visible in Sentry.
  901. Return a string for that repr value to be used or `None` to continue serializing how Sentry would have
  902. done it anyway.
  903. :param profiles_sample_rate: A number between `0` and `1`, controlling the percentage chance a given sampled
  904. transaction will be profiled.
  905. (`0` represents 0% while `1` represents 100%.) Applies equally to all transactions created in the app.
  906. This is relative to the tracing sample rate - e.g. `0.5` means 50% of sampled transactions will be
  907. profiled.
  908. :param profiles_sampler:
  909. :param profiler_mode:
  910. :param profile_lifecycle:
  911. :param profile_session_sample_rate:
  912. :param enable_tracing:
  913. :param propagate_traces:
  914. :param auto_session_tracking:
  915. :param spotlight:
  916. :param instrumenter:
  917. :param _experiments:
  918. """
  919. pass
  920. def _get_default_options():
  921. # type: () -> dict[str, Any]
  922. import inspect
  923. a = inspect.getfullargspec(ClientConstructor.__init__)
  924. defaults = a.defaults or ()
  925. kwonlydefaults = a.kwonlydefaults or {}
  926. return dict(
  927. itertools.chain(
  928. zip(a.args[-len(defaults) :], defaults),
  929. kwonlydefaults.items(),
  930. )
  931. )
  932. DEFAULT_OPTIONS = _get_default_options()
  933. del _get_default_options
  934. VERSION = "2.34.1"