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> *first_bucket_location, atomic<double> *sum_location, size_t num_elements)
63 histogram.name = name;
64 histogram.labels = labels;
65 histogram.first_bucket_location = first_bucket_location;
66 histogram.sum_location = sum_location;
67 histogram.num_elements = num_elements;
69 lock_guard<mutex> lock(mu);
70 histograms.push_back(histogram);
73 string Metrics::serialize() const
76 ss.imbue(locale("C"));
79 lock_guard<mutex> lock(mu);
80 for (const auto &name_and_type : types) {
81 if (name_and_type.second == TYPE_GAUGE) {
82 ss << "# TYPE nageru_" << name_and_type.first << " gauge\n";
85 for (const Metric &metric : metrics) {
86 string name = serialize_name(metric.name, metric.labels);
88 if (metric.data_type == DATA_TYPE_INT64) {
89 ss << name << " " << metric.location_int64->load() << "\n";
91 ss << name << " " << metric.location_double->load() << "\n";
94 for (const Histogram &histogram : histograms) {
95 ss << "# TYPE nageru_" << histogram.name << " histogram\n";
98 for (size_t i = 0; i < histogram.num_elements; ++i) {
100 snprintf(buf, sizeof(buf), "%lu", i);
101 vector<pair<string, string>> labels = histogram.labels;
102 labels.emplace_back("le", buf);
104 int64_t val = histogram.first_bucket_location[i].load();
106 ss << serialize_name(histogram.name + "_bucket", labels) << " " << count << "\n";
109 ss << serialize_name(histogram.name + "_sum", histogram.labels) << " " << histogram.sum_location->load() << "\n";
110 ss << serialize_name(histogram.name + "_count", histogram.labels) << " " << count << "\n";