Creating a notifier

The BaseNotifier is an abstract class that provides a basic structure for sending notifications in Airflow using the various on_*__callback. It is intended for providers to extend and customize for their specific needs.

To extend the BaseNotifier class, you will need to create a new class that inherits from it. In this new class, you should override the notify method with your own implementation that sends the notification. The notify method takes in a single parameter, the Airflow context, which contains information about the current task and execution.

You can also set the template_fields attribute to specify which attributes should be rendered as templates.

Here’s an example of how you can create a Notifier class:

  1. from airflow.notifications.basenotifier import BaseNotifier
  2. from my_provider import send_message
  3. class MyNotifier(BaseNotifier):
  4. template_fields = ("message",)
  5. def __init__(self, message):
  6. self.message = message
  7. def notify(self, context):
  8. # Send notification here, below is an example
  9. title = f"Task {context['task_instance'].task_id} failed"
  10. send_message(title, self.message)

Using a notifier

Once you have a notifier implementation, you can use it in your DAG definition by passing it as an argument to the on_*_callbacks. For example, you can use it with on_success_callback or on_failure_callback to send notifications based on the status of a task or a DAG run.

Here’s an example of using the above notifier:

  1. from airflow import DAG
  2. from myprovider.notifier import MyNotifier
  3. from datetime import datetime
  4. with DAG(
  5. dag_id="example_notifier",
  6. start_date=datetime(2022, 1, 1),
  7. schedule_interval=None,
  8. on_success_callback=MyNotifier(message="Success!"),
  9. on_failure_callback=MyNotifier(message="Failure!"),
  10. ):
  11. task = BashOperator(
  12. task_id="example_task",
  13. bash_command="exit 1",
  14. on_success_callback=MyNotifier(message="Task Succeeded!"),
  15. )

For a list of community-managed notifiers, see Notifications.