1+ /* *
2+ * MIT License
3+ *
4+ * Copyright (c) 2025 Huawei Technologies Co., Ltd. All rights reserved.
5+ *
6+ * Permission is hereby granted, free of charge, to any person obtaining a copy
7+ * of this software and associated documentation files (the "Software"), to deal
8+ * in the Software without restriction, including without limitation the rights
9+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10+ * copies of the Software, and to permit persons to whom the Software is
11+ * furnished to do so, subject to the following conditions:
12+ *
13+ * The above copyright notice and this permission notice shall be included in all
14+ * copies or substantial portions of the Software.
15+ *
16+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+ * SOFTWARE.
23+ * */
24+ #include < algorithm>
25+ #include " metrics.h"
26+
27+ namespace UC ::Metrics {
28+
29+ void Metrics::CreateStats (const std::string& name, std::string& type)
30+ {
31+ std::lock_guard<std::mutex> lock (mutex_);
32+ std::transform (type.begin (), type.end (), type.begin (), ::toupper);
33+ if (stats_type_.count (name)) {
34+ return ;
35+ } else {
36+ if (type == " COUNTER" ) {
37+ stats_type_[name] = MetricType::COUNTER;
38+ } else if (type == " GUAGE" ) {
39+ stats_type_[name] = MetricType::GUAGE;
40+ } else if (type == " HISTOGRAM" ) {
41+ stats_type_[name] = MetricType::HISTOGRAM;
42+ } else {
43+ return ;
44+ }
45+ }
46+ }
47+
48+ void Metrics::UpdateStats (const std::string& name, double value)
49+ {
50+ std::lock_guard<std::mutex> lock (mutex_);
51+ auto it = stats_type_.find (name);
52+ if (it == stats_map_.end () || !it->second ) { return ; }
53+ switch (it->second )
54+ {
55+ case MetricType::COUNTER:
56+ counter_stats_[name] += value;
57+ break ;
58+ case MetricType::GUAGE:
59+ gauge_stats_[name] = value;
60+ break ;
61+ case MetricType::HISTOGRAM:
62+ histogram_stats_[name].push_back (value);
63+ break ;
64+
65+ default :
66+ break ;
67+ }
68+ }
69+
70+
71+ std::tuple<
72+ std::unordered_map<std::string, double >,
73+ std::unordered_map<std::string, double >,
74+ std::unordered_map<std::string, std::vector<double >>
75+ > Metrics::GetAllStatsAndClear ()
76+ {
77+ std::lock_guard<std::mutex> lock (mutex_);
78+ auto result = std::make_tuple (
79+ std::move (counter_stats_),
80+ std::move (gauge_stats_),
81+ std::move (histogram_stats_)
82+ );
83+ counter_stats_.clear ();
84+ gauge_stats_.clear ();
85+ histogram_stats_.clear ();
86+ return result;
87+ }
88+
89+ } // namespace UC::Metrics
0 commit comments