10 Metrics global_metrics;
14 string serialize_name(const string &name, const vector<pair<string, string>> &labels)
17 return "nageru_" + name;
21 for (const pair<string, string> &label : labels) {
22 if (!label_str.empty()) {
25 label_str += label.first + "=\"" + label.second + "\"";
27 return "nageru_" + name + "{" + label_str + "}";
32 void Metrics::add(const string &name, const vector<pair<string, string>> &labels, atomic<int64_t> *location, Metrics::Type type)
35 metric.data_type = DATA_TYPE_INT64;
37 metric.labels = labels;
38 metric.location_int64 = location;
40 lock_guard<mutex> lock(mu);
41 metrics.push_back(metric);
42 assert(types.count(name) == 0 || types[name] == type);
46 void Metrics::add(const string &name, const vector<pair<string, string>> &labels, atomic<double> *location, Metrics::Type type)
49 metric.data_type = DATA_TYPE_DOUBLE;
51 metric.labels = labels;
52 metric.location_double = location;
54 lock_guard<mutex> lock(mu);
55 metrics.push_back(metric);
56 assert(types.count(name) == 0 || types[name] == type);
60 void Metrics::add_histogram(const string &name, const vector<pair<string, string>> &labels, atomic<int64_t> *location, size_t num_elements)
63 histogram.name = name;
64 histogram.labels = labels;
65 histogram.location_int64 = location;
66 histogram.num_elements = num_elements;
68 lock_guard<mutex> lock(mu);
69 histograms.push_back(histogram);
72 string Metrics::serialize() const
75 ss.imbue(locale("C"));
78 lock_guard<mutex> lock(mu);
79 for (const auto &name_and_type : types) {
80 if (name_and_type.second == TYPE_GAUGE) {
81 ss << "# TYPE nageru_" << name_and_type.first << " gauge\n";
84 for (const Metric &metric : metrics) {
85 string name = serialize_name(metric.name, metric.labels);
87 if (metric.data_type == DATA_TYPE_INT64) {
88 ss << name << " " << metric.location_int64->load() << "\n";
90 ss << name << " " << metric.location_double->load() << "\n";
93 for (const Histogram &histogram : histograms) {
94 ss << "# TYPE nageru_" << histogram.name << " histogram\n";
96 int64_t sum = 0, count = 0;
97 for (size_t i = 0; i < histogram.num_elements; ++i) {
99 snprintf(buf, sizeof(buf), "%lu", i);
100 vector<pair<string, string>> labels = histogram.labels;
101 labels.emplace_back("le", buf);
103 int64_t val = histogram.location_int64[i].load();
106 ss << serialize_name(histogram.name + "_bucket", labels) << " " << count << "\n";
109 ss << serialize_name(histogram.name + "_sum", histogram.labels) << " " << sum << "\n";
110 ss << serialize_name(histogram.name + "_count", histogram.labels) << " " << count << "\n";