xref: /base/update/updater/services/include/log/dump.h (revision fb299fa2)
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
33namespace Updater {
34class DumpHelper {
35public:
36    virtual void RecordDump(const std::string &str) = 0;
37    virtual ~DumpHelper() {}
38};
39
40class DumpHelperLog : public DumpHelper {
41public:
42    void RecordDump(const std::string &str) override
43    {
44        LOG(ERROR) << str;
45    }
46    ~DumpHelperLog() override {}
47};
48
49class Dump {
50public:
51    DISALLOW_COPY_MOVE(Dump);
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>
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
72private:
73    Dump() {}
74    std::map<std::string, std::unique_ptr<DumpHelper>> helpers_;
75};
76
77class DumpStageHelper {
78public:
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