1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/logging.h"
10 #include "base/macros.h"
11 #include "build/build_config.h"
16 typedef HANDLE FileHandle;
17 typedef HANDLE MutexHandle;
18 // Windows warns on using write(). It prefers _write().
19 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
20 // Windows doesn't define STDERR_FILENO. Define it here.
21 #define STDERR_FILENO 2
23 #elif defined(OS_MACOSX)
24 // In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
25 // in favor of OS_LOG (Unified Logging).
26 #include <AvailabilityMacros.h>
28 #if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
31 #else // !defined(OS_IOS)
32 #if !defined(MAC_OS_X_VERSION_10_12) || \
33 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
36 #endif // defined(OS_IOS)
44 #include <CoreFoundation/CoreFoundation.h>
45 #include <mach/mach.h>
46 #include <mach/mach_time.h>
47 #include <mach-o/dyld.h>
49 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
51 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
56 #if defined(OS_FUCHSIA)
57 #include <zircon/process.h>
58 #include <zircon/syscalls.h>
61 #if defined(OS_ANDROID)
62 #include <android/log.h>
65 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
74 #define MAX_PATH PATH_MAX
75 typedef FILE* FileHandle;
76 typedef pthread_mutex_t* MutexHandle;
87 #include "base/base_switches.h"
88 #include "base/callback.h"
89 #include "base/command_line.h"
90 #include "base/containers/stack.h"
91 #include "base/debug/activity_tracker.h"
92 #include "base/debug/alias.h"
93 #include "base/debug/debugger.h"
94 #include "base/debug/stack_trace.h"
95 #include "base/lazy_instance.h"
96 #include "base/posix/eintr_wrapper.h"
97 #include "base/strings/string_piece.h"
98 #include "base/strings/string_util.h"
99 #include "base/strings/stringprintf.h"
100 #include "base/strings/sys_string_conversions.h"
101 #include "base/strings/utf_string_conversions.h"
102 #include "base/synchronization/lock_impl.h"
103 #include "base/threading/platform_thread.h"
104 #include "base/vlog.h"
106 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
107 #include "base/posix/safe_strerror.h"
110 #if defined(OS_TIZEN)
111 #define LOG_TAG "CHROMIUM"
112 #include <dlog/dlog.h>
119 VlogInfo* g_vlog_info = nullptr;
120 VlogInfo* g_vlog_info_prev = nullptr;
122 const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
123 static_assert(LOG_NUM_SEVERITIES == arraysize(log_severity_names),
124 "Incorrect number of log_severity_names");
126 const char* log_severity_name(int severity) {
127 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
128 return log_severity_names[severity];
132 int g_min_log_level = 0;
134 LoggingDestination g_logging_destination = LOG_DEFAULT;
136 // For LOG_ERROR and above, always print to stderr.
137 const int kAlwaysPrintErrorLevel = LOG_ERROR;
139 // Which log file to use? This is initialized by InitLogging or
140 // will be lazily initialized to the default value when it is
143 typedef std::wstring PathString;
144 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
145 typedef std::string PathString;
147 PathString* g_log_file_name = nullptr;
149 // This file is lazily opened and the handle may be nullptr
150 FileHandle g_log_file = nullptr;
152 // What should be prepended to each message?
153 bool g_log_process_id = false;
154 bool g_log_thread_id = false;
155 bool g_log_timestamp = true;
156 bool g_log_tickcount = false;
158 // Should we pop up fatal debug messages in a dialog?
159 bool show_error_dialogs = false;
161 // An assert handler override specified by the client to be called instead of
162 // the debug message dialog and process termination. Assert handlers are stored
163 // in stack to allow overriding and restoring.
164 base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
165 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
167 // A log message handler that gets notified of every log message we process.
168 LogMessageHandlerFunction log_message_handler = nullptr;
170 #if !defined(OS_TIZEN)
171 // Helper functions to wrap platform differences.
173 int32_t CurrentProcessId() {
175 return GetCurrentProcessId();
176 #elif defined(OS_FUCHSIA)
177 zx_info_handle_basic_t basic = {};
178 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
179 sizeof(basic), nullptr, nullptr);
181 #elif defined(OS_POSIX)
186 uint64_t TickCount() {
188 return GetTickCount();
189 #elif defined(OS_FUCHSIA)
190 return zx_clock_get(ZX_CLOCK_MONOTONIC) /
191 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
192 #elif defined(OS_MACOSX)
193 return mach_absolute_time();
194 #elif defined(OS_NACL)
195 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
196 // So we have to use clock() for now.
198 #elif defined(OS_POSIX)
200 clock_gettime(CLOCK_MONOTONIC, &ts);
202 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
203 static_cast<int64_t>(ts.tv_nsec) / 1000;
205 return absolute_micro;
210 void DeleteFilePath(const PathString& log_name) {
212 DeleteFile(log_name.c_str());
213 #elif defined(OS_NACL)
214 // Do nothing; unlink() isn't supported on NaCl.
215 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
216 unlink(log_name.c_str());
218 #error Unsupported platform
222 PathString GetDefaultLogFile() {
224 // On Windows we use the same path as the exe.
225 wchar_t module_name[MAX_PATH];
226 GetModuleFileName(nullptr, module_name, MAX_PATH);
228 PathString log_name = module_name;
229 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
230 if (last_backslash != PathString::npos)
231 log_name.erase(last_backslash + 1);
232 log_name += L"debug.log";
234 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
235 // On other platforms we just use the current directory.
236 return PathString("debug.log");
240 // We don't need locks on Windows for atomically appending to files. The OS
241 // provides this functionality.
242 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
243 // This class acts as a wrapper for locking the logging files.
244 // LoggingLock::Init() should be called from the main thread before any logging
245 // is done. Then whenever logging, be sure to have a local LoggingLock
246 // instance on the stack. This will ensure that the lock is unlocked upon
247 // exiting the frame.
248 // LoggingLocks can not be nested.
259 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
262 lock_log_file = lock_log;
264 if (lock_log_file != LOCK_LOG_FILE)
265 log_lock = new base::internal::LockImpl();
271 static void LockLogging() {
272 if (lock_log_file == LOCK_LOG_FILE) {
273 pthread_mutex_lock(&log_mutex);
280 static void UnlockLogging() {
281 if (lock_log_file == LOCK_LOG_FILE) {
282 pthread_mutex_unlock(&log_mutex);
288 // The lock is used if log file locking is false. It helps us avoid problems
289 // with multiple threads writing to the log file at the same time. Use
290 // LockImpl directly instead of using Lock, because Lock makes logging calls.
291 static base::internal::LockImpl* log_lock;
293 // When we don't use a lock, we are using a global mutex. We need to do this
294 // because LockFileEx is not thread safe.
295 static pthread_mutex_t log_mutex;
297 static bool initialized;
298 static LogLockingState lock_log_file;
302 bool LoggingLock::initialized = false;
304 base::internal::LockImpl* LoggingLock::log_lock = nullptr;
306 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
308 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
310 #endif // OS_POSIX || OS_FUCHSIA
312 // Called by logging functions to ensure that |g_log_file| is initialized
313 // and can be used for writing. Returns false if the file could not be
314 // initialized. |g_log_file| will be nullptr in this case.
315 bool InitializeLogFileHandle() {
319 if (!g_log_file_name) {
320 // Nobody has called InitLogging to specify a debug log file, so here we
321 // initialize the log file name to a default.
322 g_log_file_name = new PathString(GetDefaultLogFile());
325 if ((g_logging_destination & LOG_TO_FILE) != 0) {
327 // The FILE_APPEND_DATA access mask ensures that the file is atomically
328 // appended to across accesses from multiple threads.
329 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
330 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
331 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
332 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
333 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
334 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
335 // We are intentionally not using FilePath or FileUtil here to reduce the
336 // dependencies of the logging implementation. For e.g. FilePath and
337 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
338 // some consumers of base logging like chrome_elf, etc.
339 // Please don't change the code below to use FilePath.
340 // try the current directory
341 wchar_t system_buffer[MAX_PATH];
342 system_buffer[0] = 0;
343 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
345 if (len == 0 || len > arraysize(system_buffer))
348 *g_log_file_name = system_buffer;
349 // Append a trailing backslash if needed.
350 if (g_log_file_name->back() != L'\\')
351 *g_log_file_name += L"\\";
352 *g_log_file_name += L"debug.log";
354 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
355 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
356 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
357 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
358 g_log_file = nullptr;
362 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
363 g_log_file = fopen(g_log_file_name->c_str(), "a");
364 if (g_log_file == nullptr)
367 #error Unsupported platform
374 void CloseFile(FileHandle log) {
377 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
380 #error Unsupported platform
384 void CloseLogFileUnlocked() {
388 CloseFile(g_log_file);
389 g_log_file = nullptr;
394 #if DCHECK_IS_CONFIGURABLE
395 // In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
396 // determined at run-time. We default it to INFO, to avoid it triggering
397 // crashes before the run-time has explicitly chosen the behaviour.
398 BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
399 #endif // DCHECK_IS_CONFIGURABLE
401 // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
402 // an object of the correct type on the LHS of the unused part of the ternary
404 std::ostream* g_swallow_stream;
406 LoggingSettings::LoggingSettings()
407 : logging_dest(LOG_DEFAULT),
409 lock_log(LOCK_LOG_FILE),
410 delete_old(APPEND_TO_OLD_LOG_FILE) {}
412 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
414 // Can log only to the system debug log.
415 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
417 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
418 // Don't bother initializing |g_vlog_info| unless we use one of the
420 if (command_line->HasSwitch(switches::kV) ||
421 command_line->HasSwitch(switches::kVModule)) {
422 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
423 // by another thread. Don't delete the old VLogInfo, just create a second
424 // one. We keep track of both to avoid memory leak warnings.
425 CHECK(!g_vlog_info_prev);
426 g_vlog_info_prev = g_vlog_info;
429 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
430 command_line->GetSwitchValueASCII(switches::kVModule),
434 g_logging_destination = settings.logging_dest;
436 // ignore file options unless logging to file is set.
437 if ((g_logging_destination & LOG_TO_FILE) == 0)
440 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
441 LoggingLock::Init(settings.lock_log, settings.log_file);
442 LoggingLock logging_lock;
445 // Calling InitLogging twice or after some log call has already opened the
446 // default log file will re-initialize to the new options.
447 CloseLogFileUnlocked();
449 if (!g_log_file_name)
450 g_log_file_name = new PathString();
451 *g_log_file_name = settings.log_file;
452 if (settings.delete_old == DELETE_OLD_LOG_FILE)
453 DeleteFilePath(*g_log_file_name);
455 return InitializeLogFileHandle();
458 void SetMinLogLevel(int level) {
459 g_min_log_level = std::min(LOG_FATAL, level);
462 int GetMinLogLevel() {
463 return g_min_log_level;
466 bool ShouldCreateLogMessage(int severity) {
467 if (severity < g_min_log_level)
470 // Return true here unless we know ~LogMessage won't do anything. Note that
471 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
472 // when g_logging_destination is LOG_NONE.
473 return g_logging_destination != LOG_NONE || log_message_handler ||
474 severity >= kAlwaysPrintErrorLevel;
477 int GetVlogVerbosity() {
478 return std::max(-1, LOG_INFO - GetMinLogLevel());
481 int GetVlogLevelHelper(const char* file, size_t N) {
483 // Note: |g_vlog_info| may change on a different thread during startup
484 // (but will always be valid or nullptr).
485 VlogInfo* vlog_info = g_vlog_info;
487 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
491 void SetLogItems(bool enable_process_id, bool enable_thread_id,
492 bool enable_timestamp, bool enable_tickcount) {
493 g_log_process_id = enable_process_id;
494 g_log_thread_id = enable_thread_id;
495 g_log_timestamp = enable_timestamp;
496 g_log_tickcount = enable_tickcount;
499 void SetShowErrorDialogs(bool enable_dialogs) {
500 show_error_dialogs = enable_dialogs;
503 ScopedLogAssertHandler::ScopedLogAssertHandler(
504 LogAssertHandlerFunction handler) {
505 log_assert_handler_stack.Get().push(std::move(handler));
508 ScopedLogAssertHandler::~ScopedLogAssertHandler() {
509 log_assert_handler_stack.Get().pop();
512 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
513 log_message_handler = handler;
516 LogMessageHandlerFunction GetLogMessageHandler() {
517 return log_message_handler;
520 // Explicit instantiations for commonly used comparisons.
521 template std::string* MakeCheckOpString<int, int>(
522 const int&, const int&, const char* names);
523 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
524 const unsigned long&, const unsigned long&, const char* names);
525 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
526 const unsigned long&, const unsigned int&, const char* names);
527 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
528 const unsigned int&, const unsigned long&, const char* names);
529 template std::string* MakeCheckOpString<std::string, std::string>(
530 const std::string&, const std::string&, const char* name);
532 void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
537 // Displays a message box to the user with the error message in it.
538 // Used for fatal messages, where we close the app simultaneously.
539 // This is for developers only; we don't use this in circumstances
540 // (like release builds) where users could see it, since users don't
541 // understand these messages anyway.
542 void DisplayDebugMessageInDialog(const std::string& str) {
546 if (!show_error_dialogs)
550 // We intentionally don't implement a dialog on other platforms.
551 // You can just look at stderr.
552 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
553 MB_OK | MB_ICONHAND | MB_TOPMOST);
554 #endif // defined(OS_WIN)
556 #endif // !defined(NDEBUG)
559 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
562 LogMessage::SaveLastError::~SaveLastError() {
563 ::SetLastError(last_error_);
565 #endif // defined(OS_WIN)
567 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
568 : severity_(severity), file_(file), line_(line) {
572 LogMessage::LogMessage(const char* file, int line, const char* condition)
573 : severity_(LOG_FATAL), file_(file), line_(line) {
575 stream_ << "Check failed: " << condition << ". ";
578 LogMessage::LogMessage(const char* file, int line, std::string* result)
579 : severity_(LOG_FATAL), file_(file), line_(line) {
581 stream_ << "Check failed: " << *result;
585 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
587 : severity_(severity), file_(file), line_(line) {
589 stream_ << "Check failed: " << *result;
593 LogMessage::~LogMessage() {
594 size_t stack_start = stream_.tellp();
595 #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
597 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
598 // Include a stack trace on a fatal, unless a debugger is attached.
599 base::debug::StackTrace trace;
600 stream_ << std::endl; // Newline to separate from log message.
601 trace.OutputToStream(&stream_);
604 stream_ << std::endl;
605 std::string str_newline(stream_.str());
607 // Give any log message handler first dibs on the message.
608 if (log_message_handler &&
609 log_message_handler(severity_, file_, line_,
610 message_start_, str_newline)) {
611 // The handler took care of it, no further processing.
615 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
617 OutputDebugStringA(str_newline.c_str());
618 #elif defined(OS_MACOSX)
619 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
620 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
621 // its successor OS_LOG. If there's something weird about stderr, assume
622 // that log messages are going nowhere and log via ASL/OS_LOG too.
623 // Messages logged via ASL/OS_LOG show up in Console.app.
625 // Programs started by launchd, as UI applications normally are, have had
626 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
627 // a pipe to launchd, which logged what it received (see log_redirect_fd in
628 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
630 // Another alternative would be to determine whether stderr is a pipe to
631 // launchd and avoid logging via ASL only in that case. See 10.7.5
632 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
633 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
634 // to the system log at all.
636 // Note that the ASL client by default discards messages whose levels are
637 // below ASL_LEVEL_NOTICE. It's possible to change that with
638 // asl_set_filter(), but this is pointless because syslogd normally applies
640 const bool log_to_system = []() {
641 struct stat stderr_stat;
642 if (fstat(fileno(stderr), &stderr_stat) == -1) {
645 if (!S_ISCHR(stderr_stat.st_mode)) {
649 struct stat dev_null_stat;
650 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
654 return !S_ISCHR(dev_null_stat.st_mode) ||
655 stderr_stat.st_rdev == dev_null_stat.st_rdev;
659 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
660 // CF-1153.18/CFUtilities.c __CFLogCString().
661 CFBundleRef main_bundle = CFBundleGetMainBundle();
662 CFStringRef main_bundle_id_cf =
663 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
664 std::string main_bundle_id =
665 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
668 // The facility is set to the main bundle ID if available. Otherwise,
669 // "com.apple.console" is used.
670 const class ASLClient {
672 explicit ASLClient(const std::string& facility)
673 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
674 ~ASLClient() { asl_close(client_); }
676 aslclient get() const { return client_; }
680 DISALLOW_COPY_AND_ASSIGN(ASLClient);
681 } asl_client(main_bundle_id.empty() ? main_bundle_id
682 : "com.apple.console");
684 const class ASLMessage {
686 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
687 ~ASLMessage() { asl_free(message_); }
689 aslmsg get() const { return message_; }
693 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
696 // By default, messages are only readable by the admin group. Explicitly
697 // make them readable by the user generating the messages.
698 char euid_string[12];
699 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
700 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
702 // Map Chrome log severities to ASL log levels.
703 const char* const asl_level_string = [](LogSeverity severity) {
704 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
705 // non-obvious two-step macro trick achieves what's needed.
706 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
707 #define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
708 #define ASL_LEVEL_STR_X(level) #level
711 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
713 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
715 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
717 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
719 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
720 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
723 #undef ASL_LEVEL_STR_X
725 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
727 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
729 asl_send(asl_client.get(), asl_message.get());
730 #else // !defined(USE_ASL)
733 explicit OSLog(const char* subsystem)
734 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
737 if (os_log_ != OS_LOG_DEFAULT) {
741 os_log_t get() const { return os_log_; }
745 DISALLOW_COPY_AND_ASSIGN(OSLog);
746 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
747 const os_log_type_t os_log_type = [](LogSeverity severity) {
750 return OS_LOG_TYPE_INFO;
752 return OS_LOG_TYPE_DEFAULT;
754 return OS_LOG_TYPE_ERROR;
756 return OS_LOG_TYPE_FAULT;
758 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
761 os_log_with_type(log.get(), os_log_type, "%{public}s",
762 str_newline.c_str());
763 #endif // defined(USE_ASL)
765 #elif defined(OS_ANDROID)
766 android_LogPriority priority =
767 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
770 priority = ANDROID_LOG_INFO;
773 priority = ANDROID_LOG_WARN;
776 priority = ANDROID_LOG_ERROR;
779 priority = ANDROID_LOG_FATAL;
782 __android_log_write(priority, "chromium", str_newline.c_str());
783 #elif defined(OS_TIZEN)
784 log_priority priority = DLOG_UNKNOWN;
787 priority = DLOG_INFO;
790 priority = DLOG_WARN;
793 priority = DLOG_ERROR;
796 priority = DLOG_FATAL;
799 dlog_print(priority, LOG_TAG, "%s", str_newline.c_str());
801 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
804 } else if (severity_ >= kAlwaysPrintErrorLevel) {
805 // When we're only outputting to a log file, above a certain log level, we
806 // should still output to stderr so that we can better detect and diagnose
807 // problems with unit tests, especially on the buildbots.
808 #if defined(OS_TIZEN)
809 log_priority priority = DLOG_UNKNOWN;
812 priority = DLOG_INFO;
815 priority = DLOG_WARN;
818 priority = DLOG_ERROR;
821 priority = DLOG_FATAL;
824 dlog_print(priority, LOG_TAG, "%s", str_newline.c_str());
826 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
832 if ((g_logging_destination & LOG_TO_FILE) != 0) {
833 // We can have multiple threads and/or processes, so try to prevent them
834 // from clobbering each other's writes.
835 // If the client app did not call InitLogging, and the lock has not
836 // been created do it now. We do this on demand, but if two threads try
837 // to do this at the same time, there will be a race condition to create
838 // the lock. This is why InitLogging should be called from the main
839 // thread at the beginning of execution.
840 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
841 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
842 LoggingLock logging_lock;
844 if (InitializeLogFileHandle()) {
847 WriteFile(g_log_file,
848 static_cast<const void*>(str_newline.c_str()),
849 static_cast<DWORD>(str_newline.length()),
852 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
853 ignore_result(fwrite(
854 str_newline.data(), str_newline.size(), 1, g_log_file));
857 #error Unsupported platform
862 if (severity_ == LOG_FATAL) {
863 // Write the log message to the global activity tracker, if running.
864 base::debug::GlobalActivityTracker* tracker =
865 base::debug::GlobalActivityTracker::Get();
867 tracker->RecordLogMessage(str_newline);
869 // Ensure the first characters of the string are on the stack so they
870 // are contained in minidumps for diagnostic purposes.
871 DEBUG_ALIAS_FOR_CSTR(str_stack, str_newline.c_str(), 1024);
873 if (log_assert_handler_stack.IsCreated() &&
874 !log_assert_handler_stack.Get().empty()) {
875 LogAssertHandlerFunction log_assert_handler =
876 log_assert_handler_stack.Get().top();
878 if (log_assert_handler) {
879 log_assert_handler.Run(
881 base::StringPiece(str_newline.c_str() + message_start_,
882 stack_start - message_start_),
883 base::StringPiece(str_newline.c_str() + stack_start));
886 // Don't use the string with the newline, get a fresh version to send to
887 // the debug message process. We also don't display assertions to the
888 // user in release mode. The enduser can't do anything with this
889 // information, and displaying message boxes when the application is
890 // hosed can cause additional problems.
892 if (!base::debug::BeingDebugged()) {
893 // Displaying a dialog is unnecessary when debugging and can complicate
895 DisplayDebugMessageInDialog(stream_.str());
898 // Crash the process to generate a dump.
899 base::debug::BreakDebugger();
904 // writes the common header info to the stream
905 void LogMessage::Init(const char* file, int line) {
906 base::StringPiece filename(file);
907 size_t last_slash_pos = filename.find_last_of("\\/");
908 if (last_slash_pos != base::StringPiece::npos)
909 filename.remove_prefix(last_slash_pos + 1);
911 // TODO(darin): It might be nice if the columns were fixed width.
914 #if !defined(OS_TIZEN)
915 if (g_log_process_id)
916 stream_ << CurrentProcessId() << ':';
918 stream_ << base::PlatformThread::CurrentId() << ':';
919 if (g_log_timestamp) {
921 SYSTEMTIME local_time;
922 GetLocalTime(&local_time);
923 stream_ << std::setfill('0')
924 << std::setw(2) << local_time.wMonth
925 << std::setw(2) << local_time.wDay
927 << std::setw(2) << local_time.wHour
928 << std::setw(2) << local_time.wMinute
929 << std::setw(2) << local_time.wSecond
932 << local_time.wMilliseconds
934 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
936 gettimeofday(&tv, nullptr);
937 time_t t = tv.tv_sec;
938 struct tm local_time;
939 localtime_r(&t, &local_time);
940 struct tm* tm_time = &local_time;
941 stream_ << std::setfill('0')
942 << std::setw(2) << 1 + tm_time->tm_mon
943 << std::setw(2) << tm_time->tm_mday
945 << std::setw(2) << tm_time->tm_hour
946 << std::setw(2) << tm_time->tm_min
947 << std::setw(2) << tm_time->tm_sec
949 << std::setw(6) << tv.tv_usec
952 #error Unsupported platform
956 stream_ << TickCount() << ':';
959 stream_ << log_severity_name(severity_);
961 stream_ << "VERBOSE" << -severity_;
963 stream_ << ":" << filename << "(" << line << ")] ";
965 message_start_ = stream_.str().length();
969 // This has already been defined in the header, but defining it again as DWORD
970 // ensures that the type used in the header is equivalent to DWORD. If not,
971 // the redefinition is a compile error.
972 typedef DWORD SystemErrorCode;
975 SystemErrorCode GetLastSystemErrorCode() {
977 return ::GetLastError();
978 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
983 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
985 const int kErrorMessageBufferSize = 256;
986 char msgbuf[kErrorMessageBufferSize];
987 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
988 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
989 arraysize(msgbuf), nullptr);
991 // Messages returned by system end with line breaks.
992 return base::CollapseWhitespaceASCII(msgbuf, true) +
993 base::StringPrintf(" (0x%lX)", error_code);
995 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
996 GetLastError(), error_code);
997 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
998 return base::safe_strerror(error_code) +
999 base::StringPrintf(" (%d)", error_code);
1000 #endif // defined(OS_WIN)
1005 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1007 LogSeverity severity,
1008 SystemErrorCode err)
1010 log_message_(file, line, severity) {
1013 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
1014 stream() << ": " << SystemErrorCodeToString(err_);
1015 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1016 // field) and use Alias in hopes that it makes it into crash dumps.
1017 DWORD last_error = err_;
1018 base::debug::Alias(&last_error);
1020 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1021 ErrnoLogMessage::ErrnoLogMessage(const char* file,
1023 LogSeverity severity,
1024 SystemErrorCode err)
1026 log_message_(file, line, severity) {
1029 ErrnoLogMessage::~ErrnoLogMessage() {
1030 stream() << ": " << SystemErrorCodeToString(err_);
1031 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1032 // field) and use Alias in hopes that it makes it into crash dumps.
1033 int last_error = err_;
1034 base::debug::Alias(&last_error);
1036 #endif // defined(OS_WIN)
1038 void CloseLogFile() {
1039 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
1040 LoggingLock logging_lock;
1042 CloseLogFileUnlocked();
1045 void RawLog(int level, const char* message) {
1046 if (level >= g_min_log_level && message) {
1047 size_t bytes_written = 0;
1048 const size_t message_len = strlen(message);
1050 while (bytes_written < message_len) {
1052 write(STDERR_FILENO, message + bytes_written,
1053 message_len - bytes_written));
1055 // Give up, nothing we can do now.
1058 bytes_written += rv;
1061 if (message_len > 0 && message[message_len - 1] != '\n') {
1063 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1065 // Give up, nothing we can do now.
1072 if (level == LOG_FATAL)
1073 base::debug::BreakDebugger();
1076 // This was defined at the beginning of this file.
1080 bool IsLoggingToFileEnabled() {
1081 return g_logging_destination & LOG_TO_FILE;
1084 std::wstring GetLogFileFullPath() {
1085 if (g_log_file_name)
1086 return *g_log_file_name;
1087 return std::wstring();
1091 BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
1092 LogMessage(file, line, LOG_ERROR).stream()
1093 << "NOTREACHED() hit.";
1096 } // namespace logging
1098 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
1099 return out << (wstr ? base::WideToUTF8(wstr) : std::string());