设置定时任务监控
Sentry Crons 允许你监控应用程序中任何计划的、重复运行的任务的运行时间和性能。
一旦实现,它将允许你获取警报和指标,以帮助你解决错误、检测超时并防止服务中断。
如果你使用 Celery Beat 来运行定期任务,请查看我们的Celery Beat 自动发现文档。
使用 Python SDK 监控定期任务,并在任务错过(或未在预期时间启动)、由于运行时问题(如错误)失败,或因超出最大运行时间而失败时通知你。
使用 monitor
装饰器包装你的任务:
import sentry_sdk
from sentry_sdk.crons import monitor
# Add the @monitor decorator to your task
@monitor(monitor_slug='<monitor-slug>')
def tell_the_world():
print('My scheduled task...')
或者,monitor
可以作为上下文管理器使用:
import sentry_sdk
from sentry_sdk.crons import monitor
def tell_the_world():
with monitor(monitor_slug='<monitor-slug>'):
print('My scheduled task...')
自 SDK 版本 1.44.1
起,你可以使用 monitor
来注解异步函数。
你可以使用代码而不是在 Sentry.io 中创建和配置它们 来创建和更新监控。如果监控在 Sentry 中尚不存在,它将被创建。
要创建或更新监控,请使用上面提到的 monitor
并传入你的监控配置作为 monitor_config
。这需要 SDK 版本 1.45.0
或更高版本。
# All keys except `schedule` are optional
monitor_config = {
"schedule": {"type": "crontab", "value": "0 0 * * *"},
"timezone": "Europe/Vienna",
# If an expected check-in doesn't come in `checkin_margin`
# minutes, it'll be considered missed
"checkin_margin": 10,
# The check-in is allowed to run for `max_runtime` minutes
# before it's considered failed
"max_runtime": 10,
# It'll take `failure_issue_threshold` consecutive failed
# check-ins to create an issue
"failure_issue_threshold": 5,
# It'll take `recovery_threshold` OK check-ins to resolve
# an issue
"recovery_threshold": 5,
}
@monitor(monitor_slug='<monitor-slug>', monitor_config=monitor_config)
def tell_the_world():
print('My scheduled task...')
如果你使用的是 手动签入,你可以将你的 monitor_config
传递给 capture_checkin
调用:
check_in_id = capture_checkin(
monitor_slug='<monitor-slug>',
status=MonitorStatus.IN_PROGRESS,
monitor_config=monitor_config,
)
签入监控允许你通过捕获两个签入来跟踪任务的进度:一个在任务开始时,另一个在任务结束时。这种两步过程允许 Sentry 在任务未按预期启动(错过)或超出其最大运行时间(失败)时通知你。
如果你使用 monitor
装饰器/上下文管理器,SDK 将会自动为包装的代码创建签入。
from sentry_sdk.crons import capture_checkin
from sentry_sdk.crons.consts import MonitorStatus
check_in_id = capture_checkin(
monitor_slug='<monitor-slug>',
status=MonitorStatus.IN_PROGRESS,
)
# Execute your task here...
capture_checkin(
monitor_slug='<monitor-slug>',
check_in_id=check_in_id,
status=MonitorStatus.OK,
)
当你的重复任务未能签入(错过)、超出其配置的最大运行时间(失败)或手动报告失败时,Sentry 将会创建一个带有标签的错误事件到你的监控中。
要接收这些事件的警报:
- 在侧边栏中导航到 警报。
- 创建一个新的警报并选择“错误”下的“Issues”作为警报类型。
- 配置你的警报并定义一个过滤匹配:
事件的标签匹配 {key} {match} {value}
。
示例:事件的标签匹配 monitor.slug 等于 my-monitor-slug-here
了解更多内容请参阅 问题警报配置。
Crons 对签到实施速率限制以防止滥用和资源过度使用。具体来说,每个现有监控环境每分钟最多只能发送 6 个签到。此限制按项目强制执行,意味着该速率限制适用于给定项目中的所有监控环境。您可以在 Usage Stats 页面检查是否有任何签到被丢弃。
为了避免签到被丢弃,重要的是要高效地管理和分配签到,使其在速率限制内。这将有助于保持准确的监控,并确保所有关键