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.h" 29 30 #define UPDATER_LAST_WORD Updater::Dump::GetInstance().DumpInfo 31 #define UPDATER_INIT_RECORD DumpStageHelper stageHelper(__FUNCTION__) 32 33 namespace Updater { 34 class DumpHelper { 35 public: 36 virtual void RecordDump(const std::string &str) = 0; ~DumpHelper()37 virtual ~DumpHelper() {} 38 }; 39 40 class DumpHelperLog : public DumpHelper { 41 public: RecordDump(const std::string & str)42 void RecordDump(const std::string &str) override 43 { 44 LOG(ERROR) << str; 45 } ~DumpHelperLog()46 ~DumpHelperLog() override {} 47 }; 48 49 class Dump { 50 public: 51 DISALLOW_COPY_MOVE(Dump); RegisterDump(const std::string & key,std::unique_ptr<DumpHelper> ptr)52 void RegisterDump(const std::string &key, std::unique_ptr<DumpHelper> ptr) 53 { 54 helpers_.emplace(key, std::move(ptr)); 55 } 56 virtual ~Dump(); 57 static Dump &GetInstance(); 58 template<typename ...Args> DumpInfo(Args &&...args)59 void DumpInfo(Args &&...args) 60 { 61 std::ostringstream oss; 62 std::size_t n {0}; 63 ((oss << args << (++n != sizeof ...(Args) ? "," : "")), ...); 64 std::string str = oss.str(); 65 for (const auto &[key, value] : helpers_) { 66 if (value != nullptr) { 67 value->RecordDump(str); 68 } 69 } 70 } 71 72 private: Dump()73 Dump() {} 74 std::map<std::string, std::unique_ptr<DumpHelper>> helpers_; 75 }; 76 77 class DumpStageHelper { 78 public: 79 DumpStageHelper(const std::string &stage); 80 ~DumpStageHelper(); 81 static std::stack<std::string> &GetDumpStack(); 82 }; 83 } // namespace Updater 84 #endif // UPDATE_DUMP_H 85