• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "wukong_logger.h"
17 
18 #include <algorithm>
19 #include <chrono>
20 #include <cstdarg>
21 #include <cstdio>
22 #include <cstring>
23 #include <dirent.h>
24 #include <fstream>
25 #include <hilog/log_c.h>
26 #include <iostream>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/types.h>
30 #include <thread>
31 #include <unistd.h>
32 
33 #include "securec.h"
34 #include "string_ex.h"
35 #include "wukong_define.h"
36 #include "wukong_util.h"
37 
38 namespace OHOS {
39 namespace WuKong {
40 namespace {
41 const std::string DEFAULT_DIR = "/data/local/tmp/wukong/report/";
42 const std::string LOGGER_THREAD_NAME = "wukong_logger";
43 const int LOG_CONTENT_LENGTH = 256;
44 const int LOG_PRINTER_TIMEOUT = 500;
45 std::mutex LOCK_PRINT_BUFFER;
46 }  // namespace
47 
WuKongLogger()48 WuKongLogger::WuKongLogger() : logPrinter_()
49 { /* init buf */
50 }
51 
52 /**
53  * @brief: release logfile fd
54  */
~WuKongLogger()55 WuKongLogger::~WuKongLogger()
56 {
57     if (outputLevel_ <= LOG_LEVEL_TRACK) {
58         std::cout << "Logger::~Logger" << std::endl;
59     }
60 
61     // check logPrinter thread is running, and stop
62     if (printerRunning_ && logPrinter_.IsRunning()) {
63         Stop();
64     }
65 }
66 
Start()67 bool WuKongLogger::Start()
68 {
69     if (outputLevel_ <= LOG_LEVEL_TRACK) {
70         std::cout << "Logger::Start" << std::endl;
71     }
72 
73     logFileName_ = WuKongUtil::GetInstance()->GetCurrentTestDir() + "wukong.log";
74 
75     if (logPrinter_.IsRunning()) {
76         DEBUG_LOG("Logger already started");
77         return true;
78     }
79 
80     /* start read Queue Thread */
81     printerRunning_ = true;
82     logPrinter_.Start(LOGGER_THREAD_NAME);
83 
84     // wait print thread started.
85     do {
86         std::unique_lock<std::mutex> lk(mtxThreadWait_);
87         cvWaitPrint_.wait(lk);
88     } while (false);
89     return true;
90 }
91 
Stop()92 void WuKongLogger::Stop()
93 {
94     /* release readQueueThread */
95     if (outputLevel_ <= LOG_LEVEL_TRACK) {
96         std::cout << "Logger::Stop" << std::endl;
97     }
98     if (printerRunning_ && logPrinter_.IsRunning()) {
99         printerRunning_ = false;
100         cvWaitPrint_.notify_all();
101         logPrinter_.NotifyExitSync();
102     }
103 }
104 
Print(LOG_LEVEL level,const char * format,...)105 void WuKongLogger::Print(LOG_LEVEL level, const char *format, ...)
106 {
107     if (!printerRunning_) {
108         return;
109     }
110     LOCK_PRINT_BUFFER.lock();
111     char writeBuf[LOG_CONTENT_LENGTH] = {0};
112     /* check logger_level */
113     if (level < outputLevel_ && level < LOG_LEVEL_DEBUG) {
114         LOCK_PRINT_BUFFER.unlock();
115         return;
116     }
117     /* format output content */
118     va_list args;
119     va_start(args, format);
120     int ret = vsnprintf_s(writeBuf, LOG_CONTENT_LENGTH, LOG_CONTENT_LENGTH, format, args);
121     if (ret < 0) {
122         va_end(args);
123         LOCK_PRINT_BUFFER.unlock();
124         return;
125     }
126     va_end(args);
127 
128     // write lock avoid write conflicts
129     LogInfo logInfo;
130     if (outputLevel_ <= LOG_LEVEL_TRACK) {
131         time_t currentTime = time(0);
132         char *timeChar = ctime(&currentTime);
133         logInfo.logStr_.append(timeChar, strlen(timeChar) - 1);
134         logInfo.logStr_.append(" : ");
135     }
136     logInfo.logStr_.append(writeBuf, strlen(writeBuf));
137     logInfo.level_ = level;
138     LOCK_PRINT_BUFFER.unlock();
139     // if log level is less than LOG_LEVEL_DEBUG, cout print.
140     if (outputLevel_ <= LOG_LEVEL_TRACK) {
141         std::cout << logInfo.logStr_ << std::endl;
142     }
143 
144     // push log to buffer queue.
145     mtxQueue_.lock();
146     bufferQueue_.push(logInfo);
147     mtxQueue_.unlock();
148 
149     // notify print log to printer thread.
150     cvWaitPrint_.notify_all();
151 }
152 
153 /**
154  * @brief read queue and print log to file
155  */
Run()156 bool WuKongLogger::PrinterThread::Run()
157 {
158     std::shared_ptr<WuKongLogger> self = WuKongLogger::GetInstance();
159     if (!self->printerRunning_) {
160         return false;
161     }
162     self->cvWaitPrint_.notify_all();
163     std::unique_lock<std::mutex> lk(self->mtxThreadWait_);
164     std::queue<LogInfo> tmpBuffer;
165     std::ofstream printer(self->logFileName_);
166     if (!printer.is_open()) {
167         std::cout << "ERR: Logger printer file cannot open" << std::endl;
168         return false;
169     }
170     /* read form queue output target fd */
171     printer << "WuKongLogger::PrinterThread::Run start" << std::endl;
172     const auto timeout = std::chrono::milliseconds(LOG_PRINTER_TIMEOUT);
173     while (true) {
174         // wait new log
175         if (self->printerRunning_) {
176             if (self->outputLevel_ <= LOG_LEVEL_TRACK) {
177                 printer << "WuKongLogger::PrinterThread::Run wait start" << std::endl;
178             }
179             self->cvWaitPrint_.wait_for(lk, timeout);
180             if (self->outputLevel_ <= LOG_LEVEL_TRACK) {
181                 printer << "WuKongLogger::PrinterThread::Run wait end" << std::endl;
182             }
183         }
184         // read queue buffer to thread buffer.
185         self->mtxQueue_.lock();
186         // the buffer queue is empty and main wait stop, return this thread.
187         if (self->bufferQueue_.empty() && !self->printerRunning_) {
188             self->mtxQueue_.unlock();
189             break;
190         }
191         while (!self->bufferQueue_.empty()) {
192             tmpBuffer.push(self->bufferQueue_.front());
193             self->bufferQueue_.pop();
194         }
195         self->mtxQueue_.unlock();
196         // print log to file and std::cout and hilog
197         while (!tmpBuffer.empty()) {
198             auto logInfo = tmpBuffer.front();
199             tmpBuffer.pop();
200             // output file fd
201             if (self->outputType_ & FILE_OUTPUT) {
202                 printer << logInfo.logStr_ << std::endl;
203             }
204             // doesn't print STDOUT and HILOG, when log level less than output level.
205             if (logInfo.level_ < self->outputLevel_) {
206                 continue;
207             }
208             // output STDOUT
209             if ((self->outputType_ & STD_OUTPUT) && (self->outputLevel_ > LOG_LEVEL_TRACK)) {
210                 std::cout << logInfo.logStr_ << std::endl;
211             }
212             // output HILOG
213             if (self->outputType_ & HILOG_OUTPUT) {
214                 HILOG_INFO(LOG_CORE, "%{public}s", logInfo.logStr_.c_str());
215             }
216         }
217     }
218     printer << "WuKongLogger::PrinterThread::Run end" << std::endl;
219     printer.close();
220     return false;
221 }
222 }  // namespace WuKong
223 }  // namespace OHOS
224