2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
21 #include "android-base/logging.h"
25 // For getprogname(3) or program_invocation_short_name.
26 #if defined(__ANDROID__) || defined(__APPLE__)
28 #elif defined(__GLIBC__)
43 #include "android-base/macros.h"
44 #include "android-base/strings.h"
45 #include "cutils/threads.h"
47 // Headers for LogMessage::LogLine.
49 #include <android/set_abort_message.h>
50 #include "cutils/log.h"
52 #include <sys/types.h>
57 #if defined(__APPLE__)
58 #include "AvailabilityMacros.h" // For MAC_OS_X_VERSION_MAX_ALLOWED
61 #include <sys/syscall.h>
64 #elif defined(__linux__) && !defined(__ANDROID__)
72 typedef uint32_t thread_id;
74 typedef pid_t thread_id;
77 static thread_id GetThreadId() {
78 #if defined(__BIONIC__)
80 #elif defined(__APPLE__)
81 return syscall(SYS_thread_selfid);
82 #elif defined(__linux__)
83 return syscall(__NR_gettid);
85 return GetCurrentThreadId();
92 using std::lock_guard;
94 #if defined(__GLIBC__)
95 const char* getprogname() {
96 return program_invocation_short_name;
101 const char* getprogname() {
102 static bool first = true;
103 static char progname[MAX_PATH] = {};
106 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>");
112 strcpy(progname, basename(longname));
123 InitializeCriticalSection(&critical_section_);
126 DeleteCriticalSection(&critical_section_);
130 EnterCriticalSection(&critical_section_);
134 LeaveCriticalSection(&critical_section_);
138 CRITICAL_SECTION critical_section_;
141 template <typename LockT>
144 explicit lock_guard(LockT& lock) : lock_(lock) {
155 DISALLOW_COPY_AND_ASSIGN(lock_guard);
163 static auto& logging_lock = *new mutex();
166 static auto& gLogger = *new LogFunction(LogdLogger());
168 static auto& gLogger = *new LogFunction(StderrLogger);
171 static bool gInitialized = false;
172 static LogSeverity gMinimumLogSeverity = INFO;
173 static auto& gProgramInvocationName = *new std::unique_ptr<std::string>();
175 LogSeverity GetMinimumLogSeverity() {
176 return gMinimumLogSeverity;
179 static const char* ProgramInvocationName() {
180 if (gProgramInvocationName == nullptr) {
181 gProgramInvocationName.reset(new std::string(getprogname()));
184 return gProgramInvocationName->c_str();
187 void StderrLogger(LogId, LogSeverity severity, const char*, const char* file,
188 unsigned int line, const char* message) {
189 static const char log_characters[] = "VDIWEF";
190 static_assert(arraysize(log_characters) - 1 == FATAL + 1,
191 "Mismatch in size of log_characters and values in LogSeverity");
192 char severity_char = log_characters[severity];
193 fprintf(stderr, "%s %c %5d %5d %s:%u] %s\n", ProgramInvocationName(),
194 severity_char, getpid(), GetThreadId(), file, line, message);
199 LogdLogger::LogdLogger(LogId default_log_id) : default_log_id_(default_log_id) {
202 static const android_LogPriority kLogSeverityToAndroidLogPriority[] = {
203 ANDROID_LOG_VERBOSE, ANDROID_LOG_DEBUG, ANDROID_LOG_INFO,
204 ANDROID_LOG_WARN, ANDROID_LOG_ERROR, ANDROID_LOG_FATAL,
206 static_assert(arraysize(kLogSeverityToAndroidLogPriority) == FATAL + 1,
207 "Mismatch in size of kLogSeverityToAndroidLogPriority and values "
210 static const log_id kLogIdToAndroidLogId[] = {
211 LOG_ID_MAX, LOG_ID_MAIN, LOG_ID_SYSTEM,
213 static_assert(arraysize(kLogIdToAndroidLogId) == SYSTEM + 1,
214 "Mismatch in size of kLogIdToAndroidLogId and values in LogId");
216 void LogdLogger::operator()(LogId id, LogSeverity severity, const char* tag,
217 const char* file, unsigned int line,
218 const char* message) {
219 int priority = kLogSeverityToAndroidLogPriority[severity];
221 id = default_log_id_;
224 log_id lg_id = kLogIdToAndroidLogId[id];
226 if (priority == ANDROID_LOG_FATAL) {
227 __android_log_buf_print(lg_id, priority, tag, "%s:%u] %s", file, line,
230 __android_log_buf_print(lg_id, priority, tag, "%s", message);
235 void InitLogging(char* argv[], LogFunction&& logger) {
236 SetLogger(std::forward<LogFunction>(logger));
240 void InitLogging(char* argv[]) {
247 // Stash the command line for later use. We can use /proc/self/cmdline on
248 // Linux to recover this, but we don't have that luxury on the Mac/Windows,
249 // and there are a couple of argv[0] variants that are commonly used.
250 if (argv != nullptr) {
251 gProgramInvocationName.reset(new std::string(basename(argv[0])));
254 const char* tags = getenv("ANDROID_LOG_TAGS");
255 if (tags == nullptr) {
259 std::vector<std::string> specs = Split(tags, " ");
260 for (size_t i = 0; i < specs.size(); ++i) {
261 // "tag-pattern:[vdiwefs]"
262 std::string spec(specs[i]);
263 if (spec.size() == 3 && StartsWith(spec, "*:")) {
266 gMinimumLogSeverity = VERBOSE;
269 gMinimumLogSeverity = DEBUG;
272 gMinimumLogSeverity = INFO;
275 gMinimumLogSeverity = WARNING;
278 gMinimumLogSeverity = ERROR;
281 gMinimumLogSeverity = FATAL;
283 // liblog will even suppress FATAL if you say 's' for silent, but that's
286 gMinimumLogSeverity = FATAL;
290 LOG(FATAL) << "unsupported '" << spec << "' in ANDROID_LOG_TAGS (" << tags
295 void SetLogger(LogFunction&& logger) {
296 lock_guard<mutex> lock(logging_lock);
297 gLogger = std::move(logger);
300 static const char* GetFileBasename(const char* file) {
301 // We can't use basename(3) even on Unix because the Mac doesn't
302 // have a non-modifying basename.
303 const char* last_slash = strrchr(file, '/');
304 if (last_slash != nullptr) {
305 return last_slash + 1;
308 const char* last_backslash = strrchr(file, '\\');
309 if (last_backslash != nullptr) {
310 return last_backslash + 1;
316 // This indirection greatly reduces the stack impact of having lots of
317 // checks/logging in a function.
318 class LogMessageData {
320 LogMessageData(const char* file, unsigned int line, LogId id,
321 LogSeverity severity, int error)
322 : file_(GetFileBasename(file)),
329 const char* GetFile() const {
333 unsigned int GetLineNumber() const {
337 LogSeverity GetSeverity() const {
341 LogId GetId() const {
345 int GetError() const {
349 std::ostream& GetBuffer() {
353 std::string ToString() const {
354 return buffer_.str();
358 std::ostringstream buffer_;
359 const char* const file_;
360 const unsigned int line_number_;
362 const LogSeverity severity_;
365 DISALLOW_COPY_AND_ASSIGN(LogMessageData);
368 LogMessage::LogMessage(const char* file, unsigned int line, LogId id,
369 LogSeverity severity, int error)
370 : data_(new LogMessageData(file, line, id, severity, error)) {
373 LogMessage::~LogMessage() {
374 // Finish constructing the message.
375 if (data_->GetError() != -1) {
376 data_->GetBuffer() << ": " << strerror(data_->GetError());
378 std::string msg(data_->ToString());
381 // Do the actual logging with the lock held.
382 lock_guard<mutex> lock(logging_lock);
383 if (msg.find('\n') == std::string::npos) {
384 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
385 data_->GetSeverity(), msg.c_str());
389 while (i < msg.size()) {
390 size_t nl = msg.find('\n', i);
392 LogLine(data_->GetFile(), data_->GetLineNumber(), data_->GetId(),
393 data_->GetSeverity(), &msg[i]);
399 // Abort if necessary.
400 if (data_->GetSeverity() == FATAL) {
402 android_set_abort_message(msg.c_str());
408 std::ostream& LogMessage::stream() {
409 return data_->GetBuffer();
412 void LogMessage::LogLine(const char* file, unsigned int line, LogId id,
413 LogSeverity severity, const char* message) {
414 const char* tag = ProgramInvocationName();
415 gLogger(id, severity, tag, file, line, message);
418 ScopedLogSeverity::ScopedLogSeverity(LogSeverity level) {
419 old_ = gMinimumLogSeverity;
420 gMinimumLogSeverity = level;
423 ScopedLogSeverity::~ScopedLogSeverity() {
424 gMinimumLogSeverity = old_;
428 } // namespace android