Files
airflow/dags/test/fail_test.py
T
2025-04-23 15:30:39 +08:00

56 lines
1.6 KiB
Python

from airflow import DAG
from airflow.operators.python_operator import PythonOperator
from datetime import datetime
from airflow.hooks.http_hook import HttpHook
import json
def send_dingding_alert(context):
print('监测到错误')
task_instance = context.get('task_instance')
execution_date = context.get('execution_date').strftime("%Y-%m-%d %H:%M:%S") if context.get(
'execution_date') else "N/A"
message = {
"msgtype": "markdown",
"markdown": {
"title": "Airflow 任务错误告警",
"text": f"""### ⚠️ Airflow 任务失败告警 ⚠️
**DAG**: {task_instance.dag_id}
**任务**: {task_instance.task_id}
**执行时间**: {execution_date}
**日志链接**: [点击查看]({task_instance.log_url})"""
},
"at": {"isAtAll": True}
}
http_hook = HttpHook(method="POST", http_conn_id="dingding_webhook")
http_hook.run(
endpoint="robot/send",
data=json.dumps(message),
headers={"Content-Type": "application/json"}
)
def fail_task():
raise ValueError("This task is designed to fail")
default_args = {
"owner": "airflow",
"retries": 1,
"retry_delay": timedelta(minutes=5),
"on_failure_callback": send_dingding_alert, # 任务失败时触发钉钉告警
}
dag = DAG(
'test_failure_notification',
default_args=default_args,
start_date=datetime(2025, 4, 22),
schedule_interval=None
)
task = PythonOperator(
task_id='failing_task',
python_callable=fail_task,
dag=dag
)