Avoid calling Collect() in counter/gauge Value() methods if not needed

This commit is contained in:
Tim Wojtulewicz 2024-04-09 10:00:41 -07:00
parent e195d3d778
commit d0d41f5c56
2 changed files with 28 additions and 14 deletions

View file

@ -31,7 +31,7 @@ public:
* Increments the value by @p amount.
* @pre `amount >= 0`
*/
void Inc(BaseType amount) noexcept { handle->Increment(amount); }
void Inc(BaseType amount) noexcept { handle.Increment(amount); }
/**
* Increments the value by 1.
@ -43,10 +43,14 @@ public:
}
BaseType Value() const noexcept {
// Use Collect() here instead of Value() to correctly handle metrics with
// callbacks.
auto metric = handle->Collect();
return static_cast<BaseType>(metric.counter.value);
if ( has_callback ) {
// Use Collect() here instead of Value() to correctly handle metrics with
// callbacks.
auto metric = handle.Collect();
return static_cast<BaseType>(metric.counter.value);
}
return handle.Value();
}
bool operator==(const BaseCounter<BaseType>& rhs) const noexcept { return &handle == &rhs.handle; }
@ -57,13 +61,16 @@ public:
protected:
explicit BaseCounter(FamilyType* family, const prometheus::Labels& labels,
prometheus::CollectCallbackPtr callback = nullptr) noexcept
: handle(&(family->Add(labels))), labels(labels) {
if ( callback )
handle->AddCollectCallback(callback);
: handle(family->Add(labels)), labels(labels) {
if ( callback ) {
handle.AddCollectCallback(callback);
has_callback = true;
}
}
Handle* handle;
Handle& handle;
prometheus::Labels labels;
bool has_callback = false;
};
/**