blob: 769c266c994c4b814942dcc5d6ae1151f209caf1 [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 Albert7dfb61d2015-03-20 13:46:28 -070046#include "cutils/threads.h"
Dan Albert58310b42015-03-13 23:06:01 -070047
48// Headers for LogMessage::LogLine.
49#ifdef __ANDROID__
50#include <android/set_abort_message.h>
51#include "cutils/log.h"
52#else
53#include <sys/types.h>
54#include <unistd.h>
55#endif
56
Elliott Hughesc1fd4922015-11-11 18:02:29 +000057// For gettid.
58#if defined(__APPLE__)
59#include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
60#include <stdint.h>
61#include <stdlib.h>
62#include <sys/syscall.h>
63#include <sys/time.h>
64#include <unistd.h>
65#elif defined(__linux__) && !defined(__ANDROID__)
66#include <syscall.h>
67#include <unistd.h>
68#elif defined(_WIN32)
69#include <windows.h>
70#endif
71
Dan Willemsen86cf9412016-02-03 23:29:32 -080072#if defined(_WIN32)
73typedef uint32_t thread_id;
74#else
75typedef pid_t thread_id;
76#endif
77
78static thread_id GetThreadId() {
Elliott Hughesc1fd4922015-11-11 18:02:29 +000079#if defined(__BIONIC__)
80 return gettid();
81#elif defined(__APPLE__)
82 return syscall(SYS_thread_selfid);
83#elif defined(__linux__)
84 return syscall(__NR_gettid);
85#elif defined(_WIN32)
86 return GetCurrentThreadId();
87#endif
88}
89
Dan Albert5c190402015-04-29 11:32:23 -070090namespace {
91#ifndef _WIN32
92using std::mutex;
93using std::lock_guard;
94
95#if defined(__GLIBC__)
96const char* getprogname() {
97 return program_invocation_short_name;
98}
99#endif
100
101#else
102const char* getprogname() {
103 static bool first = true;
104 static char progname[MAX_PATH] = {};
105
106 if (first) {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700107 CHAR longname[MAX_PATH];
108 DWORD nchars = GetModuleFileNameA(nullptr, longname, arraysize(longname));
109 if ((nchars >= arraysize(longname)) || (nchars == 0)) {
110 // String truncation or some other error.
111 strcpy(progname, "<unknown>");
112 } else {
113 strcpy(progname, basename(longname));
114 }
Dan Albert5c190402015-04-29 11:32:23 -0700115 first = false;
116 }
117
118 return progname;
119}
120
121class mutex {
122 public:
123 mutex() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700124 InitializeCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700125 }
126 ~mutex() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700127 DeleteCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700128 }
129
130 void lock() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700131 EnterCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700132 }
133
134 void unlock() {
Spencer Lowbdab59a2015-08-11 16:00:13 -0700135 LeaveCriticalSection(&critical_section_);
Dan Albert5c190402015-04-29 11:32:23 -0700136 }
137
138 private:
Spencer Lowbdab59a2015-08-11 16:00:13 -0700139 CRITICAL_SECTION critical_section_;
Dan Albert5c190402015-04-29 11:32:23 -0700140};
141
142template <typename LockT>
143class lock_guard {
144 public:
145 explicit lock_guard(LockT& lock) : lock_(lock) {
146 lock_.lock();
147 }
148
149 ~lock_guard() {
150 lock_.unlock();
151 }
152
153 private:
154 LockT& lock_;
155
156 DISALLOW_COPY_AND_ASSIGN(lock_guard);
157};
158#endif
159} // namespace
160
Dan Albert58310b42015-03-13 23:06:01 -0700161namespace android {
162namespace base {
163
Josh Gao7df6b5f2015-11-12 11:54:47 -0800164static auto& logging_lock = *new mutex();
Dan Albert58310b42015-03-13 23:06:01 -0700165
Dan Albertb547c852015-03-27 11:20:14 -0700166#ifdef __ANDROID__
Josh Gao7df6b5f2015-11-12 11:54:47 -0800167static auto& gLogger = *new LogFunction(LogdLogger());
Dan Albertb547c852015-03-27 11:20:14 -0700168#else
Josh Gao7df6b5f2015-11-12 11:54:47 -0800169static auto& gLogger = *new LogFunction(StderrLogger);
Dan Albertb547c852015-03-27 11:20:14 -0700170#endif
171
Dan Albert7a87d052015-04-03 11:28:46 -0700172static bool gInitialized = false;
Dan Albert58310b42015-03-13 23:06:01 -0700173static LogSeverity gMinimumLogSeverity = INFO;
Josh Gao7df6b5f2015-11-12 11:54:47 -0800174static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
Dan Albert58310b42015-03-13 23:06:01 -0700175
Spencer Low765ae6b2015-09-17 19:36:10 -0700176LogSeverity GetMinimumLogSeverity() {
177 return gMinimumLogSeverity;
178}
179
Dan Albert7a87d052015-04-03 11:28:46 -0700180static const char* ProgramInvocationName() {
181 if (gProgramInvocationName == nullptr) {
182 gProgramInvocationName.reset(new std::string(getprogname()));
183 }
Dan Albert58310b42015-03-13 23:06:01 -0700184
Dan Albert7a87d052015-04-03 11:28:46 -0700185 return gProgramInvocationName->c_str();
Dan Albert58310b42015-03-13 23:06:01 -0700186}
187
Dan Albertb547c852015-03-27 11:20:14 -0700188void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
189 unsigned int line, const char* message) {
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700190 struct tm now;
191 time_t t = time(nullptr);
192
193#if defined(_WIN32)
194 localtime_s(&now, &t);
195#else
196 localtime_r(&t, &now);
197#endif
198
199 char timestamp[32];
200 strftime(timestamp, sizeof(timestamp), "%m-%d %H:%M:%S", &now);
201
Spencer Lowbdab59a2015-08-11 16:00:13 -0700202 static const char log_characters[] = "VDIWEF";
203 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
204 "Mismatch in size of log_characters and values in LogSeverity");
Dan Albertb547c852015-03-27 11:20:14 -0700205 char severity_char = log_characters[severity];
Elliott Hughes4e5fd112016-06-21 14:25:44 -0700206 fprintf(stderr, "%s %c %s %5d %5d %s:%u] %s\n", ProgramInvocationName(),
207 severity_char, timestamp, getpid(), GetThreadId(), file, line, message);
Dan Albertb547c852015-03-27 11:20:14 -0700208}
209
210
211#ifdef __ANDROID__
212LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
213}
214
215static const android_LogPriority kLogSeverityToAndroidLogPriority[] = {
216 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
217 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
218};
219static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
220 "Mismatch in size of kLogSeverityToAndroidLogPriority and values "
221 "in LogSeverity");
222
223static const log_id kLogIdToAndroidLogId[] = {
224 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
225};
226static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
227 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
228
229void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
230 const char* file, unsigned int line,
231 const char* message) {
232 int priority = kLogSeverityToAndroidLogPriority[severity];
233 if (id == DEFAULT) {
234 id = default_log_id_;
235 }
236
237 log_id lg_id = kLogIdToAndroidLogId[id];
238
239 if (priority == ANDROID_LOG_FATAL) {
240 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
241 message);
242 } else {
243 __android_log_buf_print(lg_id, priority, tag, "%s", message);
244 }
245}
246#endif
247
248void InitLogging(char* argv[], LogFunction&& logger) {
249 SetLogger(std::forward<LogFunction>(logger));
250 InitLogging(argv);
251}
252
Dan Albert58310b42015-03-13 23:06:01 -0700253void InitLogging(char* argv[]) {
Dan Albert7a87d052015-04-03 11:28:46 -0700254 if (gInitialized) {
Dan Albert58310b42015-03-13 23:06:01 -0700255 return;
256 }
257
Dan Albert7a87d052015-04-03 11:28:46 -0700258 gInitialized = true;
259
Dan Albert58310b42015-03-13 23:06:01 -0700260 // Stash the command line for later use. We can use /proc/self/cmdline on
Spencer Low363af562015-11-07 18:51:54 -0800261 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
262 // and there are a couple of argv[0] variants that are commonly used.
Dan Albert58310b42015-03-13 23:06:01 -0700263 if (argv != nullptr) {
Dan Albert7a87d052015-04-03 11:28:46 -0700264 gProgramInvocationName.reset(new std::string(basename(argv[0])));
Dan Albert58310b42015-03-13 23:06:01 -0700265 }
Dan Albert7a87d052015-04-03 11:28:46 -0700266
Dan Albert58310b42015-03-13 23:06:01 -0700267 const char* tags = getenv("ANDROID_LOG_TAGS");
268 if (tags == nullptr) {
269 return;
270 }
271
Dan Albert47328c92015-03-19 13:24:26 -0700272 std::vector<std::string> specs = Split(tags, " ");
Dan Albert58310b42015-03-13 23:06:01 -0700273 for (size_t i = 0; i < specs.size(); ++i) {
274 // "tag-pattern:[vdiwefs]"
275 std::string spec(specs[i]);
276 if (spec.size() == 3 && StartsWith(spec, "*:")) {
277 switch (spec[2]) {
278 case 'v':
279 gMinimumLogSeverity = VERBOSE;
280 continue;
281 case 'd':
282 gMinimumLogSeverity = DEBUG;
283 continue;
284 case 'i':
285 gMinimumLogSeverity = INFO;
286 continue;
287 case 'w':
288 gMinimumLogSeverity = WARNING;
289 continue;
290 case 'e':
291 gMinimumLogSeverity = ERROR;
292 continue;
293 case 'f':
294 gMinimumLogSeverity = FATAL;
295 continue;
296 // liblog will even suppress FATAL if you say 's' for silent, but that's
297 // crazy!
298 case 's':
299 gMinimumLogSeverity = FATAL;
300 continue;
301 }
302 }
303 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
304 << ")";
305 }
306}
307
Dan Albertb547c852015-03-27 11:20:14 -0700308void SetLogger(LogFunction&& logger) {
Dan Albert5c190402015-04-29 11:32:23 -0700309 lock_guard<mutex> lock(logging_lock);
Dan Albertb547c852015-03-27 11:20:14 -0700310 gLogger = std::move(logger);
311}
312
Spencer Lowbdab59a2015-08-11 16:00:13 -0700313static const char* GetFileBasename(const char* file) {
Spencer Low363af562015-11-07 18:51:54 -0800314 // We can't use basename(3) even on Unix because the Mac doesn't
315 // have a non-modifying basename.
Spencer Lowbdab59a2015-08-11 16:00:13 -0700316 const char* last_slash = strrchr(file, '/');
Spencer Low363af562015-11-07 18:51:54 -0800317 if (last_slash != nullptr) {
318 return last_slash + 1;
319 }
320#if defined(_WIN32)
321 const char* last_backslash = strrchr(file, '\\');
322 if (last_backslash != nullptr) {
323 return last_backslash + 1;
324 }
325#endif
326 return file;
Spencer Lowbdab59a2015-08-11 16:00:13 -0700327}
328
Dan Albert58310b42015-03-13 23:06:01 -0700329// This indirection greatly reduces the stack impact of having lots of
330// checks/logging in a function.
331class LogMessageData {
332 public:
Dan Albert0c055862015-03-27 11:20:14 -0700333 LogMessageData(const char* file, unsigned int line, LogId id,
Spencer Low765ae6b2015-09-17 19:36:10 -0700334 LogSeverity severity, int error)
Spencer Lowbdab59a2015-08-11 16:00:13 -0700335 : file_(GetFileBasename(file)),
Dan Albert0c055862015-03-27 11:20:14 -0700336 line_number_(line),
337 id_(id),
338 severity_(severity),
Spencer Low765ae6b2015-09-17 19:36:10 -0700339 error_(error) {
Dan Albert58310b42015-03-13 23:06:01 -0700340 }
341
342 const char* GetFile() const {
343 return file_;
344 }
345
346 unsigned int GetLineNumber() const {
347 return line_number_;
348 }
349
350 LogSeverity GetSeverity() const {
351 return severity_;
352 }
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_;
376 const int error_;
377
378 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
379};
380
Dan Albert0c055862015-03-27 11:20:14 -0700381LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
Dan Albert58310b42015-03-13 23:06:01 -0700382 LogSeverity severity, int error)
Spencer Low765ae6b2015-09-17 19:36:10 -0700383 : data_(new LogMessageData(file, line, id, severity, error)) {
Dan Albert58310b42015-03-13 23:06:01 -0700384}
385
386LogMessage::~LogMessage() {
Dan Albert58310b42015-03-13 23:06:01 -0700387 // Finish constructing the message.
388 if (data_->GetError() != -1) {
389 data_->GetBuffer() << ": " << strerror(data_->GetError());
390 }
391 std::string msg(data_->ToString());
392
Spencer Low765ae6b2015-09-17 19:36:10 -0700393 {
394 // Do the actual logging with the lock held.
395 lock_guard<mutex> lock(logging_lock);
396 if (msg.find('\n') == std::string::npos) {
Dan Albert0c055862015-03-27 11:20:14 -0700397 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
Spencer Low765ae6b2015-09-17 19:36:10 -0700398 data_->GetSeverity(), msg.c_str());
399 } else {
400 msg += '\n';
401 size_t i = 0;
402 while (i < msg.size()) {
403 size_t nl = msg.find('\n', i);
404 msg[nl] = '\0';
405 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
406 data_->GetSeverity(), &msg[i]);
407 i = nl + 1;
408 }
Dan Albert58310b42015-03-13 23:06:01 -0700409 }
410 }
411
412 // Abort if necessary.
413 if (data_->GetSeverity() == FATAL) {
414#ifdef __ANDROID__
415 android_set_abort_message(msg.c_str());
416#endif
417 abort();
418 }
419}
420
421std::ostream& LogMessage::stream() {
422 return data_->GetBuffer();
423}
424
Dan Albert0c055862015-03-27 11:20:14 -0700425void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
Dan Albertb547c852015-03-27 11:20:14 -0700426 LogSeverity severity, const char* message) {
Dan Albert7a87d052015-04-03 11:28:46 -0700427 const char* tag = ProgramInvocationName();
Dan Albertb547c852015-03-27 11:20:14 -0700428 gLogger(id, severity, tag, file, line, message);
Dan Albert58310b42015-03-13 23:06:01 -0700429}
430
Dan Albert58310b42015-03-13 23:06:01 -0700431ScopedLogSeverity::ScopedLogSeverity(LogSeverity level) {
432 old_ = gMinimumLogSeverity;
433 gMinimumLogSeverity = level;
434}
435
436ScopedLogSeverity::~ScopedLogSeverity() {
437 gMinimumLogSeverity = old_;
438}
439
440} // namespace base
441} // namespace android