Python结构,发送失败通知

时间:2015-11-17 15:43:13

标签: python exception-handling fabric slack

我一直试图弄清楚当我的结构脚本失败时做什么的最佳方法(例如通过python模块slackbot发送松弛通知消息)。

我已经举了一个例子,我试着在这里做上述事情:

fab_failtest.py my_slackclient.py

您可以通过将两个文件下载到目录,pip install fabricslackbot来运行以上示例,然后运行:

fab --fabfile=fab_failtest.py fail_test1

fab --fabfile=fab_failtest.py fail_test2

(你还必须有一台你可以使用的机器,在这个例子中我mrbluesky@elo上有22上的开放ssh端口

  • fail_test1使用try-except,因此我可以获得异常错误信息等等
  • fail_test2使用try-finally加上一个简单的布尔变量,因此没有可用的异常信息

起初我以为我已经使用了fail_test1示例,但是我已经看到它失败了几次失败后发送松弛消息,我想知道是否存在竞争条件或涉及的东西?我可以开始使用fail_test2,但我真的希望像fail_test1一样访问堆栈跟踪。

有没有更好的方法来做到这一点,例如,在python结构中提供的东西,它在我上面的例子中试图完成的是什么?

2 个答案:

答案 0 :(得分:2)

我不同意你的方法。我坚信更少的代码更好。那是什么意思?一个函数应该做它的名字所说的,不多也不少,如果你必须添加一个全局处理程序,我将它作为一个包装器添加,结构函数很难读取,不需要添加错误处理到混合。随着说:

import sys
import traceback

from fabric.api import task, settings, local, abort
from fabric.decorators import _wrap_as_new
from functools import wraps

HOST = 'elo'
PORT = 22


def alert_on_fail(func):
    @wraps(func)
    def decorated(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except:
            # TODO: add more code here
            exception_type, value, tb_msg = sys.exc_info()
            traceback_msg = traceback.format_exc()
            notify('something went wrong: ' + traceback_msg)
            abort('exiting error!!')
    return _wrap_as_new(func, decorated)


@task
@alert_on_fail
def fail_test(host=HOST, port=PORT):
    notify('fail test', msg_type='info')
    local('''python -c "raise Exception('foobar')"''')
    notify('script ran successfully', msg_type='success')  # this will never run because the function above crashed


@task
@alert_on_fail
def pass_test(host=HOST, port=PORT):
    notify('pass test', msg_type='info')
    local('whoami')
    notify('script ran successfully', msg_type='success')


def notify(msg, **kwargs):
    # DISREGARD THIS
    print 'sent to slack:', msg

输出:

$ fab fail_test
sent to slack: fail test
[localhost] local: python -c "raise Exception('foobar')"
Traceback (most recent call last):
  File "<string>", line 1, in <module>
Exception: foobar

Fatal error: local() encountered an error (return code 1) while executing 'python -c "raise Exception('foobar')"'

Aborting.
sent to slack: something went wrong: Traceback (most recent call last):
  File "/private/tmp/fabfile.py", line 21, in decorated
    return func(*args, **kwargs)
  File "/private/tmp/fabfile.py", line 34, in fail_test
    local('''python -c "raise Exception('foobar')"''')
  File "/usr/local/lib/python2.7/site-packages/fabric/operations.py", line 1198, in local
    error(message=msg, stdout=out, stderr=err)
  File "/usr/local/lib/python2.7/site-packages/fabric/utils.py", line 347, in error
    return func(message)
  File "/usr/local/lib/python2.7/site-packages/fabric/utils.py", line 53, in abort
    sys.exit(msg)
SystemExit: local() encountered an error (return code 1) while executing 'python -c "raise Exception('foobar')"'


Fatal error: exiting error!!

Aborting.
exiting error!!

$ fab pass_test
sent to slack: pass test
[localhost] local: whoami
buzzi
sent to slack: script ran successfully

Done.

您会注意到这些功能现在很容易&#34;阅读,它们是简单的&#34;,所有的错误处理代码都被移到了其他地方。

答案 1 :(得分:0)

我有一个类似的问题问题,我想在脚本失败时发送通知。因此,我决定构建一个软件包Notif,以在脚本使用装饰器失败时发送通知。

这里有我的软件包notif的示例,用于在脚本失败时发送松弛通知:

notif = SlackNotificator(url="webhook_url")
@notification_on_fail(notif=notif, verbose_level='2')
def fail_test():
      print(t)

在此处查看doc

  

我对结构版本1.1的主要启发是

相关问题