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#ifndef TEST_WUKONG_WUKONG_LOGGER_H
16#define TEST_WUKONG_WUKONG_LOGGER_H
17
18#include <condition_variable>
19#include <mutex>
20#include <queue>
21#include <stdio.h>
22#include <string>
23#include <thread>
24
25#include "singleton.h"
26#include "thread_ex.h"
27
28namespace OHOS {
29namespace WuKong {
30enum LOG_LEVEL {
31    LOG_LEVEL_TRACK = 0,
32    LOG_LEVEL_DEBUG,
33    LOG_LEVEL_INFO,
34    LOG_LEVEL_WARN,
35    LOG_LEVEL_ERROR,
36};
37
38enum WK_LOG_OUTPUT_TYPE {
39    STD_OUTPUT = 0x0001,
40    FILE_OUTPUT = 0x0002,
41    HILOG_OUTPUT = 0x0004,
42};
43
44class WuKongLogger : public DelayedSingleton<WuKongLogger> {
45public:
46    /**
47     * @brief logger start
48     */
49    void SetLevel(LOG_LEVEL level)
50    {
51        outputLevel_ = level;
52    }
53    /**
54     * @brief logger start
55     */
56    bool Start();
57    /**
58     * @brief logger stop
59     */
60    void Stop();
61    /**
62     * @brief  print log
63     * @param level logger level
64     * @param format log string format
65     */
66    void Print(LOG_LEVEL level, const char *format, ...);
67
68    static std::shared_ptr<WuKongLogger> GetInstance();
69    LOG_LEVEL GetLogLevel()
70    {
71        return outputLevel_;
72    }
73
74    DECLARE_DELAYED_SINGLETON(WuKongLogger);
75
76private:
77    class PrinterThread : public OHOS::Thread {
78        /**
79         * @brief read queue and print log to file
80         */
81        bool Run() override;
82    };
83
84    class LogInfo {
85    public:
86        std::string logStr_;
87        LOG_LEVEL level_;
88    };
89
90    // current logger level
91    LOG_LEVEL outputLevel_ = LOG_LEVEL_INFO;
92
93    // current output setting
94    uint32_t outputType_ = STD_OUTPUT | FILE_OUTPUT | HILOG_OUTPUT;
95
96    // current process disk filename
97    std::string logFileName_ = "";
98
99    // Queue lock
100    std::mutex mtxQueue_;
101    std::queue<LogInfo> bufferQueue_;
102
103    // log printer thread.
104    bool printerRunning_ = false;
105    PrinterThread logPrinter_;
106    std::mutex mtxThreadWait_;
107    std::condition_variable cvWaitPrint_;
108    static std::mutex wukongMutex_;
109    static std::shared_ptr<WuKongLogger> wukongInstance_;
110};
111}  // namespace WuKong
112}  // namespace OHOS
113
114#endif  // TEST_WUKONG_WUKONG_LOGGER_H
115