]> git.sesse.net Git - nageru/blob - metrics.cpp
Mark the appropriate metrics as gauges.
[nageru] / metrics.cpp
1 #include "metrics.h"
2
3 #include <locale>
4 #include <sstream>
5
6 using namespace std;
7
8 Metrics global_metrics;
9
10 void Metrics::register_int_metric(const string &name, atomic<int64_t> *location, Metrics::Type type)
11 {
12         lock_guard<mutex> lock(mu);
13         int_metrics.emplace(name, Metric<int64_t>{ type, location });
14 }
15
16 void Metrics::register_double_metric(const string &name, atomic<double> *location, Metrics::Type type)
17 {
18         lock_guard<mutex> lock(mu);
19         double_metrics.emplace(name, Metric<double>{ type, location });
20 }
21
22 string Metrics::serialize() const
23 {
24         stringstream ss;
25         ss.imbue(locale("C"));
26         ss.precision(20);
27         ss << scientific;
28
29         lock_guard<mutex> lock(mu);
30         for (const auto &key_and_value : int_metrics) {
31                 if (key_and_value.second.type == TYPE_GAUGE) {
32                         ss << "# TYPE nageru_" << key_and_value.first << " gauge\n";
33                 }
34                 ss << "nageru_" << key_and_value.first << " " << key_and_value.second.location->load() << "\n";
35         }
36         for (const auto &key_and_value : double_metrics) {
37                 if (key_and_value.second.type == TYPE_GAUGE) {
38                         ss << "# TYPE nageru_" << key_and_value.first << " gauge\n";
39                 }
40                 ss << "nageru_" << key_and_value.first << " " << key_and_value.second.location->load() << "\n";
41         }
42
43         return ss.str();
44 }