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 27 void PlatformLogBase::logLooper() { 28 while (1) { 29 char *logMessage = nullptr; 30 31 { 32 std::unique_lock<std::mutex> lock(mMutex); 33 mConditionVariable.wait( 34 lock, [this] { return (!mLogQueue.empty() || mStopLogger); }); 35 36 if (!mLogQueue.empty()) { 37 // Move the log message to avoid holding a lock for longer than 38 // required. 39 logMessage = mLogQueue.front(); 40 mLogQueue.pop(); 41 } else if (mStopLogger) { 42 // The stop logger is checked in an else-if to allow the main log queue 43 // to drain when the logger is stopping. 44 break; 45 } 46 } 47 48 // If we get here, there must be a log message to output. This is outside of 49 // the context of the lock which means that the logging thread will only be 50 // blocked for the minimum amount of time. 51 std::cerr << logMessage << std::endl; 52 free(logMessage); 53 } 54 } 55 56 PlatformLog::PlatformLog() { 57 mLoggerThread = std::thread(&PlatformLog::logLooper, this); 58 } 59 60 PlatformLog::~PlatformLog() { 61 { 62 std::unique_lock<std::mutex> lock(mMutex); 63 mStopLogger = true; 64 mConditionVariable.notify_one(); 65 } 66 67 mLoggerThread.join(); 68 } 69 70 void PlatformLog::log(const char *formatStr, ...) { 71 char *formattedStr; 72 va_list argList; 73 va_start(argList, formatStr); 74 int result = vasprintf(&formattedStr, formatStr, argList); 75 va_end(argList); 76 77 if (result >= 0) { 78 std::unique_lock<std::mutex> lock(mMutex); 79 mLogQueue.push(formattedStr); 80 mConditionVariable.notify_one(); 81 } else { 82 FATAL_ERROR("Failed to allocate log message"); 83 } 84 } 85 86 } // namespace chre 87