prometheus / prometheus/client_python

Allow count_exceptions to add the error type as a label

未关闭
#744 2 条评论 0 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

主要语言
Python
星标
4.4k
派生
876
平均合并
8 天 4 小时
30 天内合并 PR
1

描述

I'd like count_exceptions to add the error type as a label so I can track what errors are occurring against what endpoints for my application.

I'd like to do this via the with method.

from prometheus_client import Counter

ERRORS = Counter(
    'http_request_errors_count',
    'Count of  exceptions that happen during an HTTP request',
    ['method', 'endpoint', 'error']
)

async def error_middleware(request, handler):
    try:
        with ERRORS.count_exceptions(request.method, request.path):
            return await handler(request)
    except SomeHTTPException as e:
        ...

To do this I've created my own custom Counter classes.

from prometheus_client import Counter, context_managers


class CustomExceptionCounter(context_managers.ExceptionCounter):
    def __init__(self, counter, exception, *labels):
        self._counter = counter
        self._exception = exception
        self._labels = labels

    def __exit__(self, typ, value, traceback):
        if isinstance(value, self._exception):
            self._counter.labels(*(*self._labels, typ.__name__)).inc()  # Append exception's name as a label


class CustomCounter(Counter):
    def count_exceptions(self, *labels, exception=Exception):
        return CustomExceptionCounter(self, exception, *labels)


ERRORS = CustomCounter(
    'http_request_errors_count',
    'Count of CancelledError exceptions',
    ['method', 'endpoint', 'error']
)

I think there is a general solution that's backward compatible, I've just not figured it out. Is this something you'd support? I'd be happy to submit a PR if I can figure out how to make this backward compatible.

贡献指南

打开贡献指南

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

调研方向

从 Counter.count_exceptions 和 context_managers.ExceptionCounter 开始,然后跟踪 with 方法如何处理异常类型和标签。定义如何在保留现有调用和行为的同时添加错误标签,并通过向后兼容性测试验证所请求的 endpoint 和异常标签使用场景。

由索引模型根据 Issue 内容生成。

评估

技术栈
python
领域
observability-sre
Issue 类型
功能
难度
4/5
预计耗时
3-5 天
活跃度
停滞
描述清晰度
基本清楚
新手友好度
35/100

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。