blob: 30d7f8d5799cb4de59d3026c48d722bc0a90f7c3 [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
Dan Albert58310b42015-03-13 23:06:01 -070039#include <iostream>
40#include <limits>
Josh Gao63bdcb52016-09-13 14:57:12 -070041#include <mutex>
Dan Albert58310b42015-03-13 23:06:01 -070042#include <sstream>
43#include <string>
Dan Albertb547c852015-03-27 11:20:14 -070044#include <utility>
Dan Albert58310b42015-03-13 23:06:01 -070045#include <vector>
46
Dan Albert58310b42015-03-13 23:06:01 -070047// Headers for LogMessage::LogLine.
48#ifdef __ANDROID__
Andreas Gampeaf05f3b2018-02-15 11:40:30 -080049#include <android/log.h>
Dan Albert58310b42015-03-13 23:06:01 -070050#include <android/set_abort_message.h>
Dan Albert58310b42015-03-13 23:06:01 -070051#else
52#include <sys/types.h>
53#include <unistd.h>
54#endif
55
Mark Salyzynff2dcd92016-09-28 15:54:45 -070056#include <android-base/macros.h>
57#include <android-base/strings.h>
Josh Gao5791e212018-03-16 14:25:42 -070058#include <android-base/threads.h>
Elliott Hughesc1fd4922015-11-11 18:02:29 +000059
Dan Albert5c190402015-04-29 11:32:23 -070060namespace {
Dan Albert5c190402015-04-29 11:32:23 -070061#if defined(__GLIBC__)
62const char* getprogname() {
63 return program_invocation_short_name;
64}
Josh Gao63bdcb52016-09-13 14:57:12 -070065#elif defined(_WIN32)
Dan Albert5c190402015-04-29 11:32:23 -070066const char* getprogname() {
67 static bool first = true;
68 static char progname[MAX_PATH] = {};
69
70 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -070071 CHAR longname[MAX_PATH];
72 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
73 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
74 // String truncation or some other error.
75 strcpy(progname, "<unknown>");
76 } else {
77 strcpy(progname, basename(longname));
78 }
Dan Albert5c190402015-04-29 11:32:23 -070079 first = false;
80 }
81
82 return progname;
83}
Dan Albert5c190402015-04-29 11:32:23 -070084#endif
85} // namespace
86
Dan Albert58310b42015-03-13 23:06:01 -070087namespace android {
88namespace base {
89
Yabin Cui0c689532017-01-23 10:29:23 -080090static std::mutex& LoggingLock() {
91 static auto& logging_lock = *new std::mutex();
92 return logging_lock;
93}
Dan Albert58310b42015-03-13 23:06:01 -070094
Yabin Cui0c689532017-01-23 10:29:23 -080095static LogFunction& Logger() {
Dan Albertb547c852015-03-27 11:20:14 -070096#ifdef __ANDROID__
Yabin Cui0c689532017-01-23 10:29:23 -080097 static auto& logger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -070098#else
Yabin Cui0c689532017-01-23 10:29:23 -080099 static auto& logger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700100#endif
Yabin Cui0c689532017-01-23 10:29:23 -0800101 return logger;
102}
Dan Albertb547c852015-03-27 11:20:14 -0700103
Yabin Cui0c689532017-01-23 10:29:23 -0800104static AbortFunction& Aborter() {
105 static auto& aborter = *new AbortFunction(DefaultAborter);
106 return aborter;
107}
108
Andreas Gampe1923e762018-03-05 10:00:19 -0800109static std::recursive_mutex& TagLock() {
110 static auto& tag_lock = *new std::recursive_mutex();
111 return tag_lock;
112}
113static std::string* gDefaultTag;
114std::string GetDefaultTag() {
115 std::lock_guard<std::recursive_mutex> lock(TagLock());
116 if (gDefaultTag == nullptr) {
117 return "";
118 }
119 return *gDefaultTag;
120}
121void SetDefaultTag(const std::string& tag) {
122 std::lock_guard<std::recursive_mutex> lock(TagLock());
123 if (gDefaultTag != nullptr) {
124 delete gDefaultTag;
125 gDefaultTag = nullptr;
126 }
127 if (!tag.empty()) {
128 gDefaultTag = new std::string(tag);
129 }
Yabin Cui0c689532017-01-23 10:29:23 -0800130}
Andreas Gampe2691e332016-09-08 11:03:58 -0700131
Dan Albert7a87d052015-04-03 11:28:46 -0700132static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700133static LogSeverity gMinimumLogSeverity = INFO;
Dan Albert58310b42015-03-13 23:06:01 -0700134
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700135#if defined(__linux__)
136void KernelLogger(android::base::LogId, android::base::LogSeverity severity,
137 const char* tag, const char*, unsigned int, const char* msg) {
Andreas Gampe550829d2016-09-07 10:10:50 -0700138 // clang-format off
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700139 static constexpr int kLogSeverityToKernelLogLevel[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700140 [android::base::VERBOSE] = 7, // KERN_DEBUG (there is no verbose kernel log
141 // level)
142 [android::base::DEBUG] = 7, // KERN_DEBUG
143 [android::base::INFO] = 6, // KERN_INFO
144 [android::base::WARNING] = 4, // KERN_WARNING
145 [android::base::ERROR] = 3, // KERN_ERROR
146 [android::base::FATAL_WITHOUT_ABORT] = 2, // KERN_CRIT
147 [android::base::FATAL] = 2, // KERN_CRIT
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700148 };
Andreas Gampe550829d2016-09-07 10:10:50 -0700149 // clang-format on
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700150 static_assert(arraysize(kLogSeverityToKernelLogLevel) == android::base::FATAL + 1,
151 "Mismatch in size of kLogSeverityToKernelLogLevel and values in LogSeverity");
152
153 static int klog_fd = TEMP_FAILURE_RETRY(open("/dev/kmsg", O_WRONLY | O_CLOEXEC));
154 if (klog_fd == -1) return;
155
156 int level = kLogSeverityToKernelLogLevel[severity];
157
158 // The kernel's printk buffer is only 1024 bytes.
159 // TODO: should we automatically break up long lines into multiple lines?
160 // Or we could log but with something like "..." at the end?
161 char buf[1024];
162 size_t size = snprintf(buf, sizeof(buf), "<%d>%s: %s\n", level, tag, msg);
163 if (size > sizeof(buf)) {
164 size = snprintf(buf, sizeof(buf), "<%d>%s: %zu-byte message too long for printk\n",
165 level, tag, size);
166 }
167
168 iovec iov[1];
169 iov[0].iov_base = buf;
170 iov[0].iov_len = size;
171 TEMP_FAILURE_RETRY(writev(klog_fd, iov, 1));
172}
173#endif
174
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800175void StderrLogger(LogId, LogSeverity severity, const char* tag, const char* file, unsigned int line,
176 const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700177 struct tm now;
178 time_t t = time(nullptr);
179
180#if defined(_WIN32)
181 localtime_s(&now, &t);
182#else
183 localtime_r(&t, &now);
184#endif
185
186 char timestamp[32];
187 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
188
Andreas Gampe550829d2016-09-07 10:10:50 -0700189 static const char log_characters[] = "VDIWEFF";
Spencer Lowbdab59a2015-08-11 16:00:13 -0700190 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
191 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700192 char severity_char = log_characters[severity];
Josh Gao5791e212018-03-16 14:25:42 -0700193 fprintf(stderr, "%s %c %s %5d %5" PRIu64 " %s:%u] %s\n", tag ? tag : "nullptr", severity_char,
194 timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700195}
196
Andreas Gampe2691e332016-09-08 11:03:58 -0700197void DefaultAborter(const char* abort_message) {
198#ifdef __ANDROID__
199 android_set_abort_message(abort_message);
200#else
201 UNUSED(abort_message);
202#endif
203 abort();
204}
205
Dan Albertb547c852015-03-27 11:20:14 -0700206
207#ifdef __ANDROID__
208LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
209}
210
Dan Albertb547c852015-03-27 11:20:14 -0700211void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
212 const char* file, unsigned int line,
213 const char* message) {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700214 static constexpr android_LogPriority kLogSeverityToAndroidLogPriority[] = {
Andreas Gampe550829d2016-09-07 10:10:50 -0700215 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
216 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
217 ANDROID_LOG_FATAL,
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700218 };
219 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
220 "Mismatch in size of kLogSeverityToAndroidLogPriority and values in LogSeverity");
221
Dan Albertb547c852015-03-27 11:20:14 -0700222 int priority = kLogSeverityToAndroidLogPriority[severity];
223 if (id == DEFAULT) {
224 id = default_log_id_;
225 }
226
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700227 static constexpr log_id kLogIdToAndroidLogId[] = {
228 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
229 };
230 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
231 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
Dan Albertb547c852015-03-27 11:20:14 -0700232 log_id lg_id = kLogIdToAndroidLogId[id];
233
234 if (priority == ANDROID_LOG_FATAL) {
235 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
236 message);
237 } else {
238 __android_log_buf_print(lg_id, priority, tag, "%s", message);
239 }
240}
241#endif
242
Andreas Gampe2691e332016-09-08 11:03:58 -0700243void InitLogging(char* argv[], LogFunction&& logger, AbortFunction&& aborter) {
Dan Albertb547c852015-03-27 11:20:14 -0700244 SetLogger(std::forward<LogFunction>(logger));
Andreas Gampe2691e332016-09-08 11:03:58 -0700245 SetAborter(std::forward<AbortFunction>(aborter));
Dan Albertb547c852015-03-27 11:20:14 -0700246
Dan Albert7a87d052015-04-03 11:28:46 -0700247 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700248 return;
249 }
250
Dan Albert7a87d052015-04-03 11:28:46 -0700251 gInitialized = true;
252
Dan Albert58310b42015-03-13 23:06:01 -0700253 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800254 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
255 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700256 if (argv != nullptr) {
Andreas Gampe1923e762018-03-05 10:00:19 -0800257 SetDefaultTag(basename(argv[0]));
Dan Albert58310b42015-03-13 23:06:01 -0700258 }
Dan Albert7a87d052015-04-03 11:28:46 -0700259
Dan Albert58310b42015-03-13 23:06:01 -0700260 const char* tags = getenv("ANDROID_LOG_TAGS");
261 if (tags == nullptr) {
262 return;
263 }
264
Dan Albert47328c92015-03-19 13:24:26 -0700265 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700266 for (size_t i = 0; i < specs.size(); ++i) {
267 // "tag-pattern:[vdiwefs]"
268 std::string spec(specs[i]);
269 if (spec.size() == 3 && StartsWith(spec, "*:")) {
270 switch (spec[2]) {
271 case 'v':
272 gMinimumLogSeverity = VERBOSE;
273 continue;
274 case 'd':
275 gMinimumLogSeverity = DEBUG;
276 continue;
277 case 'i':
278 gMinimumLogSeverity = INFO;
279 continue;
280 case 'w':
281 gMinimumLogSeverity = WARNING;
282 continue;
283 case 'e':
284 gMinimumLogSeverity = ERROR;
285 continue;
286 case 'f':
Andreas Gampe550829d2016-09-07 10:10:50 -0700287 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700288 continue;
289 // liblog will even suppress FATAL if you say 's' for silent, but that's
290 // crazy!
291 case 's':
Andreas Gampe550829d2016-09-07 10:10:50 -0700292 gMinimumLogSeverity = FATAL_WITHOUT_ABORT;
Dan Albert58310b42015-03-13 23:06:01 -0700293 continue;
294 }
295 }
296 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
297 << ")";
298 }
299}
300
Dan Albertb547c852015-03-27 11:20:14 -0700301void SetLogger(LogFunction&& logger) {
Yabin Cui0c689532017-01-23 10:29:23 -0800302 std::lock_guard<std::mutex> lock(LoggingLock());
303 Logger() = std::move(logger);
Dan Albertb547c852015-03-27 11:20:14 -0700304}
305
Andreas Gampe2691e332016-09-08 11:03:58 -0700306void SetAborter(AbortFunction&& aborter) {
Yabin Cui0c689532017-01-23 10:29:23 -0800307 std::lock_guard<std::mutex> lock(LoggingLock());
308 Aborter() = std::move(aborter);
Andreas Gampe2691e332016-09-08 11:03:58 -0700309}
310
Spencer Lowbdab59a2015-08-11 16:00:13 -0700311static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800312 // We can't use basename(3) even on Unix because the Mac doesn't
313 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700314 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800315 if (last_slash != nullptr) {
316 return last_slash + 1;
317 }
318#if defined(_WIN32)
319 const char* last_backslash = strrchr(file, '\\');
320 if (last_backslash != nullptr) {
321 return last_backslash + 1;
322 }
323#endif
324 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700325}
326
Dan Albert58310b42015-03-13 23:06:01 -0700327// This indirection greatly reduces the stack impact of having lots of
328// checks/logging in a function.
329class LogMessageData {
330 public:
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800331 LogMessageData(const char* file, unsigned int line, LogId id, LogSeverity severity,
332 const char* tag, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700333 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700334 line_number_(line),
335 id_(id),
336 severity_(severity),
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800337 tag_(tag),
338 error_(error) {}
Dan Albert58310b42015-03-13 23:06:01 -0700339
340 const char* GetFile() const {
341 return file_;
342 }
343
344 unsigned int GetLineNumber() const {
345 return line_number_;
346 }
347
348 LogSeverity GetSeverity() const {
349 return severity_;
350 }
351
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800352 const char* GetTag() const { return tag_; }
353
Dan Albert0c055862015-03-27 11:20:14 -0700354 LogId GetId() const {
355 return id_;
356 }
357
Dan Albert58310b42015-03-13 23:06:01 -0700358 int GetError() const {
359 return error_;
360 }
361
362 std::ostream& GetBuffer() {
363 return buffer_;
364 }
365
366 std::string ToString() const {
367 return buffer_.str();
368 }
369
370 private:
371 std::ostringstream buffer_;
372 const char* const file_;
373 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700374 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700375 const LogSeverity severity_;
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800376 const char* const tag_;
Dan Albert58310b42015-03-13 23:06:01 -0700377 const int error_;
378
379 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
380};
381
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800382LogMessage::LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity,
383 const char* tag, int error)
384 : data_(new LogMessageData(file, line, id, severity, tag, error)) {}
385
386LogMessage::LogMessage(const char* file, unsigned int line, LogId id, LogSeverity severity,
387 int error)
388 : LogMessage(file, line, id, severity, nullptr, error) {}
Dan Albert58310b42015-03-13 23:06:01 -0700389
390LogMessage::~LogMessage() {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700391 // Check severity again. This is duplicate work wrt/ LOG macros, but not LOG_STREAM.
Andreas Gampe1f5fb432016-09-23 16:37:12 -0700392 if (!WOULD_LOG(data_->GetSeverity())) {
Andreas Gampe19ff8f12016-09-23 13:31:52 -0700393 return;
394 }
395
Dan Albert58310b42015-03-13 23:06:01 -0700396 // Finish constructing the message.
397 if (data_->GetError() != -1) {
398 data_->GetBuffer() << ": " << strerror(data_->GetError());
399 }
400 std::string msg(data_->ToString());
401
Spencer Low765ae6b2015-09-17 19:36:10 -0700402 {
403 // Do the actual logging with the lock held.
Yabin Cui0c689532017-01-23 10:29:23 -0800404 std::lock_guard<std::mutex> lock(LoggingLock());
Spencer Low765ae6b2015-09-17 19:36:10 -0700405 if (msg.find('\n') == std::string::npos) {
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800406 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(), data_->GetSeverity(),
407 data_->GetTag(), msg.c_str());
Spencer Low765ae6b2015-09-17 19:36:10 -0700408 } else {
409 msg += '\n';
410 size_t i = 0;
411 while (i < msg.size()) {
412 size_t nl = msg.find('\n', i);
413 msg[nl] = '\0';
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800414 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(), data_->GetSeverity(),
415 data_->GetTag(), &msg[i]);
Andreas Gampeb4e32f32016-10-04 19:17:07 -0700416 // Undo the zero-termination so we can give the complete message to the aborter.
417 msg[nl] = '\n';
Spencer Low765ae6b2015-09-17 19:36:10 -0700418 i = nl + 1;
419 }
Dan Albert58310b42015-03-13 23:06:01 -0700420 }
421 }
422
423 // Abort if necessary.
424 if (data_->GetSeverity() == FATAL) {
Yabin Cui0c689532017-01-23 10:29:23 -0800425 Aborter()(msg.c_str());
Dan Albert58310b42015-03-13 23:06:01 -0700426 }
427}
428
429std::ostream& LogMessage::stream() {
430 return data_->GetBuffer();
431}
432
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800433void LogMessage::LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
434 const char* tag, const char* message) {
Andreas Gampe1923e762018-03-05 10:00:19 -0800435 if (tag == nullptr) {
436 std::lock_guard<std::recursive_mutex> lock(TagLock());
437 if (gDefaultTag == nullptr) {
438 gDefaultTag = new std::string(getprogname());
439 }
440 Logger()(id, severity, gDefaultTag->c_str(), file, line, message);
441 } else {
442 Logger()(id, severity, tag, file, line, message);
443 }
Dan Albert58310b42015-03-13 23:06:01 -0700444}
445
Tomasz Wasilczykc2516002017-12-18 06:30:17 -0800446void LogMessage::LogLine(const char* file, unsigned int line, LogId id, LogSeverity severity,
447 const char* message) {
448 LogLine(file, line, id, severity, nullptr, message);
449}
450
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700451LogSeverity GetMinimumLogSeverity() {
452 return gMinimumLogSeverity;
453}
454
455LogSeverity SetMinimumLogSeverity(LogSeverity new_severity) {
456 LogSeverity old_severity = gMinimumLogSeverity;
457 gMinimumLogSeverity = new_severity;
458 return old_severity;
459}
460
461ScopedLogSeverity::ScopedLogSeverity(LogSeverity new_severity) {
462 old_ = SetMinimumLogSeverity(new_severity);
Dan Albert58310b42015-03-13 23:06:01 -0700463}
464
465ScopedLogSeverity::~ScopedLogSeverity() {
Elliott Hughes7bc87a52016-08-04 16:09:39 -0700466 SetMinimumLogSeverity(old_);
Dan Albert58310b42015-03-13 23:06:01 -0700467}
468
469} // namespace base
470} // namespace android