在我DAG文件中,我定义了一个on_failure_callback()函数,用于在失败的情况下发布一个Slack。
如果我在DAG中为每个运算符指定了on_failure_callback=on_failure_callback(),它就能很好地工作。
有没有办法自动(例如,通过default_args,或者通过我的DAG对象)分派给我所有的操作员?
发布于 2017-09-19 15:46:36
我终于找到了这样做的方法。
您可以将on_failure_callback作为default_args进行传递
class Foo:
@staticmethod
def get_default_args():
"""
Return default args
:return: default_args
"""
default_args = {
'on_failure_callback': Foo.on_failure_callback
}
return default_args
@staticmethod
def on_failure_callback(context):
"""
Define the callback to post on Slack if a failure is detected in the Workflow
:return: operator.execute
"""
operator = SlackAPIPostOperator(
task_id='failure',
text=str(context['task_instance']),
token=Variable.get("slack_access_token"),
channel=Variable.get("slack_channel")
)
return operator.execute(context=context) 发布于 2022-01-05 16:35:26
在此延迟回答,但您可以在DAG的默认值中指定on_failure_callback。您只需编写一个自定义函数,确保它可以在上下文中使用。示例:
def failure_callback(context):
message = [
":red_circle: Task failed",
f"*Dag*: {context['dag_run'].dag_id}",
f"*Run*: {context['dag_run'].run_id}",
f"*Task*: <{context.get('task_instance').log_url}|*{context.get('task_instance').task_id}* failed for execution {context.get('execution_date')}>",
]
# Replace this return with whatever you want
# I usually send a Slack notification here
return "\n".join(message)
with DAG(
...
default_args={
...
"on_failure_callback": failure_callback,
},
) as dag:
...https://stackoverflow.com/questions/45312439
复制相似问题