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 std::unique_ptr<char> logMessage;
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 = std::move(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.get() << std::endl;
53 }
54 }
55
PlatformLog()56 PlatformLog::PlatformLog() {
57 mLoggerThread = std::thread(&PlatformLog::logLooper, this);
58 }
59
~PlatformLog()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
log(const char * formatStr,...)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 // Wrap the formatted string into a unique_ptr so that it will be free'd
79 // once it has been logged.
80 std::unique_ptr<char> log(formattedStr);
81
82 std::unique_lock<std::mutex> lock(mMutex);
83 mLogQueue.push(std::move(log));
84 mConditionVariable.notify_one();
85 } else {
86 FATAL_ERROR("Failed to allocate log message");
87 }
88 }
89
90 } // namespace chre
91