Skip to content

Commit 7c24a37

Browse files
author
Mike Aizatsky
committed
supporting multiple adds with same labels. Fixes issue #75
1 parent 57f4ce1 commit 7c24a37

File tree

2 files changed

+25
-6
lines changed

2 files changed

+25
-6
lines changed

include/prometheus/family.h

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -67,14 +67,26 @@ T& Family<T>::Add(const std::map<std::string, std::string>& labels,
6767
}
6868
#endif
6969

70-
std::lock_guard<std::mutex> lock{mutex_};
7170
auto hash = hash_labels(labels);
72-
auto metric = new T(std::forward<Args>(args)...);
71+
std::lock_guard<std::mutex> lock{mutex_};
72+
auto metrics_iter = metrics_.find(hash);
73+
74+
if (metrics_iter != metrics_.end()) {
75+
#ifndef NDEBUG
76+
auto labels_iter = labels_.find(hash);
77+
assert(labels_iter != labels_.end());
78+
const auto &old_labels = labels_iter->second;
79+
assert(labels == old_labels);
80+
#endif
81+
return *metrics_iter->second;
82+
} else {
83+
auto metric = new T(std::forward<Args>(args)...);
84+
metrics_.insert(std::make_pair(hash, std::unique_ptr<T>{metric}));
85+
labels_.insert({hash, labels});
86+
labels_reverse_lookup_.insert({metric, hash});
87+
return *metric;
88+
}
7389

74-
metrics_.insert(std::make_pair(hash, std::unique_ptr<T>{metric}));
75-
labels_.insert({hash, labels});
76-
labels_reverse_lookup_.insert({metric, hash});
77-
return *metric;
7890
}
7991

8092
template <typename T>

tests/family_test.cc

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,13 @@ TEST_F(FamilyTest, Histogram) {
7575
EXPECT_THAT(collected[0].metric(0).histogram().sample_count(), Eq(1));
7676
}
7777

78+
TEST_F(FamilyTest, add_twice) {
79+
Family<Counter> family{"total_requests", "Counts all requests", {}};
80+
auto& counter = family.Add({{"name", "counter1"}});
81+
auto& counter1 = family.Add({{"name", "counter1"}});
82+
ASSERT_EQ(&counter, &counter1);
83+
}
84+
7885
#ifndef NDEBUG
7986
TEST_F(FamilyTest, should_assert_on_invalid_metric_name) {
8087
auto create_family_with_invalid_name = []() {

0 commit comments

Comments
 (0)