繁体   English   中英

避免 email 洪水。 在 Python 警报

[英]Avoid email flood. in Python Alerting

如果任务未处于运行状态,我有一个脚本将发送 email。 此脚本每 5 分钟运行一次。

for task_list in status['tasks']:
        if task_list['state'] != 'RUNNING':
            alert_email(connector+'-task-'+str(task_list['id'])+'-status-'+task_list['state'])

我正在寻找的是避免淹没 email。因为出现故障可能无法在接下来的 1 小时左右内修复。 只想发送 1 email 而不是 12 封电子邮件。 我将不胜感激任何想法。

在通过电子邮件发送警报之前,我正在考虑在已发送目录中编写警报。 下次仅当 md5sum 与发送目录中写入的警报不匹配或发送目录为空时才会发送警报。

使用 Boolean 标志!

alert_sent = False
for task_list in status['tasks']:
    if task_list['state'] != 'RUNNING' and not alert_sent:
        alert_email(connector+'-task-'+str(task_list['id'])+'-status-'+task_list['state'])
        alert_sent = True

alert_sent标志最初设置为False 当发送警报 email 时,该标志设置为True ,因此不会为任务列表的 rest 发送进一步的警报。

更新:

import os

sent_dir = 'sent'
if not os.path.exists(sent_dir):
    os.makedirs(sent_dir)

for task_list in status['tasks']:
    task_id = str(task_list['id'])
    state = task_list['state']
    filename = os.path.join(sent_dir, f"{task_id}-{state}.txt")
    if state != 'RUNNING' and not os.path.exists(filename):
        alert_email(connector+'-task-'+task_id+'-status-'+state)
        with open(filename, 'w') as f:
            f.write("Sent alert for task %s in state %s" % (task_id, state))

现在脚本将检查名为 sent 的目录是否存在。 如果没有,则创建该目录。 然后,对于列表中的每个任务,脚本根据任务 ID 和 state 生成一个文件名。如果任务不在运行中 state 并且相应的文件不存在,则发送警报并创建一个文件存储警报的 state。

如果任务 state 发生变化(例如,从“FAILED”变为“RUNNING”),相应的文件将被删除,下次脚本运行时,如果 state 不是“RUNNING”,它将发送另一个警报。

更新#2:

import time

alert_sent_time = 0
time_threshold = 300 # 5 minutes in seconds
for task_list in status['tasks']:
    if task_list['state'] != 'RUNNING' and time.time() - alert_sent_time > time_threshold:
        alert_email(connector+'-task-'+str(task_list['id'])+'-status-'+task_list['state'])
        alert_sent_time = time.time()

现在它将在 5 分钟后自动重置(如您在帖子中所述)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM