celery task 异常捕获的两种方式.(sentry, mail)

捕获celery task异常的两种方式, sentry, mail

sentry (sentry 记录异常.)
import sentry_sdk
from sentry_sdk.integrations.celery import CeleryIntegration
sentry_sdk.init(
dsn="", # dsn地址.
integrations=[CeleryIntegration()],
# Set traces_sample_rate to 1.0 to capture 100%
# of transactions for performance monitoring.
# We recommend adjusting this value in production,
traces_sample_rate=1.0,
)
mail (捕获异常, 发送邮件.)
import smtplib
import traceback
from email.header import Header
from email.mime.text import MIMEText
# 第三方 SMTP 服务
mail_host = "" # 设置服务器
mail_user = "" # 用户名
mail_pass = "" # 密码
sender = ""
receivers = [""] # 接收邮件, 设置邮箱
def celery_exception_decorator(task):
def decorator(*args, **kwargs):
try:
task(*args, **kwargs)
except Exception:
celery_exception_trace_info(task.__name__, str(traceback.format_exc()))
return decorator
def celery_exception_trace_info(name, info):
message = MIMEText('{}: {}'.format(name, info), 'plain', 'utf-8')
message['From'] = Header("CJ 运维组", 'utf-8')
message['To'] = Header("CJ 开发组", 'utf-8')
subject = 'celery 任务异常'
message['Subject'] = Header(subject, 'utf-8')
try:
smtp_obj = smtplib.SMTP()
smtp_obj.connect(mail_host, 25) # 25 为 SMTP 端口号
smtp_obj.login(mail_user, mail_pass)
smtp_obj.sendmail(sender, receivers, message.as_string())
print("邮件发送成功")
except smtplib.SMTPException:
print("Error: 无法发送邮件")
#### celery task 装饰器, 对任务进行装饰即可.
posted @   德克斯特的实验室  阅读(182)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示