Monitoring C++ Applications: metrics Library for Collecting Metrics

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Monitoring C++ Applications with the metrics Library



When developing high-load and mission-critical systems in C++, high-quality monitoring is essential. Performance tracking, bottleneck detection, and rapid incident response are key tasks for DevOps and developers. The metrics library (also known as cppmetrics) provides a lightweight and efficient way to collect, aggregate, and export metrics directly from C++ code.



In this article, we will explore the library's main features, its architecture, show usage examples, and explain how to integrate it with data collection systems such as Prometheus.



What is the metrics Library?



metrics is a header-only library for C++ (C++11 and later) that implements popular metric types from Dropwizard Metrics (Java). It includes:



  • Counters — for counting events (e.g., number of requests).
  • Gauges — for instantaneous values (current CPU load, queue size).
  • Histograms — for analyzing value distributions (response time, packet size).
  • Timers — a combination of a counter and a histogram for measuring operation duration.
  • Meters — measure the rate of events (requests per second).


The library supports thread safety, configurable sampling reservoirs (e.g., exponentially decaying), and metric export in JSON, Prometheus, and Graphite formats.



Installation and Setup



Since the library is header-only, installation consists of copying the header files into your project. You can use CMake FetchContent or simply copy the metrics folder into your include directory:



#include <metrics/metrics.hpp>


For Prometheus support, you will also need to install prometheus-cpp (optional).



Usage Example: Basic Metrics



Let's consider a simple HTTP server that counts requests and measures their processing time.



#include <metrics/metrics.hpp>#include <iostream>#include <thread>#include <chrono>

using namespace metrics;

// Create a metrics registryMetricsRegistry registry("my_app");

// Define a counter and a timerCounter& request_counter = registry.counter("http.requests.total");Timer& request_timer = registry.timer("http.requests.duration");

void handle_request() { auto context = request_timer.create_context(); // start the timer request_counter.increment(); // increment the counter

// Simulate processing std::this_thread::sleep_for(std::chrono::milliseconds(rand() % 100));

// Time is automatically recorded when context is destroyed}

int main() { for (int i = 0; i < 100; ++i) { handle_request(); }

// Output metrics to console (JSON) std::cout << registry.report_json() << std::endl; return 0;}


As a result, you will get JSON with the counter and the 50th, 75th, 95th, and 99th percentiles of processing time.



Exporting Metrics to Prometheus



For integration with Prometheus, the library provides a separate module metrics_prometheus. Example of setting up an endpoint:



#include <metrics/metrics.hpp>#include <metrics/prometheus/prometheus_collector.hpp>#include <metrics/prometheus/prometheus_server.hpp>

using namespace metrics;

int main() { MetricsRegistry registry("my_service"); // ... register metrics ...

// Create an HTTP server on port 8080 PrometheusServer server(registry, 8080); server.start();

std::cout << "Prometheus metrics available at http://localhost:8080/metrics" << std::endl; return 0;}


After starting the server, Prometheus will be able to scrape metrics from the specified endpoint.



Advanced Features



The library supports metric labeling for flexible filtering and aggregation. For example, you can add labels to an HTTP request counter:



auto& counter = registry.counter("http_requests_total", {{"method", "GET"}, {"endpoint", "/api/v1/users"}});counter.increment();


Additionally, you can configure custom sampling reservoirs for histograms. The default is an exponentially decaying reservoir, but you can use a uniform reservoir or implement your own.



Conclusion



The metrics library for C++ is a powerful and flexible tool for application monitoring. It provides all the necessary metric types, thread safety, and easy integration with popular monitoring systems. Whether you are developing a microservice, a game server, or an embedded system, metrics will help you gain insight into your application's behavior and performance.



Try the library in your next C++ project and see how easy it is to add observability to your code!

Recommendations