]> git.sesse.net Git - nageru/blob - metrics.h
519cb80f694c03756aaa34d5d809eaa1c569a722
[nageru] / metrics.h
1 #ifndef _METRICS_H
2 #define _METRICS_H 1
3
4 // A simple global class to keep track of metrics export in Prometheus format.
5 // It would be better to use a more full-featured Prometheus client library for this,
6 // but it would introduce a dependency that is not commonly packaged in distributions,
7 // which makes it quite unwieldy. Thus, we'll package our own for the time being.
8
9 #include <atomic>
10 #include <mutex>
11 #include <string>
12 #include <map>
13 #include <vector>
14
15 class Metrics {
16 public:
17         enum Type {
18                 TYPE_COUNTER,
19                 TYPE_GAUGE,
20         };
21
22         void add(const std::string &name, std::atomic<int64_t> *location, Type type = TYPE_COUNTER)
23         {
24                 add(name, {}, location, type);
25         }
26
27         void add(const std::string &name, std::atomic<double> *location, Type type = TYPE_COUNTER)
28         {
29                 add(name, {}, location, type);
30         }
31
32         void add(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, std::atomic<int64_t> *location, Type type = TYPE_COUNTER);
33         void add(const std::string &name, const std::vector<std::pair<std::string, std::string>> &labels, std::atomic<double> *location, Type type = TYPE_COUNTER);
34
35         std::string serialize() const;
36
37 private:
38         enum DataType {
39                 DATA_TYPE_INT64,
40                 DATA_TYPE_DOUBLE,
41         };
42
43         struct Metric {
44                 DataType data_type;
45                 std::string name;
46                 std::vector<std::pair<std::string, std::string>> labels;
47                 union {
48                         std::atomic<int64_t> *location_int64;
49                         std::atomic<double> *location_double;
50                 };
51         };
52
53         mutable std::mutex mu;
54         std::map<std::string, Type> types;
55         std::vector<Metric> metrics;
56 };
57
58 extern Metrics global_metrics;
59
60 #endif  // !defined(_METRICS_H)