blob: 959bb8b0598018239b6fa74351eeee0a05f7be80 [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
Spencer Lowac3f7d92015-05-19 22:12:06 -070017#ifdef _WIN32
18#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
Dan Albert7a87d052015-04-03 11:28:46 -070023#include <libgen.h>
Elliott Hughes4e5fd112016-06-21 14:25:44 -070024#include <time.h>
Dan Albert7a87d052015-04-03 11:28:46 -070025
26// For getprogname(3) or program_invocation_short_name.
27#if defined(__ANDROID__) || defined(__APPLE__)
28#include <stdlib.h>
29#elif defined(__GLIBC__)
30#include <errno.h>
31#endif
32
Dan Albert58310b42015-03-13 23:06:01 -070033#include <iostream>
34#include <limits>
35#include <sstream>
36#include <string>
Dan Albertb547c852015-03-27 11:20:14 -070037#include <utility>
Dan Albert58310b42015-03-13 23:06:01 -070038#include <vector>
39
Dan Albert5c190402015-04-29 11:32:23 -070040#ifndef _WIN32
41#include <mutex>
Dan Albert5c190402015-04-29 11:32:23 -070042#endif
43
Elliott Hughes4f713192015-12-04 22:00:26 -080044#include "android-base/macros.h"
45#include "android-base/strings.h"
Dan Albert58310b42015-03-13 23:06:01 -070046
47// Headers for LogMessage::LogLine.
48#ifdef __ANDROID__
49#include <android/set_abort_message.h>
Elliott Hughese5dd71a2016-07-28 15:15:28 -070050#include "log/log.h"
Dan Albert58310b42015-03-13 23:06:01 -070051#else
52#include <sys/types.h>
53#include <unistd.h>
54#endif
55
Elliott Hughesc1fd4922015-11-11 18:02:29 +000056// For gettid.
57#if defined(__APPLE__)
58#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
59#include <stdint.h>
60#include <stdlib.h>
61#include <sys/syscall.h>
62#include <sys/time.h>
63#include <unistd.h>
64#elif defined(__linux__) && !defined(__ANDROID__)
65#include <syscall.h>
66#include <unistd.h>
67#elif defined(_WIN32)
68#include <windows.h>
69#endif
70
Dan Willemsen86cf9412016-02-03 23:29:32 -080071#if defined(_WIN32)
72typedef uint32_t thread_id;
73#else
74typedef pid_t thread_id;
75#endif
76
77static thread_id GetThreadId() {
Elliott Hughesc1fd4922015-11-11 18:02:29 +000078#if defined(__BIONIC__)
79 return gettid();
80#elif defined(__APPLE__)
81 return syscall(SYS_thread_selfid);
82#elif defined(__linux__)
83 return syscall(__NR_gettid);
84#elif defined(_WIN32)
85 return GetCurrentThreadId();
86#endif
87}
88
Dan Albert5c190402015-04-29 11:32:23 -070089namespace {
90#ifndef _WIN32
91using std::mutex;
92using std::lock_guard;
93
94#if defined(__GLIBC__)
95const char* getprogname() {
96 return program_invocation_short_name;
97}
98#endif
99
100#else
101const char* getprogname() {
102 static bool first = true;
103 static char progname[MAX_PATH] = {};
104
105 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700106 CHAR longname[MAX_PATH];
107 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
108 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
109 // String truncation or some other error.
110 strcpy(progname, "<unknown>");
111 } else {
112 strcpy(progname, basename(longname));
113 }
Dan Albert5c190402015-04-29 11:32:23 -0700114 first = false;
115 }
116
117 return progname;
118}
119
120class mutex {
121 public:
122 mutex() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700123 InitializeCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700124 }
125 ~mutex() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700126 DeleteCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700127 }
128
129 void lock() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700130 EnterCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700131 }
132
133 void unlock() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700134 LeaveCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700135 }
136
137 private:
Spencer Lowbdab59a2015-08-11 16:00:13 -0700138 CRITICAL_SECTION critical_section_;
Dan Albert5c190402015-04-29 11:32:23 -0700139};
140
141template <typename LockT>
142class lock_guard {
143 public:
144 explicit lock_guard(LockT& lock) : lock_(lock) {
145 lock_.lock();
146 }
147
148 ~lock_guard() {
149 lock_.unlock();
150 }
151
152 private:
153 LockT& lock_;
154
155 DISALLOW_COPY_AND_ASSIGN(lock_guard);
156};
157#endif
158} // namespace
159
Dan Albert58310b42015-03-13 23:06:01 -0700160namespace android {
161namespace base {
162
Josh Gao7df6b5f2015-11-12 11:54:47 -0800163static auto& logging_lock = *new mutex();
Dan Albert58310b42015-03-13 23:06:01 -0700164
Dan Albertb547c852015-03-27 11:20:14 -0700165#ifdef __ANDROID__
Josh Gao7df6b5f2015-11-12 11:54:47 -0800166static auto& gLogger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700167#else
Josh Gao7df6b5f2015-11-12 11:54:47 -0800168static auto& gLogger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700169#endif
170
Dan Albert7a87d052015-04-03 11:28:46 -0700171static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700172static LogSeverity gMinimumLogSeverity = INFO;
Josh Gao7df6b5f2015-11-12 11:54:47 -0800173static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
Dan Albert58310b42015-03-13 23:06:01 -0700174
Spencer Low765ae6b2015-09-17 19:36:10 -0700175LogSeverity GetMinimumLogSeverity() {
176 return gMinimumLogSeverity;
177}
178
Dan Albert7a87d052015-04-03 11:28:46 -0700179static const char* ProgramInvocationName() {
180 if (gProgramInvocationName == nullptr) {
181 gProgramInvocationName.reset(new std::string(getprogname()));
182 }
Dan Albert58310b42015-03-13 23:06:01 -0700183
Dan Albert7a87d052015-04-03 11:28:46 -0700184 return gProgramInvocationName->c_str();
Dan Albert58310b42015-03-13 23:06:01 -0700185}
186
Dan Albertb547c852015-03-27 11:20:14 -0700187void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
188 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700189 struct tm now;
190 time_t t = time(nullptr);
191
192#if defined(_WIN32)
193 localtime_s(&now, &t);
194#else
195 localtime_r(&t, &now);
196#endif
197
198 char timestamp[32];
199 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
200
Spencer Lowbdab59a2015-08-11 16:00:13 -0700201 static const char log_characters[] = "VDIWEF";
202 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
203 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700204 char severity_char = log_characters[severity];
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700205 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
206 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700207}
208
209
210#ifdef __ANDROID__
211LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
212}
213
214static const android_LogPriority kLogSeverityToAndroidLogPriority[] = {
215 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
216 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
217};
218static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
219 "Mismatch in size of kLogSeverityToAndroidLogPriority and values "
220 "in LogSeverity");
221
222static const log_id kLogIdToAndroidLogId[] = {
223 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
224};
225static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
226 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
227
228void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
229 const char* file, unsigned int line,
230 const char* message) {
231 int priority = kLogSeverityToAndroidLogPriority[severity];
232 if (id == DEFAULT) {
233 id = default_log_id_;
234 }
235
236 log_id lg_id = kLogIdToAndroidLogId[id];
237
238 if (priority == ANDROID_LOG_FATAL) {
239 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
240 message);
241 } else {
242 __android_log_buf_print(lg_id, priority, tag, "%s", message);
243 }
244}
245#endif
246
247void InitLogging(char* argv[], LogFunction&& logger) {
248 SetLogger(std::forward<LogFunction>(logger));
249 InitLogging(argv);
250}
251
Dan Albert58310b42015-03-13 23:06:01 -0700252void InitLogging(char* argv[]) {
Dan Albert7a87d052015-04-03 11:28:46 -0700253 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700254 return;
255 }
256
Dan Albert7a87d052015-04-03 11:28:46 -0700257 gInitialized = true;
258
Dan Albert58310b42015-03-13 23:06:01 -0700259 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800260 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
261 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700262 if (argv != nullptr) {
Dan Albert7a87d052015-04-03 11:28:46 -0700263 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Albert58310b42015-03-13 23:06:01 -0700264 }
Dan Albert7a87d052015-04-03 11:28:46 -0700265
Dan Albert58310b42015-03-13 23:06:01 -0700266 const char* tags = getenv("ANDROID_LOG_TAGS");
267 if (tags == nullptr) {
268 return;
269 }
270
Dan Albert47328c92015-03-19 13:24:26 -0700271 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700272 for (size_t i = 0; i < specs.size(); ++i) {
273 // "tag-pattern:[vdiwefs]"
274 std::string spec(specs[i]);
275 if (spec.size() == 3 && StartsWith(spec, "*:")) {
276 switch (spec[2]) {
277 case 'v':
278 gMinimumLogSeverity = VERBOSE;
279 continue;
280 case 'd':
281 gMinimumLogSeverity = DEBUG;
282 continue;
283 case 'i':
284 gMinimumLogSeverity = INFO;
285 continue;
286 case 'w':
287 gMinimumLogSeverity = WARNING;
288 continue;
289 case 'e':
290 gMinimumLogSeverity = ERROR;
291 continue;
292 case 'f':
293 gMinimumLogSeverity = FATAL;
294 continue;
295 // liblog will even suppress FATAL if you say 's' for silent, but that's
296 // crazy!
297 case 's':
298 gMinimumLogSeverity = FATAL;
299 continue;
300 }
301 }
302 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
303 << ")";
304 }
305}
306
Dan Albertb547c852015-03-27 11:20:14 -0700307void SetLogger(LogFunction&& logger) {
Dan Albert5c190402015-04-29 11:32:23 -0700308 lock_guard<mutex> lock(logging_lock);
Dan Albertb547c852015-03-27 11:20:14 -0700309 gLogger = std::move(logger);
310}
311
Spencer Lowbdab59a2015-08-11 16:00:13 -0700312static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800313 // We can't use basename(3) even on Unix because the Mac doesn't
314 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700315 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800316 if (last_slash != nullptr) {
317 return last_slash + 1;
318 }
319#if defined(_WIN32)
320 const char* last_backslash = strrchr(file, '\\');
321 if (last_backslash != nullptr) {
322 return last_backslash + 1;
323 }
324#endif
325 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700326}
327
Dan Albert58310b42015-03-13 23:06:01 -0700328// This indirection greatly reduces the stack impact of having lots of
329// checks/logging in a function.
330class LogMessageData {
331 public:
Dan Albert0c055862015-03-27 11:20:14 -0700332 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700333 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700334 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700335 line_number_(line),
336 id_(id),
337 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700338 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700339 }
340
341 const char* GetFile() const {
342 return file_;
343 }
344
345 unsigned int GetLineNumber() const {
346 return line_number_;
347 }
348
349 LogSeverity GetSeverity() const {
350 return severity_;
351 }
352
Dan Albert0c055862015-03-27 11:20:14 -0700353 LogId GetId() const {
354 return id_;
355 }
356
Dan Albert58310b42015-03-13 23:06:01 -0700357 int GetError() const {
358 return error_;
359 }
360
361 std::ostream& GetBuffer() {
362 return buffer_;
363 }
364
365 std::string ToString() const {
366 return buffer_.str();
367 }
368
369 private:
370 std::ostringstream buffer_;
371 const char* const file_;
372 const unsigned int line_number_;
Dan Albert0c055862015-03-27 11:20:14 -0700373 const LogId id_;
Dan Albert58310b42015-03-13 23:06:01 -0700374 const LogSeverity severity_;
375 const int error_;
376
377 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
378};
379
Dan Albert0c055862015-03-27 11:20:14 -0700380LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700381 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700382 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700383}
384
385LogMessage::~LogMessage() {
Dan Albert58310b42015-03-13 23:06:01 -0700386 // Finish constructing the message.
387 if (data_->GetError() != -1) {
388 data_->GetBuffer() << ": " << strerror(data_->GetError());
389 }
390 std::string msg(data_->ToString());
391
Spencer Low765ae6b2015-09-17 19:36:10 -0700392 {
393 // Do the actual logging with the lock held.
394 lock_guard<mutex> lock(logging_lock);
395 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700396 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700397 data_->GetSeverity(), msg.c_str());
398 } else {
399 msg += '\n';
400 size_t i = 0;
401 while (i < msg.size()) {
402 size_t nl = msg.find('\n', i);
403 msg[nl] = '\0';
404 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
405 data_->GetSeverity(), &msg[i]);
406 i = nl + 1;
407 }
Dan Albert58310b42015-03-13 23:06:01 -0700408 }
409 }
410
411 // Abort if necessary.
412 if (data_->GetSeverity() == FATAL) {
413#ifdef __ANDROID__
414 android_set_abort_message(msg.c_str());
415#endif
416 abort();
417 }
418}
419
420std::ostream& LogMessage::stream() {
421 return data_->GetBuffer();
422}
423
Dan Albert0c055862015-03-27 11:20:14 -0700424void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700425 LogSeverity severity, const char* message) {
Dan Albert7a87d052015-04-03 11:28:46 -0700426 const char* tag = ProgramInvocationName();
Dan Albertb547c852015-03-27 11:20:14 -0700427 gLogger(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700428}
429
Dan Albert58310b42015-03-13 23:06:01 -0700430ScopedLogSeverity::ScopedLogSeverity(LogSeverity level) {
431 old_ = gMinimumLogSeverity;
432 gMinimumLogSeverity = level;
433}
434
435ScopedLogSeverity::~ScopedLogSeverity() {
436 gMinimumLogSeverity = old_;
437}
438
439} // namespace base
440} // namespace android