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 28 namespace OHOS { 29 namespace WuKong { 30 enum 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 38 enum WK_LOG_OUTPUT_TYPE { 39 STD_OUTPUT = 0x0001, 40 FILE_OUTPUT = 0x0002, 41 HILOG_OUTPUT = 0x0004, 42 }; 43 44 class WuKongLogger : public DelayedSingleton<WuKongLogger> { 45 public: 46 /** 47 * @brief logger start 48 */ SetLevel(LOG_LEVEL level)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 GetLogLevel()68 LOG_LEVEL GetLogLevel() 69 { 70 return outputLevel_; 71 } 72 73 DECLARE_DELAYED_SINGLETON(WuKongLogger); 74 75 private: 76 class PrinterThread : public OHOS::Thread { 77 /** 78 * @brief read queue and print log to file 79 */ 80 bool Run() override; 81 }; 82 83 class LogInfo { 84 public: 85 std::string logStr_; 86 LOG_LEVEL level_; 87 }; 88 89 // current logger level 90 LOG_LEVEL outputLevel_ = LOG_LEVEL_INFO; 91 92 // current output setting 93 uint32_t outputType_ = STD_OUTPUT | FILE_OUTPUT | HILOG_OUTPUT; 94 95 // current process disk filename 96 std::string logFileName_ = ""; 97 98 // Queue lock 99 std::mutex mtxQueue_; 100 std::queue<LogInfo> bufferQueue_; 101 102 // log printer thread. 103 bool printerRunning_ = false; 104 PrinterThread logPrinter_; 105 std::mutex mtxThreadWait_; 106 std::condition_variable cvWaitPrint_; 107 }; 108 } // namespace WuKong 109 } // namespace OHOS 110 111 #endif // TEST_WUKONG_WUKONG_LOGGER_H 112