diff --git a/sentry_sdk/integrations/rq.py b/sentry_sdk/integrations/rq.py index acff045358..f32e2c5871 100644 --- a/sentry_sdk/integrations/rq.py +++ b/sentry_sdk/integrations/rq.py @@ -35,6 +35,15 @@ DEFAULT_TRANSACTION_NAME = "unknown RQ task" +JOB_PROPERTY_TO_ATTRIBUTE = { + "id": "messaging.message.id", +} + +QUEUE_PROPERTY_TO_ATTRIBUTE = { + "name": "messaging.destination.name", +} + + class RqIntegration(Integration): identifier = "rq" origin = f"auto.queue.{identifier}" @@ -54,8 +63,8 @@ def setup_once(): old_perform_job = Worker.perform_job @ensure_integration_enabled(RqIntegration, old_perform_job) - def sentry_patched_perform_job(self, job, *args, **kwargs): - # type: (Any, Job, *Queue, **Any) -> bool + def sentry_patched_perform_job(self, job, queue, *args, **kwargs): + # type: (Any, Job, Queue, *Any, **Any) -> bool with sentry_sdk.new_scope() as scope: try: transaction_name = job.func_name or DEFAULT_TRANSACTION_NAME @@ -76,9 +85,9 @@ def sentry_patched_perform_job(self, job, *args, **kwargs): name=transaction_name, source=TRANSACTION_SOURCE_TASK, origin=RqIntegration.origin, - attributes=_prepopulate_attributes(job), + attributes=_prepopulate_attributes(job, queue), ): - rv = old_perform_job(self, job, *args, **kwargs) + rv = old_perform_job(self, job, queue, *args, **kwargs) if self.is_horse: # We're inside of a forked process and RQ is @@ -169,9 +178,18 @@ def _capture_exception(exc_info, **kwargs): sentry_sdk.capture_event(event, hint=hint) -JOB_PROPERTY_TO_ATTRIBUTE = {} +def _prepopulate_attributes(job, queue): + # type: (Job, Queue) -> dict[str, Any] + attributes = { + "messaging.system": "rq", + } + + for prop, attr in JOB_PROPERTY_TO_ATTRIBUTE.items(): + if getattr(job, prop, None) is not None: + attributes[attr] = getattr(job, prop) + for prop, attr in QUEUE_PROPERTY_TO_ATTRIBUTE.items(): + if getattr(queue, prop, None) is not None: + attributes[attr] = getattr(queue, prop) -def _prepopulate_attributes(job): - attributes = {} return attributes diff --git a/tests/integrations/rq/test_rq.py b/tests/integrations/rq/test_rq.py index dba072766d..1a9ad55fc3 100644 --- a/tests/integrations/rq/test_rq.py +++ b/tests/integrations/rq/test_rq.py @@ -165,7 +165,12 @@ def test_tracing_enabled( assert error_event["transaction"] == "tests.integrations.rq.test_rq.crashing_job" assert transaction["transaction"] == "tests.integrations.rq.test_rq.crashing_job" - assert transaction["contexts"]["trace"] == error_event["contexts"]["trace"] + for trace_key in error_event["contexts"]["trace"]: + assert trace_key in transaction["contexts"]["trace"] + assert ( + error_event["contexts"]["trace"][trace_key] + == transaction["contexts"]["trace"][trace_key] + ) def test_tracing_disabled(