Sentry for Python: 为每个源代码行添加 "git blame" 类前缀

Sentry for Python: Add "git blame" like prefix to each source code line

如果哨兵中的异常包含像 git blame 那样的信息,那就太好了。

如果我在 sentry 的异常中看到的每一行源代码都有一个像 git blame(日期、提交哈希、作者)这样的前缀,你可以更快地找到相关的提交。

AFAIK 哨兵无法开箱即用。我在哪里以及如何连接到哨兵来获得这个?

请发表评论,说明您对这个问题投反对票的原因。我很好奇也愿意学习。

仅作记录。哨兵团队正在做这样的事情。不完全是,但它确实解决了相同的用例:https://github.com/getsentry/sentry/issues/6547

我建议您尝试 Guthub 插件,它不显示 git blame,但与 Sentry Releases 集成并显示适当的提交和作者 link 到 Github.

https://sentry.io/integrations/github/

回溯由多行代码组成。您可以使用 GitPython 库从 git blame 中为每一行提取信息:

import sys
import traceback


from git import Repo


def commit_info(file_path, line_number):
    for commit, lines in Repo().blame('HEAD', file_path):
        line_number -= len(lines)
        if line_number <= 0:
            return commit.hexsha, commit.committed_datetime, commit.author.name


try:
    raise Exception('error')
except Exception:
    for filename, line_number, _, _ in traceback.extract_tb(sys.exc_info()[2]):
        print filename, line_number, commit_info(filename, line_number)

然后,由您决定如何将此信息发送到 Sentry。一种可能的解决方案是选择上面列表中的一个提交并使用 extra 关键字,让您的记录器为您完成这项工作:

try:
    raise Exception
except Exception:
    commit = choose_one_commit()
    logger.exception('Error', extra={'author': author.name, 'sha': commit.hexsha}) 

此外,您可以使用自己的记录器,它将此 extra 参数添加到所有 .exception().error().critical() 调用。

总的来说,你想实现什么样的行为是比较模糊的,一切皆有可能。但是调用 git blame 是昂贵的并且可能会严重损害您的应用程序的性能。