blob: 880287b177d82dfeb4def012e61774fe36f5c383 [file] [log] [blame]
Dan Albert58310b42015-03-13 23:06:01 -07001/*
2 * Copyright (C) 2015 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
Elliott Hughes7bc87a52016-08-04 16:09:39 -070017#if defined(_WIN32)
Spencer Lowac3f7d92015-05-19 22:12:06 -070018#include <windows.h>
19#endif
20
Elliott Hughes4f713192015-12-04 22:00:26 -080021#include "android-base/logging.h"
Dan Albert58310b42015-03-13 23:06:01 -070022
Elliott Hughes7bc87a52016-08-04 16:09:39 -070023#include <fcntl.h>
Josh Gao5791e212018-03-16 14:25:42 -070024#include <inttypes.h>
Dan Albert7a87d052015-04-03 11:28:46 -070025#include <libgen.h>
Elliott Hughes4e5fd112016-06-21 14:25:44 -070026#include <time.h>
Dan Albert7a87d052015-04-03 11:28:46 -070027
28// For getprogname(3) or program_invocation_short_name.
29#if defined(__ANDROID__) || defined(__APPLE__)
30#include <stdlib.h>
31#elif defined(__GLIBC__)
32#include <errno.h>
33#endif
34
Elliott Hughes7bc87a52016-08-04 16:09:39 -070035#if defined(__linux__)
36#include <sys/uio.h>
37#endif
38
Tom Cherry349b0c42020-01-08 14:47:42 -080039#include <atomic>
Dan Albert58310b42015-03-13 23:06:01 -070040#include <iostream>
41#include <limits>
Josh Gao63bdcb52016-09-13 14:57:12 -070042#include <mutex>
Tom Cherry349b0c42020-01-08 14:47:42 -080043#include <optional>
Dan Albert58310b42015-03-13 23:06:01 -070044#include <sstream>
45#include <string>
Dan Albertb547c852015-03-27 11:20:14 -070046#include <utility>
Dan Albert58310b42015-03-13 23:06:01 -070047#include <vector>
48
Andreas Gampeaf05f3b2018-02-15 11:40:30 -080049#include <android/log.h>
Tom Cherry99216302020-01-08 13:41:56 -080050#ifdef __ANDROID__
Dan Albert58310b42015-03-13 23:06:01 -070051#include <android/set_abort_message.h>
Dan Albert58310b42015-03-13 23:06:01 -070052#else
53#include <sys/types.h>
54#include <unistd.h>
55#endif
56
Elliott Hughes4679a392018-10-19 13:59:44 -070057#include <android-base/file.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070058#include <android-base/macros.h>
Mark Salyzyn2507a042018-04-06 09:40:26 -070059#include <android-base/parseint.h>
Mark Salyzynff2dcd92016-09-28 15:54:45 -070060#include <android-base/strings.h>
Josh Gao5791e212018-03-16 14:25:42 -070061#include <android-base/threads.h>
Elliott Hughesc1fd4922015-11-11 18:02:29 +000062
Tom Cherry349b0c42020-01-08 14:47:42 -080063#include "liblog_symbols.h"
64
Elliott Hughes11a64eb2018-06-06 12:54:41 -070065namespace android {
66namespace base {
67
68// BSD-based systems like Android/macOS have getprogname(). Others need us to provide one.
69#if defined(__GLIBC__) || defined(_WIN32)
70static const char* getprogname() {
Dan Albert5c190402015-04-29 11:32:23 -070071#if defined(__GLIBC__)
Dan Albert5c190402015-04-29 11:32:23 -070072 return program_invocation_short_name;
Josh Gao63bdcb52016-09-13 14:57:12 -070073#elif defined(_WIN32)
Dan Albert5c190402015-04-29 11:32:23 -070074 static bool first = true;
75 static char progname[MAX_PATH] = {};
76
77 if (first) {
Elliott Hughes4679a392018-10-19 13:59:44 -070078 snprintf(progname, sizeof(progname), "%s",
79 android::base::Basename(android::base::GetExecutablePath()).c_str());
Dan Albert5c190402015-04-29 11:32:23 -070080 first = false;
81 }
82
83 return progname;
Elliott Hughes11a64eb2018-06-06 12:54:41 -070084#endif
Dan Albert5c190402015-04-29 11:32:23 -070085}
Dan Albert5c190402015-04-29 11:32:23 -070086#endif
Mark Salyzyn2507a042018-04-06 09:40:26 -070087
Elliott Hughes11a64eb2018-06-06 12:54:41 -070088static const char* GetFileBasename(const char* file) {
89 // We can't use basename(3) even on Unix because the Mac doesn't
90 // have a non-modifying basename.
91 const char* last_slash = strrchr(file, '/');
92 if (last_slash != nullptr) {
93 return last_slash + 1;
94 }
95#if defined(_WIN32)
96 const char* last_backslash = strrchr(file, '\\');
97 if (last_backslash != nullptr) {
98 return last_backslash + 1;
99 }
100#endif
101 return file;
102}
103
Mark Salyzyn2507a042018-04-06 09:40:26 -0700104#if defined(__linux__)
Elliott Hughes11a64eb2018-06-06 12:54:41 -0700105static int OpenKmsg() {
Mark Salyzyn2507a042018-04-06 09:40:26 -0700106#if defined(__ANDROID__)
107 // pick up 'file w /dev/kmsg' environment from daemon's init rc file
108 const auto val = getenv("ANDROID_FILE__dev_kmsg");
109 if (val != nullptr) {
110 int fd;
111 if (android::base::ParseInt(val, &fd, 0)) {
112 auto flags = fcntl(fd, F_GETFL);
113 if ((flags != -1) && ((flags & O_ACCMODE) == O_WRONLY)) return fd;
114 }
115 }
116#endif
117 return TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
118}
119#endif
Dan Albert58310b42015-03-13 23:06:01 -0700120
Tom Cherry349b0c42020-01-08 14:47:42 -0800121static LogId log_id_tToLogId(int buffer_id) {
122 switch (buffer_id) {
123 case LOG_ID_MAIN:
124 return MAIN;
125 case LOG_ID_SYSTEM:
126 return SYSTEM;
127 case LOG_ID_RADIO:
128 return RADIO;
129 case LOG_ID_CRASH:
130 return CRASH;
131 case LOG_ID_DEFAULT:
132 default:
133 return DEFAULT;
134 }
135}
136
137static int LogIdTolog_id_t(LogId log_id) {
138 switch (log_id) {
139 case MAIN:
140 return LOG_ID_MAIN;
141 case SYSTEM:
142 return LOG_ID_SYSTEM;
143 case RADIO:
144 return LOG_ID_RADIO;
145 case CRASH:
146 return LOG_ID_CRASH;
147 case DEFAULT:
148 default:
149 return LOG_ID_DEFAULT;
150 }
151}
152
153static LogSeverity PriorityToLogSeverity(int priority) {
154 switch (priority) {
155 case ANDROID_LOG_VERBOSE:
156 return VERBOSE;
157 case ANDROID_LOG_DEBUG:
158 return DEBUG;
159 case ANDROID_LOG_INFO:
160 return INFO;
161 case ANDROID_LOG_WARN:
162 return WARNING;
163 case ANDROID_LOG_ERROR:
164 return ERROR;
165 case ANDROID_LOG_FATAL:
166 return FATAL;
167 default:
168 return FATAL;
169 }
170}
171
172static android_LogPriority LogSeverityToPriority(LogSeverity severity) {
173 switch (severity) {
174 case VERBOSE:
175 return ANDROID_LOG_VERBOSE;
176 case DEBUG:
177 return ANDROID_LOG_DEBUG;
178 case INFO:
179 return ANDROID_LOG_INFO;
180 case WARNING:
181 return ANDROID_LOG_WARN;
182 case ERROR:
183 return ANDROID_LOG_ERROR;
184 case FATAL_WITHOUT_ABORT:
185 case FATAL:
186 default:
187 return ANDROID_LOG_FATAL;
188 }
189}
190
Yabin Cui0c689532017-01-23 10:29:23 -0800191static std::mutex& LoggingLock() {
192 static auto& logging_lock = *new std::mutex();
193 return logging_lock;
194}
Dan Albert58310b42015-03-13 23:06:01 -0700195
Tom Cherry349b0c42020-01-08 14:47:42 -0800196// Only used for Q fallback.
Yabin Cui0c689532017-01-23 10:29:23 -0800197static LogFunction& Logger() {
Dan Albertb547c852015-03-27 11:20:14 -0700198#ifdef __ANDROID__
Yabin Cui0c689532017-01-23 10:29:23 -0800199 static auto& logger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700200#else
Yabin Cui0c689532017-01-23 10:29:23 -0800201 static auto& logger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700202#endif
Yabin Cui0c689532017-01-23 10:29:23 -0800203 return logger;
204}
Dan Albertb547c852015-03-27 11:20:14 -0700205
Tom Cherry349b0c42020-01-08 14:47:42 -0800206// Only used for Q fallback.
Yabin Cui0c689532017-01-23 10:29:23 -0800207static AbortFunction& Aborter() {
208 static auto& aborter = *new AbortFunction(DefaultAborter);
209 return aborter;
210}
211
Andreas Gampe1923e762018-03-05 10:00:19 -0800212static std::recursive_mutex& TagLock() {
213 static auto& tag_lock = *new std::recursive_mutex();
214 return tag_lock;
215}
216static std::string* gDefaultTag;
217std::string GetDefaultTag() {
218 std::lock_guard<std::recursive_mutex> lock(TagLock());
219 if (gDefaultTag == nullptr) {
220 return "";
221 }
222 return *gDefaultTag;
223}
224void SetDefaultTag(const std::string& tag) {
225 std::lock_guard<std::recursive_mutex> lock(TagLock());
226 if (gDefaultTag != nullptr) {
227 delete gDefaultTag;
228 gDefaultTag = nullptr;
229 }
230 if (!tag.empty()) {
231 gDefaultTag = new std::string(tag);
232 }
Yabin Cui0c689532017-01-23 10:29:23 -0800233}
Andreas Gampe2691e332016-09-08 11:03:58 -0700234
Dan Albert7a87d052015-04-03 11:28:46 -0700235static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700236static LogSeverity gMinimumLogSeverity = INFO;
Dan Albert58310b42015-03-13 23:06:01 -0700237
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700238#if defined(__linux__)
239void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
240 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700241 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700242 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700243 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
244 // level)
245 [android::base::DEBUG] = 7, // KERN_DEBUG
246 [android::base::INFO] = 6, // KERN_INFO
247 [android::base::WARNING] = 4, // KERN_WARNING
248 [android::base::ERROR] = 3, // KERN_ERROR
249 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
250 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700251 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700252 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700253 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
254 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
255
Mark Salyzyn2507a042018-04-06 09:40:26 -0700256 static int klog_fd = OpenKmsg();
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700257 if (klog_fd == -1) return;
258
259 int level = kLogSeverityToKernelLogLevel[severity];
260
261 // The kernel's printk buffer is only 1024 bytes.
262 // TODO: should we automatically break up long lines into multiple lines?
263 // Or we could log but with something like "..." at the end?
264 char buf[1024];
265 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
266 if (size > sizeof(buf)) {
267 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
268 level, tag, size);
269 }
270
271 iovec iov[1];
272 iov[0].iov_base = buf;
273 iov[0].iov_len = size;
274 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
275}
276#endif
277
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800278void StderrLogger(LogId, LogSeverity severity, const char* tag, const char* file, unsigned int line,
279 const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700280 struct tm now;
281 time_t t = time(nullptr);
282
283#if defined(_WIN32)
284 localtime_s(&now, &t);
285#else
286 localtime_r(&t, &now);
287#endif
288
289 char timestamp[32];
290 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
291
Andreas Gampe550829d2016-09-07 10:10:50 -0700292 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700293 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
294 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700295 char severity_char = log_characters[severity];
Tom Cherry349b0c42020-01-08 14:47:42 -0800296 if (file != nullptr) {
297 fprintf(stderr, "%s %c %s %5d %5" PRIu64 " %s:%u] %s\n", tag ? tag : "nullptr", severity_char,
298 timestamp, getpid(), GetThreadId(), file, line, message);
299 } else {
300 fprintf(stderr, "%s %c %s %5d %5" PRIu64 " %s\n", tag ? tag : "nullptr", severity_char,
301 timestamp, getpid(), GetThreadId(), message);
302 }
Dan Albertb547c852015-03-27 11:20:14 -0700303}
304
Elliott Hughes1be0d142018-05-23 09:16:46 -0700305void StdioLogger(LogId, LogSeverity severity, const char* /*tag*/, const char* /*file*/,
306 unsigned int /*line*/, const char* message) {
307 if (severity >= WARNING) {
308 fflush(stdout);
Elliott Hughes11a64eb2018-06-06 12:54:41 -0700309 fprintf(stderr, "%s: %s\n", GetFileBasename(getprogname()), message);
Elliott Hughes1be0d142018-05-23 09:16:46 -0700310 } else {
311 fprintf(stdout, "%s\n", message);
312 }
313}
314
Andreas Gampe2691e332016-09-08 11:03:58 -0700315void DefaultAborter(const char* abort_message) {
316#ifdef __ANDROID__
317 android_set_abort_message(abort_message);
318#else
319 UNUSED(abort_message);
320#endif
321 abort();
322}
323
Dan Albertb547c852015-03-27 11:20:14 -0700324
Dan Albertb547c852015-03-27 11:20:14 -0700325LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
326}
327
Dan Albertb547c852015-03-27 11:20:14 -0700328void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
329 const char* file, unsigned int line,
330 const char* message) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800331 android_LogPriority priority = LogSeverityToPriority(severity);
Dan Albertb547c852015-03-27 11:20:14 -0700332 if (id == DEFAULT) {
333 id = default_log_id_;
334 }
335
Tom Cherry349b0c42020-01-08 14:47:42 -0800336 int lg_id = LogIdTolog_id_t(id);
Dan Albertb547c852015-03-27 11:20:14 -0700337
Tom Cherry349b0c42020-01-08 14:47:42 -0800338 char log_message[1024];
339 if (priority == ANDROID_LOG_FATAL && file != nullptr) {
340 snprintf(log_message, sizeof(log_message), "%s:%u] %s", file, line, message);
341 } else {
342 snprintf(log_message, sizeof(log_message), "%s", message);
343 }
344
345 static auto& liblog_functions = GetLibLogFunctions();
346 if (liblog_functions) {
347 __android_logger_data logger_data = {sizeof(__android_logger_data), lg_id, priority, tag,
348 static_cast<const char*>(nullptr), 0};
349 liblog_functions->__android_log_logd_logger(&logger_data, log_message);
Dan Albertb547c852015-03-27 11:20:14 -0700350 } else {
351 __android_log_buf_print(lg_id, priority, tag, "%s", message);
352 }
353}
Dan Albertb547c852015-03-27 11:20:14 -0700354
Andreas Gampe2691e332016-09-08 11:03:58 -0700355void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albertb547c852015-03-27 11:20:14 -0700356 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe2691e332016-09-08 11:03:58 -0700357 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albertb547c852015-03-27 11:20:14 -0700358
Dan Albert7a87d052015-04-03 11:28:46 -0700359 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700360 return;
361 }
362
Dan Albert7a87d052015-04-03 11:28:46 -0700363 gInitialized = true;
364
Dan Albert58310b42015-03-13 23:06:01 -0700365 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800366 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
367 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700368 if (argv != nullptr) {
Andreas Gampe1923e762018-03-05 10:00:19 -0800369 SetDefaultTag(basename(argv[0]));
Dan Albert58310b42015-03-13 23:06:01 -0700370 }
Dan Albert7a87d052015-04-03 11:28:46 -0700371
Dan Albert58310b42015-03-13 23:06:01 -0700372 const char* tags = getenv("ANDROID_LOG_TAGS");
373 if (tags == nullptr) {
374 return;
375 }
376
Dan Albert47328c92015-03-19 13:24:26 -0700377 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700378 for (size_t i = 0; i < specs.size(); ++i) {
379 // "tag-pattern:[vdiwefs]"
380 std::string spec(specs[i]);
381 if (spec.size() == 3 && StartsWith(spec, "*:")) {
382 switch (spec[2]) {
383 case 'v':
384 gMinimumLogSeverity = VERBOSE;
385 continue;
386 case 'd':
387 gMinimumLogSeverity = DEBUG;
388 continue;
389 case 'i':
390 gMinimumLogSeverity = INFO;
391 continue;
392 case 'w':
393 gMinimumLogSeverity = WARNING;
394 continue;
395 case 'e':
396 gMinimumLogSeverity = ERROR;
397 continue;
398 case 'f':
Andreas Gampe550829d2016-09-07 10:10:50 -0700399 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700400 continue;
401 // liblog will even suppress FATAL if you say 's' for silent, but that's
402 // crazy!
403 case 's':
Andreas Gampe550829d2016-09-07 10:10:50 -0700404 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700405 continue;
406 }
407 }
408 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
409 << ")";
410 }
411}
412
Dan Albertb547c852015-03-27 11:20:14 -0700413void SetLogger(LogFunction&& logger) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800414 static auto& liblog_functions = GetLibLogFunctions();
415 if (liblog_functions) {
416 // We need to atomically swap the old and new pointers since other threads may be logging.
417 // We know all threads will be using the new logger after __android_log_set_logger() returns,
418 // so we can delete it then.
419 // This leaks one std::function<> per instance of libbase if multiple copies of libbase within a
420 // single process call SetLogger(). That is the same cost as having a static
421 // std::function<>, which is the not-thread-safe alternative.
422 static std::atomic<LogFunction*> logger_function(nullptr);
423 auto* old_logger_function = logger_function.exchange(new LogFunction(logger));
424 liblog_functions->__android_log_set_logger([](const struct __android_logger_data* logger_data,
425 const char* message) {
426 auto log_id = log_id_tToLogId(logger_data->buffer_id);
427 auto severity = PriorityToLogSeverity(logger_data->priority);
428
429 auto& function = *logger_function.load(std::memory_order_acquire);
430 function(log_id, severity, logger_data->tag, logger_data->file, logger_data->line, message);
431 });
432 delete old_logger_function;
433 } else {
434 std::lock_guard<std::mutex> lock(LoggingLock());
435 Logger() = std::move(logger);
436 }
Dan Albertb547c852015-03-27 11:20:14 -0700437}
438
Andreas Gampe2691e332016-09-08 11:03:58 -0700439void SetAborter(AbortFunction&& aborter) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800440 static auto& liblog_functions = GetLibLogFunctions();
441 if (liblog_functions) {
442 // See the comment in SetLogger().
443 static std::atomic<AbortFunction*> abort_function(nullptr);
444 auto* old_abort_function = abort_function.exchange(new AbortFunction(aborter));
445 __android_log_set_aborter([](const char* abort_message) {
446 auto& function = *abort_function.load(std::memory_order_acquire);
447 function(abort_message);
448 });
449 delete old_abort_function;
450 } else {
451 std::lock_guard<std::mutex> lock(LoggingLock());
452 Aborter() = std::move(aborter);
453 }
Andreas Gampe2691e332016-09-08 11:03:58 -0700454}
455
Dan Albert58310b42015-03-13 23:06:01 -0700456// This indirection greatly reduces the stack impact of having lots of
457// checks/logging in a function.
458class LogMessageData {
459 public:
Tom Cherryd044eaa2020-01-10 17:18:55 -0800460 LogMessageData(const char* file, unsigned int line, LogSeverity severity, const char* tag,
461 int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700462 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700463 line_number_(line),
Dan Albert0c055862015-03-27 11:20:14 -0700464 severity_(severity),
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800465 tag_(tag),
466 error_(error) {}
Dan Albert58310b42015-03-13 23:06:01 -0700467
468 const char* GetFile() const {
469 return file_;
470 }
471
472 unsigned int GetLineNumber() const {
473 return line_number_;
474 }
475
476 LogSeverity GetSeverity() const {
477 return severity_;
478 }
479
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800480 const char* GetTag() const { return tag_; }
481
Dan Albert58310b42015-03-13 23:06:01 -0700482 int GetError() const {
483 return error_;
484 }
485
486 std::ostream& GetBuffer() {
487 return buffer_;
488 }
489
490 std::string ToString() const {
491 return buffer_.str();
492 }
493
494 private:
495 std::ostringstream buffer_;
496 const char* const file_;
497 const unsigned int line_number_;
498 const LogSeverity severity_;
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800499 const char* const tag_;
Dan Albert58310b42015-03-13 23:06:01 -0700500 const int error_;
501
502 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
503};
504
Tom Cherryd044eaa2020-01-10 17:18:55 -0800505LogMessage::LogMessage(const char* file, unsigned int line, LogId, LogSeverity severity,
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800506 const char* tag, int error)
Tom Cherryd044eaa2020-01-10 17:18:55 -0800507 : LogMessage(file, line, severity, tag, error) {}
508
509LogMessage::LogMessage(const char* file, unsigned int line, LogSeverity severity, const char* tag,
510 int error)
511 : data_(new LogMessageData(file, line, severity, tag, error)) {}
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800512
Dan Albert58310b42015-03-13 23:06:01 -0700513LogMessage::~LogMessage() {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700514 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampe1f5fb432016-09-23 16:37:12 -0700515 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700516 return;
517 }
518
Dan Albert58310b42015-03-13 23:06:01 -0700519 // Finish constructing the message.
520 if (data_->GetError() != -1) {
521 data_->GetBuffer() << ": " << strerror(data_->GetError());
522 }
523 std::string msg(data_->ToString());
524
Andreas Gampe2819c0b2018-12-05 11:26:14 -0800525 if (data_->GetSeverity() == FATAL) {
526#ifdef __ANDROID__
527 // Set the bionic abort message early to avoid liblog doing it
528 // with the individual lines, so that we get the whole message.
529 android_set_abort_message(msg.c_str());
530#endif
531 }
532
Spencer Low765ae6b2015-09-17 19:36:10 -0700533 {
534 // Do the actual logging with the lock held.
Yabin Cui0c689532017-01-23 10:29:23 -0800535 std::lock_guard<std::mutex> lock(LoggingLock());
Spencer Low765ae6b2015-09-17 19:36:10 -0700536 if (msg.find('\n') == std::string::npos) {
Tom Cherryd044eaa2020-01-10 17:18:55 -0800537 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(), data_->GetTag(),
538 msg.c_str());
Spencer Low765ae6b2015-09-17 19:36:10 -0700539 } else {
540 msg += '\n';
541 size_t i = 0;
542 while (i < msg.size()) {
543 size_t nl = msg.find('\n', i);
544 msg[nl] = '\0';
Tom Cherryd044eaa2020-01-10 17:18:55 -0800545 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetSeverity(), data_->GetTag(),
546 &msg[i]);
Andreas Gampeb4e32f32016-10-04 19:17:07 -0700547 // Undo the zero-termination so we can give the complete message to the aborter.
548 msg[nl] = '\n';
Spencer Low765ae6b2015-09-17 19:36:10 -0700549 i = nl + 1;
550 }
Dan Albert58310b42015-03-13 23:06:01 -0700551 }
552 }
553
554 // Abort if necessary.
555 if (data_->GetSeverity() == FATAL) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800556 static auto& liblog_functions = GetLibLogFunctions();
557 if (liblog_functions) {
558 liblog_functions->__android_log_call_aborter(msg.c_str());
559 } else {
560 Aborter()(msg.c_str());
561 }
Dan Albert58310b42015-03-13 23:06:01 -0700562 }
563}
564
565std::ostream& LogMessage::stream() {
566 return data_->GetBuffer();
567}
568
Tom Cherryd044eaa2020-01-10 17:18:55 -0800569void LogMessage::LogLine(const char* file, unsigned int line, LogSeverity severity, const char* tag,
570 const char* message) {
Tom Cherry349b0c42020-01-08 14:47:42 -0800571 static auto& liblog_functions = GetLibLogFunctions();
572 auto priority = LogSeverityToPriority(severity);
Andreas Gampe1923e762018-03-05 10:00:19 -0800573 if (tag == nullptr) {
574 std::lock_guard<std::recursive_mutex> lock(TagLock());
575 if (gDefaultTag == nullptr) {
576 gDefaultTag = new std::string(getprogname());
577 }
Tom Cherry349b0c42020-01-08 14:47:42 -0800578
579 if (liblog_functions) {
580 __android_logger_data logger_data = {sizeof(__android_logger_data), LOG_ID_DEFAULT, priority,
581 gDefaultTag->c_str(), file, line};
582 __android_log_write_logger_data(&logger_data, message);
583 } else {
584 Logger()(DEFAULT, severity, gDefaultTag->c_str(), file, line, message);
585 }
Andreas Gampe1923e762018-03-05 10:00:19 -0800586 } else {
Tom Cherry349b0c42020-01-08 14:47:42 -0800587 if (liblog_functions) {
588 __android_logger_data logger_data = {
589 sizeof(__android_logger_data), LOG_ID_DEFAULT, priority, tag, file, line};
590 __android_log_write_logger_data(&logger_data, message);
591 } else {
592 Logger()(DEFAULT, severity, tag, file, line, message);
593 }
Andreas Gampe1923e762018-03-05 10:00:19 -0800594 }
Dan Albert58310b42015-03-13 23:06:01 -0700595}
596
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700597LogSeverity GetMinimumLogSeverity() {
598 return gMinimumLogSeverity;
599}
600
601LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
602 LogSeverity old_severity = gMinimumLogSeverity;
603 gMinimumLogSeverity = new_severity;
604 return old_severity;
605}
606
607ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
608 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700609}
610
611ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700612 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700613}
614
615} // namespace base
616} // namespace android