How to Route Alerts by Severity in Python
Map alert severity levels to routing targets and simulate dispatching alerts to on-call pages, email, Slack, or logs.
Python code
36 linesdef main():
# Severity levels with corresponding alert routing targets
routing_map = {
"critical": "call_page",
"high": "call_page",
"medium": "email_team",
"low": "slack_channel",
"info": "log_only"
}
# Simulated alerts with severity
alerts = [
{"name": "cpu_usage", "severity": "critical"},
{"name": "db_connection", "severity": "high"},
{"name": "memory_leak", "severity": "medium"},
{"name": "disk_full", "severity": "low"},
{"name": "cache_miss", "severity": "info"}
]
# Route each alert based on severity
for alert in alerts:
severity = alert["severity"]
target = routing_map.get(severity, "unknown")
# Simulate the routing action
if target == "call_page":
print(f"PAGING on-call for: {alert['name']} ({severity})")
elif target == "email_team":
print(f"EMAIL team about: {alert['name']} ({severity})")
elif target == "slack_channel":
print(f"SLACK channel for: {alert['name']} ({severity})")
else:
print(f"LOG only: {alert['name']} ({severity})")
if __name__ == "__main__":
main()
Output
PAGING on-call for: cpu_usage (critical)
PAGING on-call for: db_connection (high)
EMAIL team about: memory_leak (medium)
SLACK channel for: disk_full (low)
LOG only: cache_miss (info)
How it works
The routing_map dictionary acts as a lookup table that translates each severity string into a concrete destination. The .get(severity, "unknown") call safely returns a fallback when an unexpected severity appears, preventing a KeyError. Iterating over the alerts list keeps the routing logic separate from the alert data, making it easy to add new severities or targets. This pattern mirrors how real incident management systems dispatch alerts through different channels based on priority.
Common mistakes
- Assuming every severity key exists instead of using `.get()` with a default
- Hard-coding routing logic inside the loop instead of using a mapping table
- Forgetting to handle unknown severity values gracefully
Variations
- Use a match statement (`match severity:`) in Python 3.10+ for more explicit case handling
- Store routing targets in a config file or environment variable for dynamic updates
Real-world use cases
- Integrating with PagerDuty or Opsgenie to page on-call engineers only for critical incidents.
- Sending medium-severity issues to a team email list while low-severity warnings go to a Slack channel.
- Building an internal alert router that logs info-level metrics to a database instead of notifying anyone.
Sponsored
More from Observability & SRE
- Adding a Correlation ID to Log Context in Python medium
- Calculate Error Rate from Log Stream in Python easy
- Check if a Timestamp Falls in a Daily Maintenance Window in Python easy
- Export Metrics with OTLP Mock in Python medium
- Generate Mock CPU and Memory Metrics in Python easy
- Generate Prometheus Text Exposition Format in Python easy
Keep learning
Related tutorials and quizzes for this topic.