Prometheus C++ 的使用指南?

Cod*_*tor 13 c++ prometheus

我查看了prometheus-cpp中的语法示例和主要 prometheus 文档中非常相似的 go one,但我不确定我应该如何在我的 C++ 应用程序中使用类似的代码。Go 使用全局变量来保存计数器,C++ 在检测函数中使用本地引用。自动引用意味着我不能轻易地将计数器放入包装器中,但是每次我想增加一个计数器时都需要 10 行的开销是不可接受的。

天真的它看起来像这样:

void SomeClass::a_little_method() {
    auto start = get_accurate_time();

    // actual code that the method
    // uses to do whatever it does
    // in less than ten lines of code

    auto& counter_family = BuildCounter()
            .Name("little_method")
            .Help("little method execution count and duration")
            .Labels({
        {"My Application", "metrics"}
    })
    .Register(*global_registry_pointer);
    auto& call_counter = counter_family.Add({
        {"calls", "count"}
    });
    auto& execution_timer = counter_family.Add({
        {"calls", "duration"}
    });
    call_counter.Increment();
    execution_timer.Increment(get_accurate_time() - start);
}
Run Code Online (Sandbox Code Playgroud)

有比被检测的代码更多的检测。随着更多的东西被检测,情况变得更糟,普罗米修斯指南“每个日志行都应该有一个计数器”意味着每个日志行都会获得 8 或 10 行 prometheus 语句。并且创建了两个局部变量,使用一次,然后销毁。

解决方案一:更多的全局变量

Prometheus-cpp 有它的全局“注册表”对象,所以大概的目的是我只是添加一堆“计数器系列”全局变量,然后是一大堆全局“计数器”变量。这意味着如果 prometheus 初始化失败,程序根本不会运行,但至少每个计数器只设置一次。至少柜台图书馆都在一个地方,所以很容易查看和组织。

解决方案二:暴露 Increment() 方法的包装线程

我可以在一个巨大的方法中声明所有这些自动引用变量,以“while not terminate sleep”调用结束该方法并将其作为线程运行。然后通过一组 Increment 方法公开这些本地计数器变量。但这感觉好像我在违背图书馆作者的意图。

解决方案三:正确操作??

我真的希望每个计数器增量有一行,理想情况下作为可注入/可模拟类的方法。最好使用其他prometheus 包装器持续时间包装器。即使 prometheus 不可用或由于某种原因无法运行,我的程序也应该运行(我没有运行唯一目的是玩 prometheus 的服务器)。

SomeClass::SomeClass(... prometheus...)
SomeClass::wrap_a_little_method() {
    prometheus.observe_duration([&]() {
        a_little_method();
    }
    prometheus.Increment(a_little_method_call_count);
}
Run Code Online (Sandbox Code Playgroud)

(没有 prometheus-cpp 标签,我没有创建一个的代表,抱歉)