diff --git a/dags/test/fail_test.py b/dags/test/fail_test.py index bb515ac..65228ae 100644 --- a/dags/test/fail_test.py +++ b/dags/test/fail_test.py @@ -1,12 +1,50 @@ from airflow import DAG from airflow.operators.python_operator import PythonOperator from datetime import datetime +from airflow.providers.http.hooks.http.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 )