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 @ 2023-03-08 10:00  德克斯特的实验室  阅读(129)  评论(0编辑  收藏  举报