1 /* 2 * Copyright (c) 2022 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 #ifndef UPDATE_DUMP_H 17 #define UPDATE_DUMP_H 18 19 #include <cstdlib> 20 #include <iostream> 21 #include <map> 22 #include <memory> 23 #include <sstream> 24 #include <stack> 25 #include <string> 26 #include <vector> 27 #include "log.h" 28 #include "macros_updater.h" 29 30 #define UPDATER_LAST_WORD Updater::Dump::GetInstance().DumpInfo 31 #define UPDATER_INIT_RECORD DumpStageHelper stageHelper(__FUNCTION__) 32 #define UPDATER_CLEAR_RECORD Updater::Dump::GetInstance().ClearDump() 33 34 namespace Updater { 35 class DumpHelper { 36 public: 37 virtual void RecordDump(const std::string &str) = 0; 38 virtual void ClearDump(void) = 0; ~DumpHelper()39 virtual ~DumpHelper() {} 40 }; 41 42 class DumpHelperLog : public DumpHelper { 43 public: RecordDump(const std::string & str)44 void RecordDump(const std::string &str) override 45 { 46 LOG(ERROR) << str; 47 } ClearDump(void)48 void ClearDump(void) override {} ~DumpHelperLog()49 ~DumpHelperLog() override {} 50 }; 51 52 class Dump { 53 public: 54 DISALLOW_COPY_MOVE(Dump); RegisterDump(const std::string & key,std::unique_ptr<DumpHelper> ptr)55 void RegisterDump(const std::string &key, std::unique_ptr<DumpHelper> ptr) 56 { 57 helpers_.emplace(key, std::move(ptr)); 58 } 59 virtual ~Dump(); 60 static Dump &GetInstance(); 61 template<typename ...Args> DumpInfo(Args &&...args)62 void DumpInfo(Args &&...args) 63 { 64 std::ostringstream oss; 65 std::size_t n {0}; 66 ((oss << args << (++n != sizeof ...(Args) ? "," : "")), ...); 67 std::string str = oss.str(); 68 for (const auto &[key, value] : helpers_) { 69 if (value != nullptr) { 70 value->RecordDump(str); 71 } 72 } 73 } ClearDump(void)74 void ClearDump(void) 75 { 76 for (const auto &[key, value] : helpers_) { 77 if (value != nullptr) { 78 value->ClearDump(); 79 } 80 } 81 } 82 83 private: Dump()84 Dump() {} 85 std::map<std::string, std::unique_ptr<DumpHelper>> helpers_; 86 }; 87 88 class DumpStageHelper { 89 public: 90 DumpStageHelper(const std::string &stage); 91 ~DumpStageHelper(); 92 static std::stack<std::string> &GetDumpStack(); 93 }; 94 } // namespace Updater 95 #endif // UPDATE_DUMP_H 96