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/linux/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 PlatformLog::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
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
logVa(chreLogLevel,const char * formatStr,va_list args)70 void PlatformLog::logVa(chreLogLevel /*logLevel*/, const char *formatStr,
71 va_list args) {
72 char *formattedStr;
73 int result = vasprintf(&formattedStr, formatStr, args);
74
75 if (result >= 0) {
76 std::unique_lock<std::mutex> lock(mMutex);
77 mLogQueue.push(formattedStr);
78 mConditionVariable.notify_one();
79 } else {
80 FATAL_ERROR("Failed to allocate log message");
81 }
82 }
83
84 } // namespace chre
85