1 /* 2 * Copyright (C) 2021 The Android Open Source Project 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 #pragma once 18 19 #include <map> 20 #include <mutex> 21 #include <sstream> 22 23 #include <android-base/thread_annotations.h> 24 #include <audio_utils/SimpleLog.h> 25 26 namespace android::mediametrics { 27 28 class StatsdLog { 29 public: StatsdLog(size_t lines)30 explicit StatsdLog(size_t lines) : mSimpleLog(lines) {} 31 log(int atom,const std::string & string)32 void log(int atom, const std::string& string) { 33 { 34 std::lock_guard lock(mLock); 35 ++mCountMap[atom]; 36 } 37 mSimpleLog.log("%s", string.c_str()); 38 } 39 40 std::string dumpToString(const char *prefix = "", size_t logLines = 0) const { 41 std::stringstream ss; 42 43 { // first print out the atom counts 44 std::lock_guard lock(mLock); 45 46 size_t col = 0; 47 for (const auto& count : mCountMap) { 48 if (col == 8) { 49 col = 0; 50 ss << "\n" << prefix; 51 } else { 52 ss << " "; 53 } 54 ss << "[ " << count.first << " : " << count.second << " ]"; 55 ++col; 56 } 57 ss << "\n"; 58 } 59 60 // then print out the log lines 61 ss << mSimpleLog.dumpToString(prefix, logLines); 62 return ss.str(); 63 } 64 65 private: 66 mutable std::mutex mLock; 67 SimpleLog mSimpleLog; // internally locked 68 std::map<int /* atom */, size_t /* count */> mCountMap GUARDED_BY(mLock); // sorted 69 }; 70 71 } // namespace android::mediametrics 72