Celery for Python
Learn how to set up Sentry in your Celery app, capture your first events and traces, and view them in Sentry.
If you're using stream mode, this page's references to "transaction" should be applied to service spans instead. See Streamed Spans for more information.
You need:
- A Sentry account and project
- Your application up and running
- Celery:
4.4.7+(SDK <3.0)5.0.0+(SDK 3.0+)
- Python:
3.6+(SDK <3.0)3.7+(SDK 3.0+)
Run the command for your preferred package manager to add the Sentry SDK to your application:
pip install "sentry-sdk"
pip install "sentry-sdk"
uv add "sentry-sdk"
poetry add "sentry-sdk"
This guide requires sentry-sdk version 2.70.0 or later. If you already have the SDK installed, upgrade it with pip install --upgrade sentry-sdk.
Error Monitoring starts working as soon as you call sentry_sdk.init(). Logs and Application Metrics need no extra configuration when using sentry_sdk.logger and sentry_sdk.metrics, and you'll learn how to send them in steps #3 and #4. This guide also enables Tracing and Profiling.
Configuration should happen as early as possible in your application's lifecycle.
The init snippets also turn on:
- Collection of task arguments in error events: via
data_collection - Tracing: via
traces_sample_rate - Profiling: via
profile_session_sample_rateandprofile_lifecycle
Don't need a feature? Remove its options from the snippets.
If you have the celery package in your dependencies, the Celery integration will be enabled automatically when you initialize the Sentry SDK.
Make sure that the call to sentry_sdk.init() is loaded on worker startup and not only in the module where your tasks are defined. Otherwise, the initialization may happen too late and events might not get reported.
When using Celery without Django, you'll need to initialize the Sentry SDK in both your application and the Celery worker processes spawned by the Celery daemon.
tasks.pyfrom celery import Celery, signals
import sentry_sdk
# Initializing Celery
app = Celery("tasks", broker="...")
# Initialize Sentry SDK on Celery startup
@signals.celeryd_init.connect
def init_sentry(**_kwargs):
sentry_sdk.init(
dsn="___PUBLIC_DSN___",
# Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
data_collection={
"queues": True,
},
# Enables Tracing.
# Set to 1.0 to capture 100% of spans for tracing.
# We recommend reducing this value in production.
traces_sample_rate=1.0,
# Enables Profiling.
# Set to 1.0 to profile 100% of sessions.
profile_session_sample_rate=1.0,
# Profiles are collected while a transaction is active.
profile_lifecycle="trace",
)
# Task definitions go here
@app.task
def add(x, y):
return x + y
from celery import Celery, signals
import sentry_sdk
# Initializing Celery
app = Celery("tasks", broker="...")
# Initialize Sentry SDK on Celery startup
@signals.celeryd_init.connect
def init_sentry(**_kwargs):
sentry_sdk.init(
dsn="___PUBLIC_DSN___",
# Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
data_collection={
"queues": True,
},
# Enables Tracing.
# Set to 1.0 to capture 100% of spans for tracing.
# We recommend reducing this value in production.
traces_sample_rate=1.0,
# Enables Profiling.
# Set to 1.0 to profile 100% of sessions.
profile_session_sample_rate=1.0,
# Profiles are collected while a transaction is active.
profile_lifecycle="trace",
)
# Task definitions go here
@app.task
def add(x, y):
return x + y
The celeryd_init signal is triggered when the Celery daemon starts, before the worker processes are spawned. If you need to initialize Sentry for each individual worker process, use the worker_init signal instead.
main.pyfrom tasks import add
import sentry_sdk
def main():
# Initializing Sentry SDK in our process
sentry_sdk.init(
dsn="___PUBLIC_DSN___",
# Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
data_collection={
"queues": True,
},
# Enables Tracing.
# Set to 1.0 to capture 100% of spans for tracing.
# We recommend reducing this value in production.
traces_sample_rate=1.0,
# Enables Profiling.
# Set to 1.0 to profile 100% of sessions.
profile_session_sample_rate=1.0,
# Profiles are collected while a transaction is active.
profile_lifecycle="trace",
)
# Enqueueing a task to be processed by Celery
with sentry_sdk.start_transaction(name="calling-a-celery-task"):
# or sentry_sdk.traces.start_span(name="calling-a-celery-task", parent_span=None) in stream mode
result = add.delay(4, 4)
if __name__ == "__main__":
main()
from tasks import add
import sentry_sdk
def main():
# Initializing Sentry SDK in our process
sentry_sdk.init(
dsn="___PUBLIC_DSN___",
# Check https://docs.sentry.io/platforms/python/data-management/data-collected/ to configure what data is collected
data_collection={
"queues": True,
},
# Enables Tracing.
# Set to 1.0 to capture 100% of spans for tracing.
# We recommend reducing this value in production.
traces_sample_rate=1.0,
# Enables Profiling.
# Set to 1.0 to profile 100% of sessions.
profile_session_sample_rate=1.0,
# Profiles are collected while a transaction is active.
profile_lifecycle="trace",
)
# Enqueueing a task to be processed by Celery
with sentry_sdk.start_transaction(name="calling-a-celery-task"):
# or sentry_sdk.traces.start_span(name="calling-a-celery-task", parent_span=None) in stream mode
result = add.delay(4, 4)
if __name__ == "__main__":
main()
If you're using Celery with Django in a typical setup, have initialized the SDK in your settings.py file (as described in the Django integration documentation), and have your Celery configured to use the same settings as config_from_object, there's no need to initialize the Celery SDK separately.
To further customize your setup, review the Options section below.
Sentry automatically captures errors and exceptions raised in your Celery tasks and reports them as issues.
To learn how to manually report issues, see Capturing Errors.
The Sentry SDK automatically creates spans for your Celery tasks, and propagates the trace from the code that enqueues a task to the worker that runs it.
You can also manually capture performance data – see Custom Instrumentation to learn more.
Distributed tracing extends the trace from the code running your Celery task to include the code that initiated the task.
You can disable this globally with the propagate_traces option, documented in the options below. If you set propagate_traces to False, all Celery tasks will start their own trace.
If you want to have more fine-grained control over trace distribution, you can override the propagate_traces option by passing the sentry-propagate-traces header when starting the Celery task:
The CeleryIntegration does not utilize the traces_sample_rate config option for deciding if a trace should be propagated into a Celery task.
import sentry_sdk
# Enable global distributed traces (this is the default, just to be explicit)
sentry_sdk.init(
# same as above
integrations=[
CeleryIntegration(
propagate_traces=True
),
],
)
# This will propagate the trace:
my_task_a.delay("some parameter")
# This will propagate the trace:
my_task_b.apply_async(
args=("some_parameter", )
)
# This will NOT propagate the trace. The task will start its own trace:
my_task_b.apply_async(
args=("some_parameter", ),
headers={"sentry-propagate-traces": False},
)
# Note: overriding the tracing behaviour using `task_x.delay()` is not possible.
import sentry_sdk
# Enable global distributed traces (this is the default, just to be explicit)
sentry_sdk.init(
# same as above
integrations=[
CeleryIntegration(
propagate_traces=True
),
],
)
# This will propagate the trace:
my_task_a.delay("some parameter")
# This will propagate the trace:
my_task_b.apply_async(
args=("some_parameter", )
)
# This will NOT propagate the trace. The task will start its own trace:
my_task_b.apply_async(
args=("some_parameter", ),
headers={"sentry-propagate-traces": False},
)
# Note: overriding the tracing behaviour using `task_x.delay()` is not possible.
Use sentry_sdk.logger to send structured logs at different levels. You can include searchable attributes with each message.
To capture records from Python's standard-library logging module or Loguru, configure capture_sentry_logs=True on the corresponding integration. See the standard logging and Loguru integration guides.
See Set Up Logs for all available logging methods and formatting options.
import sentry_sdk
sentry_sdk.logger.info("Order processed {order_id}", order_id="order-123")
sentry_sdk.logger.warning("Rate limit reached", attributes={"endpoint": "/api/orders"})
import sentry_sdk
sentry_sdk.logger.info("Order processed {order_id}", order_id="order-123")
sentry_sdk.logger.warning("Rate limit reached", attributes={"endpoint": "/api/orders"})
Use sentry_sdk.metrics to send counters, gauges, and distributions from your app. Metrics are enabled by default after you initialize the SDK.
See Set Up Metrics for all available metric types and configuration options.
import sentry_sdk
sentry_sdk.metrics.count("checkout.failed", 1)
sentry_sdk.metrics.gauge("active_connections", 42)
sentry_sdk.metrics.distribution("api_latency", 187, unit="millisecond")
import sentry_sdk
sentry_sdk.metrics.count("checkout.failed", 1)
sentry_sdk.metrics.gauge("active_connections", 42)
sentry_sdk.metrics.distribution("api_latency", 187, unit="millisecond")
Let's test your setup and confirm that data reaches your Sentry project.
Add a task that raises an exception, then call debug_sentry.delay() from a running Celery worker:
@app.task
def debug_sentry():
1 / 0
@app.task
def debug_sentry():
1 / 0
Now, head over to your project on Sentry.io to view the collected data (it takes a couple of moments for the data to appear).
In stream mode, these options still work as described, but apply to service spans instead of transactions.
To set options on CeleryIntegration to change its behavior, add it explicitly to your sentry_sdk.init():
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
sentry_sdk.init(
# same as above
integrations=[
CeleryIntegration(
monitor_beat_tasks=True,
exclude_beat_tasks=[
"unimportant-task",
"payment-check-.*"
],
),
],
)
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
sentry_sdk.init(
# same as above
integrations=[
CeleryIntegration(
monitor_beat_tasks=True,
exclude_beat_tasks=[
"unimportant-task",
"payment-check-.*"
],
),
],
)
You can pass the following keyword arguments to CeleryIntegration():
propagate_traces
| Type | bool |
|---|---|
| Default | True |
Propagate Sentry tracing information to the Celery task. This makes it possible to link Celery task errors to the function that triggered the task.
If this is set to False:
- errors in Celery tasks won't be matched to the triggering function.
- your Celery tasks will start a new trace and won't be connected to the trace in the calling function.
See Distributed Traces to learn how to get more fine-grained control over distributed tracing in Celery tasks.
monitor_beat_tasks
| Type | bool |
|---|---|
| Default | False |
Turn auto-instrumentation on or off for Celery Beat tasks using Sentry Crons.
See Celery Beat Auto Discovery to learn more.
exclude_beat_tasks
| Type | list[str] |
|---|---|
| Default | None |
A list of Celery Beat tasks that should be excluded from auto-instrumentation using Sentry Crons. Only applied if monitor_beat_tasks is set to True.
The list can contain strings with the names of tasks in the Celery Beat schedule to be excluded. It can also include regular expressions to match multiple tasks. For example, if you include "payment-check-.*" every task starting with payment-check- will be excluded from auto-instrumentation.
See Celery Beat Auto Discovery to learn more.
At this point, you should have integrated Sentry into your Celery application. Here's what to explore next:
- Explore practical guides on what to monitor, log, track, and investigate after setup
- Set up Agent Tracing to monitor your AI systems
- Learn how to manually capture errors
Our documentation is open source and available on GitHub. Your contributions are welcome, whether fixing a typo (drat!) or suggesting an update ("yeah, this would be better").