• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "chre/platform/shared/platform_log.h"
18 
19 #include <cstdarg>
20 #include <cstdio>
21 #include <iostream>
22 
23 #include "chre/platform/fatal_error.h"
24 
25 namespace chre {
26 
logLooper()27 void PlatformLogBase::logLooper() {
28   while (1) {
29     char *logMessage = nullptr;
30 
31     {
32       std::unique_lock<std::mutex> lock(mMutex);
33       mConditionVariable.wait(lock, [this]{
34         return (!mLogQueue.empty() || mStopLogger);
35       });
36 
37       if (!mLogQueue.empty()) {
38         // Move the log message to avoid holding a lock for longer than
39         // required.
40         logMessage = mLogQueue.front();
41         mLogQueue.pop();
42       } else if (mStopLogger) {
43         // The stop logger is checked in an else-if to allow the main log queue
44         // to drain when the logger is stopping.
45         break;
46       }
47     }
48 
49     // If we get here, there must be a log message to output. This is outside of
50     // the context of the lock which means that the logging thread will only be
51     // blocked for the minimum amount of time.
52     std::cerr << logMessage << std::endl;
53     free(logMessage);
54   }
55 }
56 
PlatformLog()57 PlatformLog::PlatformLog() {
58   mLoggerThread = std::thread(&PlatformLog::logLooper, this);
59 }
60 
~PlatformLog()61 PlatformLog::~PlatformLog() {
62   {
63     std::unique_lock<std::mutex> lock(mMutex);
64     mStopLogger = true;
65     mConditionVariable.notify_one();
66   }
67 
68   mLoggerThread.join();
69 }
70 
log(const char * formatStr,...)71 void PlatformLog::log(const char *formatStr, ...) {
72   char *formattedStr;
73   va_list argList;
74   va_start(argList, formatStr);
75   int result = vasprintf(&formattedStr, formatStr, argList);
76   va_end(argList);
77 
78   if (result >= 0) {
79     std::unique_lock<std::mutex> lock(mMutex);
80     mLogQueue.push(formattedStr);
81     mConditionVariable.notify_one();
82   } else {
83     FATAL_ERROR("Failed to allocate log message");
84   }
85 }
86 
87 }  // namespace chre
88