Line data Source code
1 : // 2 : // Copyright 2024 OpenModelViewer Authors 3 : // 4 : // Licensed under the Apache License, Version 2.0 (the "License"); 5 : // you may not use this file except in compliance with the License. 6 : // You may obtain a copy of the License at 7 : // 8 : // http://www.apache.org/licenses/LICENSE-2.0 9 : // 10 : // Unless required by applicable law or agreed to in writing, software 11 : // distributed under the License is distributed on an "AS IS" BASIS, 12 : // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 : // See the License for the specific language governing permissions and 14 : // limitations under the License. 15 : // 16 : 17 : #include "openmodelviewer/core/log/sinks/counter_sink.hpp" 18 : 19 : #include <algorithm> 20 : 21 : namespace openmodelviewer::core::log::sinks 22 : { 23 2 : CounterSink::CounterSink() 24 : { 25 2 : } 26 : 27 5 : CounterSink::CounterSink(std::initializer_list<LogLevel> levels) 28 : { 29 5 : m_counters.reserve(levels.size()); 30 : 31 12 : for (LogLevel level : levels) 32 : { 33 7 : this->trackLevel(level); 34 : } 35 5 : } 36 : 37 10 : void CounterSink::log(const LogEntry& entry) 38 : { 39 10 : LogLevel level = entry.getLevel(); 40 : 41 10 : if (this->isTracked(level)) 42 : { 43 8 : m_counters[level]++; 44 : } 45 10 : } 46 : 47 1 : void CounterSink::flush() 48 : { 49 1 : m_tracked.clear(); 50 1 : m_counters.clear(); 51 1 : } 52 : 53 9 : bool CounterSink::trackLevel(LogLevel level) 54 : { 55 9 : if (this->isTracked(level)) 56 : { 57 0 : return false; 58 : } 59 : 60 9 : m_tracked.push_back(level); 61 9 : m_counters.insert({ level, 0 }); 62 : 63 9 : return true; 64 : } 65 : 66 1 : bool CounterSink::untrackLevel(LogLevel level) 67 : { 68 1 : if (!this->isTracked(level)) 69 : { 70 0 : return false; 71 : } 72 : 73 1 : m_tracked.erase(std::find(m_tracked.begin(), m_tracked.end(), level)); 74 : 75 1 : return true; 76 : } 77 : 78 29 : bool CounterSink::isTracked(LogLevel level) const noexcept 79 : { 80 40 : for (LogLevel tlevel : m_tracked) 81 : { 82 25 : if (tlevel == level) 83 : { 84 14 : return true; 85 : } 86 : } 87 : 88 15 : return false; 89 : } 90 : 91 9 : uint64_t CounterSink::getCount(LogLevel level) const noexcept 92 : { 93 9 : auto it = m_counters.find(level); 94 9 : return (it != m_counters.end()) ? it->second : 0; 95 : } 96 : 97 1 : bool CounterSink::reset(LogLevel level) 98 : { 99 1 : if (!this->isTracked(level)) 100 : { 101 0 : return false; 102 : } 103 : else 104 : { 105 1 : m_counters.at(level) = 0; 106 1 : return true; 107 : } 108 : } 109 : 110 1 : void CounterSink::resetAll() 111 : { 112 3 : for (auto& counter : m_counters) 113 : { 114 2 : counter.second = 0; 115 : } 116 1 : } 117 : }