Prometheus 指标集成到 C++:prometheus-cpp 库

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Prometheus 指标集成到 C++:prometheus-cpp 库



在现代软件开发中,监控已成为生产系统不可或缺的一部分。Prometheus 是最流行的指标收集和分析解决方案之一。如果您使用 C++ 编写代码并希望为应用程序添加监控功能,prometheus-cpp 库正是您所需要的。它完全支持 Prometheus 指标类型,并允许您通过 HTTP 轻松导出这些指标。



什么是 prometheus-cpp?



prometheus-cpp 是一个 C++ 客户端库,实现了 Prometheus 指标导出协议。它支持所有主要的指标类型:Counter、Gauge、Histogram 和 Summary。该库使用现代 C++(C++11 及以上版本)编写,没有外部依赖(除了标准库和用于 HTTP 服务器的 libcurl),并且得到了社区的积极维护。



安装



最简单的安装方式是通过 vcpkg 或 Conan。对于 vcpkg,请执行:



vcpkg install prometheus-cpp


如果您更喜欢手动构建,请克隆仓库并使用 CMake:



git clone https://github.com/jupp0r/prometheus-cpp.gitcd prometheus-cppmkdir build && cd buildcmake ..make -j4sudo make install


核心概念



该库围绕以下组件构建:



  • Registry — 存储应用程序所有指标的注册表。
  • Counter — 只能递增的计数器(例如,请求数量)。
  • Gauge — 可以增加或减少的值(例如,活跃连接数)。
  • Histogram — 用于测量值分布情况的直方图(例如,响应时间)。
  • Summary — 分位数估计(类似于直方图,但计算精确的百分位数)。


示例:创建 Counter 和 Gauge



让我们看一个简单的例子——一个 HTTP 服务器,它统计请求数量并跟踪活跃连接数。



#include <prometheus/counter.h>#include <prometheus/gauge.h>#include <prometheus/registry.h>#include <prometheus/exposer.h>

int main() { // 创建指标注册表 auto registry = std::make_shared<prometheus::Registry>();

// 创建 Counter 系列 auto& counter_family = prometheus::BuildCounter() .Name("http_requests_total") .Help("Total number of HTTP requests") .Register(*registry);

// 添加标签 "method",值为 "GET" auto& http_requests = counter_family.Add({{"method", "GET"}});

// 创建 Gauge 系列 auto& gauge_family = prometheus::BuildGauge() .Name("active_connections") .Help("Number of active connections") .Register(*registry);

auto& active_connections = gauge_family.Add({});

// 在端口 8080 上导出指标 prometheus::Exposer exposer("0.0.0.0:8080"); exposer.RegisterCollectable(registry);

// 模拟工作 while (true) { http_requests.Increment(); // 计数器 +1 active_connections.Set(42); // 设置值为 42 std::this_thread::sleep_for(std::chrono::seconds(1)); }

return 0;}


示例:用于响应时间的 Histogram



直方图对于测量延迟非常有用。定义响应时间的桶:



#include <prometheus/histogram.h>

// 创建直方图,桶为:0.1, 0.5, 1.0, 2.5, 5.0 秒auto& histogram_family = prometheus::BuildHistogram() .Name("http_request_duration_seconds") .Help("Request latency in seconds") .Register(*registry);

auto& request_duration = histogram_family.Add(

推荐