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/stl_util.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_split.h"
99 #include "base/strings/string_util.h"
100 #include "base/strings/stringprintf.h"
101 #include "base/strings/sys_string_conversions.h"
102 #include "base/strings/utf_string_conversions.h"
103 #include "base/synchronization/lock_impl.h"
104 #include "base/threading/platform_thread.h"
105 #include "base/vlog.h"
107 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
108 #include "base/posix/safe_strerror.h"
111 #if defined(OS_TIZEN)
112 #define LOG_TAG "CHROMIUM"
113 #include <dlog/dlog.h>
120 VlogInfo* g_vlog_info = nullptr;
121 VlogInfo* g_vlog_info_prev = nullptr;
123 const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
124 static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
125 "Incorrect number of log_severity_names");
127 const char* log_severity_name(int severity) {
128 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
129 return log_severity_names[severity];
133 int g_min_log_level = 0;
135 LoggingDestination g_logging_destination = LOG_DEFAULT;
137 // For LOG_ERROR and above, always print to stderr.
138 const int kAlwaysPrintErrorLevel = LOG_ERROR;
140 // Which log file to use? This is initialized by InitLogging or
141 // will be lazily initialized to the default value when it is
144 typedef std::wstring PathString;
145 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
146 typedef std::string PathString;
148 PathString* g_log_file_name = nullptr;
150 // This file is lazily opened and the handle may be nullptr
151 FileHandle g_log_file = nullptr;
153 // What should be prepended to each message?
154 bool g_log_process_id = false;
155 bool g_log_thread_id = false;
156 bool g_log_timestamp = true;
157 bool g_log_tickcount = false;
158 const char* g_log_prefix = nullptr;
160 // Should we pop up fatal debug messages in a dialog?
161 bool show_error_dialogs = false;
163 // An assert handler override specified by the client to be called instead of
164 // the debug message dialog and process termination. Assert handlers are stored
165 // in stack to allow overriding and restoring.
166 base::LazyInstance<base::stack<LogAssertHandlerFunction>>::Leaky
167 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
169 // A log message handler that gets notified of every log message we process.
170 LogMessageHandlerFunction log_message_handler = nullptr;
172 #if !defined(OS_TIZEN)
173 // Helper functions to wrap platform differences.
175 int32_t CurrentProcessId() {
177 return GetCurrentProcessId();
178 #elif defined(OS_FUCHSIA)
179 zx_info_handle_basic_t basic = {};
180 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
181 sizeof(basic), nullptr, nullptr);
183 #elif defined(OS_POSIX)
188 uint64_t TickCount() {
190 return GetTickCount();
191 #elif defined(OS_FUCHSIA)
192 return zx_clock_get(ZX_CLOCK_MONOTONIC) /
193 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
194 #elif defined(OS_MACOSX)
195 return mach_absolute_time();
196 #elif defined(OS_NACL)
197 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
198 // So we have to use clock() for now.
200 #elif defined(OS_POSIX)
202 clock_gettime(CLOCK_MONOTONIC, &ts);
204 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
205 static_cast<int64_t>(ts.tv_nsec) / 1000;
207 return absolute_micro;
212 void DeleteFilePath(const PathString& log_name) {
214 DeleteFile(log_name.c_str());
215 #elif defined(OS_NACL)
216 // Do nothing; unlink() isn't supported on NaCl.
217 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
218 unlink(log_name.c_str());
220 #error Unsupported platform
224 PathString GetDefaultLogFile() {
226 // On Windows we use the same path as the exe.
227 wchar_t module_name[MAX_PATH];
228 GetModuleFileName(nullptr, module_name, MAX_PATH);
230 PathString log_name = module_name;
231 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
232 if (last_backslash != PathString::npos)
233 log_name.erase(last_backslash + 1);
234 log_name += L"debug.log";
236 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
237 // On other platforms we just use the current directory.
238 return PathString("debug.log");
242 // We don't need locks on Windows for atomically appending to files. The OS
243 // provides this functionality.
244 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
245 // This class acts as a wrapper for locking the logging files.
246 // LoggingLock::Init() should be called from the main thread before any logging
247 // is done. Then whenever logging, be sure to have a local LoggingLock
248 // instance on the stack. This will ensure that the lock is unlocked upon
249 // exiting the frame.
250 // LoggingLocks can not be nested.
261 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
264 lock_log_file = lock_log;
266 if (lock_log_file != LOCK_LOG_FILE)
267 log_lock = new base::internal::LockImpl();
273 static void LockLogging() {
274 if (lock_log_file == LOCK_LOG_FILE) {
275 pthread_mutex_lock(&log_mutex);
282 static void UnlockLogging() {
283 if (lock_log_file == LOCK_LOG_FILE) {
284 pthread_mutex_unlock(&log_mutex);
290 // The lock is used if log file locking is false. It helps us avoid problems
291 // with multiple threads writing to the log file at the same time. Use
292 // LockImpl directly instead of using Lock, because Lock makes logging calls.
293 static base::internal::LockImpl* log_lock;
295 // When we don't use a lock, we are using a global mutex. We need to do this
296 // because LockFileEx is not thread safe.
297 static pthread_mutex_t log_mutex;
299 static bool initialized;
300 static LogLockingState lock_log_file;
304 bool LoggingLock::initialized = false;
306 base::internal::LockImpl* LoggingLock::log_lock = nullptr;
308 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
310 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
312 #endif // OS_POSIX || OS_FUCHSIA
314 // Called by logging functions to ensure that |g_log_file| is initialized
315 // and can be used for writing. Returns false if the file could not be
316 // initialized. |g_log_file| will be nullptr in this case.
317 bool InitializeLogFileHandle() {
321 if (!g_log_file_name) {
322 // Nobody has called InitLogging to specify a debug log file, so here we
323 // initialize the log file name to a default.
324 g_log_file_name = new PathString(GetDefaultLogFile());
327 if ((g_logging_destination & LOG_TO_FILE) != 0) {
329 // The FILE_APPEND_DATA access mask ensures that the file is atomically
330 // appended to across accesses from multiple threads.
331 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
332 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
333 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
334 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
335 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
336 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
337 // We are intentionally not using FilePath or FileUtil here to reduce the
338 // dependencies of the logging implementation. For e.g. FilePath and
339 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
340 // some consumers of base logging like chrome_elf, etc.
341 // Please don't change the code below to use FilePath.
342 // try the current directory
343 wchar_t system_buffer[MAX_PATH];
344 system_buffer[0] = 0;
346 ::GetCurrentDirectory(base::size(system_buffer), system_buffer);
347 if (len == 0 || len > base::size(system_buffer))
350 *g_log_file_name = system_buffer;
351 // Append a trailing backslash if needed.
352 if (g_log_file_name->back() != L'\\')
353 *g_log_file_name += L"\\";
354 *g_log_file_name += L"debug.log";
356 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
357 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
358 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
359 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
360 g_log_file = nullptr;
364 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
365 g_log_file = fopen(g_log_file_name->c_str(), "a");
366 if (g_log_file == nullptr)
369 #error Unsupported platform
376 void CloseFile(FileHandle log) {
379 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
382 #error Unsupported platform
386 void CloseLogFileUnlocked() {
390 CloseFile(g_log_file);
391 g_log_file = nullptr;
396 #if defined(DCHECK_IS_CONFIGURABLE)
397 // In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
398 // determined at run-time. We default it to INFO, to avoid it triggering
399 // crashes before the run-time has explicitly chosen the behaviour.
400 BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
401 #endif // defined(DCHECK_IS_CONFIGURABLE)
403 // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
404 // an object of the correct type on the LHS of the unused part of the ternary
406 std::ostream* g_swallow_stream;
408 LoggingSettings::LoggingSettings()
409 : logging_dest(LOG_DEFAULT),
411 lock_log(LOCK_LOG_FILE),
412 delete_old(APPEND_TO_OLD_LOG_FILE) {}
414 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
416 // Can log only to the system debug log.
417 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
419 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
420 // Don't bother initializing |g_vlog_info| unless we use one of the
422 if (command_line->HasSwitch(switches::kV) ||
423 command_line->HasSwitch(switches::kVModule)) {
424 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
425 // by another thread. Don't delete the old VLogInfo, just create a second
426 // one. We keep track of both to avoid memory leak warnings.
427 CHECK(!g_vlog_info_prev);
428 g_vlog_info_prev = g_vlog_info;
431 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
432 command_line->GetSwitchValueASCII(switches::kVModule),
436 g_logging_destination = settings.logging_dest;
438 // ignore file options unless logging to file is set.
439 if ((g_logging_destination & LOG_TO_FILE) == 0)
442 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
443 LoggingLock::Init(settings.lock_log, settings.log_file);
444 LoggingLock logging_lock;
447 // Calling InitLogging twice or after some log call has already opened the
448 // default log file will re-initialize to the new options.
449 CloseLogFileUnlocked();
451 if (!g_log_file_name)
452 g_log_file_name = new PathString();
453 *g_log_file_name = settings.log_file;
454 if (settings.delete_old == DELETE_OLD_LOG_FILE)
455 DeleteFilePath(*g_log_file_name);
457 return InitializeLogFileHandle();
460 void SetMinLogLevel(int level) {
461 g_min_log_level = std::min(LOG_FATAL, level);
464 int GetMinLogLevel() {
465 return g_min_log_level;
468 bool ShouldCreateLogMessage(int severity) {
469 if (severity < g_min_log_level)
472 // Return true here unless we know ~LogMessage won't do anything. Note that
473 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
474 // when g_logging_destination is LOG_NONE.
475 return g_logging_destination != LOG_NONE || log_message_handler ||
476 severity >= kAlwaysPrintErrorLevel;
479 int GetVlogVerbosity() {
480 return std::max(-1, LOG_INFO - GetMinLogLevel());
483 int GetVlogLevelHelper(const char* file, size_t N) {
485 // Note: |g_vlog_info| may change on a different thread during startup
486 // (but will always be valid or nullptr).
487 VlogInfo* vlog_info = g_vlog_info;
489 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
493 void SetLogItems(bool enable_process_id, bool enable_thread_id,
494 bool enable_timestamp, bool enable_tickcount) {
495 g_log_process_id = enable_process_id;
496 g_log_thread_id = enable_thread_id;
497 g_log_timestamp = enable_timestamp;
498 g_log_tickcount = enable_tickcount;
501 void SetLogPrefix(const char* prefix) {
503 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
504 g_log_prefix = prefix;
507 void SetShowErrorDialogs(bool enable_dialogs) {
508 show_error_dialogs = enable_dialogs;
511 ScopedLogAssertHandler::ScopedLogAssertHandler(
512 LogAssertHandlerFunction handler) {
513 log_assert_handler_stack.Get().push(std::move(handler));
516 ScopedLogAssertHandler::~ScopedLogAssertHandler() {
517 log_assert_handler_stack.Get().pop();
520 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
521 log_message_handler = handler;
524 LogMessageHandlerFunction GetLogMessageHandler() {
525 return log_message_handler;
528 // Explicit instantiations for commonly used comparisons.
529 template std::string* MakeCheckOpString<int, int>(
530 const int&, const int&, const char* names);
531 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
532 const unsigned long&, const unsigned long&, const char* names);
533 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
534 const unsigned long&, const unsigned int&, const char* names);
535 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
536 const unsigned int&, const unsigned long&, const char* names);
537 template std::string* MakeCheckOpString<std::string, std::string>(
538 const std::string&, const std::string&, const char* name);
540 void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
545 // Displays a message box to the user with the error message in it.
546 // Used for fatal messages, where we close the app simultaneously.
547 // This is for developers only; we don't use this in circumstances
548 // (like release builds) where users could see it, since users don't
549 // understand these messages anyway.
550 void DisplayDebugMessageInDialog(const std::string& str) {
554 if (!show_error_dialogs)
558 // We intentionally don't implement a dialog on other platforms.
559 // You can just look at stderr.
560 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
561 MB_OK | MB_ICONHAND | MB_TOPMOST);
562 #endif // defined(OS_WIN)
564 #endif // !defined(NDEBUG)
566 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
567 : severity_(severity), file_(file), line_(line) {
571 LogMessage::LogMessage(const char* file, int line, const char* condition)
572 : severity_(LOG_FATAL), file_(file), line_(line) {
574 stream_ << "Check failed: " << condition << ". ";
577 LogMessage::LogMessage(const char* file, int line, std::string* result)
578 : severity_(LOG_FATAL), file_(file), line_(line) {
580 stream_ << "Check failed: " << *result;
584 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
586 : severity_(severity), file_(file), line_(line) {
588 stream_ << "Check failed: " << *result;
592 LogMessage::~LogMessage() {
593 size_t stack_start = stream_.tellp();
594 #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
596 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
597 // Include a stack trace on a fatal, unless a debugger is attached.
598 base::debug::StackTrace trace;
599 stream_ << std::endl; // Newline to separate from log message.
600 trace.OutputToStream(&stream_);
603 stream_ << std::endl;
604 std::string str_newline(stream_.str());
606 // Give any log message handler first dibs on the message.
607 if (log_message_handler &&
608 log_message_handler(severity_, file_, line_,
609 message_start_, str_newline)) {
610 // The handler took care of it, no further processing.
614 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
616 OutputDebugStringA(str_newline.c_str());
617 #elif defined(OS_MACOSX)
618 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
619 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
620 // its successor OS_LOG. If there's something weird about stderr, assume
621 // that log messages are going nowhere and log via ASL/OS_LOG too.
622 // Messages logged via ASL/OS_LOG show up in Console.app.
624 // Programs started by launchd, as UI applications normally are, have had
625 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
626 // a pipe to launchd, which logged what it received (see log_redirect_fd in
627 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
629 // Another alternative would be to determine whether stderr is a pipe to
630 // launchd and avoid logging via ASL only in that case. See 10.7.5
631 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
632 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
633 // to the system log at all.
635 // Note that the ASL client by default discards messages whose levels are
636 // below ASL_LEVEL_NOTICE. It's possible to change that with
637 // asl_set_filter(), but this is pointless because syslogd normally applies
639 const bool log_to_system = []() {
640 struct stat stderr_stat;
641 if (fstat(fileno(stderr), &stderr_stat) == -1) {
644 if (!S_ISCHR(stderr_stat.st_mode)) {
648 struct stat dev_null_stat;
649 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
653 return !S_ISCHR(dev_null_stat.st_mode) ||
654 stderr_stat.st_rdev == dev_null_stat.st_rdev;
658 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
659 // CF-1153.18/CFUtilities.c __CFLogCString().
660 CFBundleRef main_bundle = CFBundleGetMainBundle();
661 CFStringRef main_bundle_id_cf =
662 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
663 std::string main_bundle_id =
664 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
667 // The facility is set to the main bundle ID if available. Otherwise,
668 // "com.apple.console" is used.
669 const class ASLClient {
671 explicit ASLClient(const std::string& facility)
672 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
673 ~ASLClient() { asl_close(client_); }
675 aslclient get() const { return client_; }
679 DISALLOW_COPY_AND_ASSIGN(ASLClient);
680 } asl_client(main_bundle_id.empty() ? main_bundle_id
681 : "com.apple.console");
683 const class ASLMessage {
685 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
686 ~ASLMessage() { asl_free(message_); }
688 aslmsg get() const { return message_; }
692 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
695 // By default, messages are only readable by the admin group. Explicitly
696 // make them readable by the user generating the messages.
697 char euid_string[12];
698 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
699 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
701 // Map Chrome log severities to ASL log levels.
702 const char* const asl_level_string = [](LogSeverity severity) {
703 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
704 // non-obvious two-step macro trick achieves what's needed.
705 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
706 #define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
707 #define ASL_LEVEL_STR_X(level) #level
710 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
712 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
714 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
716 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
718 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
719 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
722 #undef ASL_LEVEL_STR_X
724 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
726 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
728 asl_send(asl_client.get(), asl_message.get());
729 #else // !defined(USE_ASL)
732 explicit OSLog(const char* subsystem)
733 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
736 if (os_log_ != OS_LOG_DEFAULT) {
740 os_log_t get() const { return os_log_; }
744 DISALLOW_COPY_AND_ASSIGN(OSLog);
745 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
746 const os_log_type_t os_log_type = [](LogSeverity severity) {
749 return OS_LOG_TYPE_INFO;
751 return OS_LOG_TYPE_DEFAULT;
753 return OS_LOG_TYPE_ERROR;
755 return OS_LOG_TYPE_FAULT;
757 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
760 os_log_with_type(log.get(), os_log_type, "%{public}s",
761 str_newline.c_str());
762 #endif // defined(USE_ASL)
764 #elif defined(OS_ANDROID)
765 android_LogPriority priority =
766 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
769 priority = ANDROID_LOG_INFO;
772 priority = ANDROID_LOG_WARN;
775 priority = ANDROID_LOG_ERROR;
778 priority = ANDROID_LOG_FATAL;
782 // Split the output by new lines to prevent the Android system from
783 // truncating the log.
784 for (const auto& line : base::SplitString(
785 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL))
786 __android_log_write(priority, "chromium", line.c_str());
788 // The Android system may truncate the string if it's too long.
789 __android_log_write(priority, "chromium", str_newline.c_str());
791 #elif defined(OS_TIZEN)
792 log_priority priority = DLOG_UNKNOWN;
795 priority = DLOG_INFO;
798 priority = DLOG_WARN;
801 priority = DLOG_ERROR;
804 priority = DLOG_FATAL;
807 dlog_print(priority, LOG_TAG, "%s", str_newline.c_str());
809 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
812 } else if (severity_ >= kAlwaysPrintErrorLevel) {
813 // When we're only outputting to a log file, above a certain log level, we
814 // should still output to stderr so that we can better detect and diagnose
815 // problems with unit tests, especially on the buildbots.
816 #if defined(OS_TIZEN)
817 log_priority priority = DLOG_UNKNOWN;
820 priority = DLOG_INFO;
823 priority = DLOG_WARN;
826 priority = DLOG_ERROR;
829 priority = DLOG_FATAL;
832 dlog_print(priority, LOG_TAG, "%s", str_newline.c_str());
834 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
840 if ((g_logging_destination & LOG_TO_FILE) != 0) {
841 // We can have multiple threads and/or processes, so try to prevent them
842 // from clobbering each other's writes.
843 // If the client app did not call InitLogging, and the lock has not
844 // been created do it now. We do this on demand, but if two threads try
845 // to do this at the same time, there will be a race condition to create
846 // the lock. This is why InitLogging should be called from the main
847 // thread at the beginning of execution.
848 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
849 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
850 LoggingLock logging_lock;
852 if (InitializeLogFileHandle()) {
855 WriteFile(g_log_file,
856 static_cast<const void*>(str_newline.c_str()),
857 static_cast<DWORD>(str_newline.length()),
860 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
861 ignore_result(fwrite(
862 str_newline.data(), str_newline.size(), 1, g_log_file));
865 #error Unsupported platform
870 if (severity_ == LOG_FATAL) {
871 // Write the log message to the global activity tracker, if running.
872 base::debug::GlobalActivityTracker* tracker =
873 base::debug::GlobalActivityTracker::Get();
875 tracker->RecordLogMessage(str_newline);
877 // Ensure the first characters of the string are on the stack so they
878 // are contained in minidumps for diagnostic purposes. We place start
879 // and end marker values at either end, so we can scan captured stacks
880 // for the data easily.
882 uint32_t start_marker = 0xbedead01;
884 uint32_t end_marker = 0x5050dead;
886 base::strlcpy(str_stack.data, str_newline.data(),
887 base::size(str_stack.data));
888 base::debug::Alias(&str_stack);
890 if (log_assert_handler_stack.IsCreated() &&
891 !log_assert_handler_stack.Get().empty()) {
892 LogAssertHandlerFunction log_assert_handler =
893 log_assert_handler_stack.Get().top();
895 if (log_assert_handler) {
896 log_assert_handler.Run(
898 base::StringPiece(str_newline.c_str() + message_start_,
899 stack_start - message_start_),
900 base::StringPiece(str_newline.c_str() + stack_start));
903 // Don't use the string with the newline, get a fresh version to send to
904 // the debug message process. We also don't display assertions to the
905 // user in release mode. The enduser can't do anything with this
906 // information, and displaying message boxes when the application is
907 // hosed can cause additional problems.
909 if (!base::debug::BeingDebugged()) {
910 // Displaying a dialog is unnecessary when debugging and can complicate
912 DisplayDebugMessageInDialog(stream_.str());
915 // Crash the process to generate a dump.
916 #if defined(OFFICIAL_BUILD) && defined(NDEBUG)
919 base::debug::BreakDebugger();
925 // writes the common header info to the stream
926 void LogMessage::Init(const char* file, int line) {
927 base::StringPiece filename(file);
928 size_t last_slash_pos = filename.find_last_of("\\/");
929 if (last_slash_pos != base::StringPiece::npos)
930 filename.remove_prefix(last_slash_pos + 1);
932 // TODO(darin): It might be nice if the columns were fixed width.
935 #if !defined(OS_TIZEN)
937 stream_ << g_log_prefix << ':';
938 if (g_log_process_id)
939 stream_ << CurrentProcessId() << ':';
941 stream_ << base::PlatformThread::CurrentId() << ':';
942 if (g_log_timestamp) {
944 SYSTEMTIME local_time;
945 GetLocalTime(&local_time);
946 stream_ << std::setfill('0')
947 << std::setw(2) << local_time.wMonth
948 << std::setw(2) << local_time.wDay
950 << std::setw(2) << local_time.wHour
951 << std::setw(2) << local_time.wMinute
952 << std::setw(2) << local_time.wSecond
955 << local_time.wMilliseconds
957 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
959 gettimeofday(&tv, nullptr);
960 time_t t = tv.tv_sec;
961 struct tm local_time;
962 localtime_r(&t, &local_time);
963 struct tm* tm_time = &local_time;
964 stream_ << std::setfill('0')
965 << std::setw(2) << 1 + tm_time->tm_mon
966 << std::setw(2) << tm_time->tm_mday
968 << std::setw(2) << tm_time->tm_hour
969 << std::setw(2) << tm_time->tm_min
970 << std::setw(2) << tm_time->tm_sec
972 << std::setw(6) << tv.tv_usec
975 #error Unsupported platform
979 stream_ << TickCount() << ':';
982 stream_ << log_severity_name(severity_);
984 stream_ << "VERBOSE" << -severity_;
986 stream_ << ":" << filename << "(" << line << ")] ";
988 message_start_ = stream_.str().length();
992 // This has already been defined in the header, but defining it again as DWORD
993 // ensures that the type used in the header is equivalent to DWORD. If not,
994 // the redefinition is a compile error.
995 typedef DWORD SystemErrorCode;
998 SystemErrorCode GetLastSystemErrorCode() {
1000 return ::GetLastError();
1001 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1006 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
1008 const int kErrorMessageBufferSize = 256;
1009 char msgbuf[kErrorMessageBufferSize];
1010 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1011 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
1012 base::size(msgbuf), nullptr);
1014 // Messages returned by system end with line breaks.
1015 return base::CollapseWhitespaceASCII(msgbuf, true) +
1016 base::StringPrintf(" (0x%lX)", error_code);
1018 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
1019 GetLastError(), error_code);
1020 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1021 return base::safe_strerror(error_code) +
1022 base::StringPrintf(" (%d)", error_code);
1023 #endif // defined(OS_WIN)
1028 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1030 LogSeverity severity,
1031 SystemErrorCode err)
1033 log_message_(file, line, severity) {
1036 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
1037 stream() << ": " << SystemErrorCodeToString(err_);
1038 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1039 // field) and use Alias in hopes that it makes it into crash dumps.
1040 DWORD last_error = err_;
1041 base::debug::Alias(&last_error);
1043 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1044 ErrnoLogMessage::ErrnoLogMessage(const char* file,
1046 LogSeverity severity,
1047 SystemErrorCode err)
1049 log_message_(file, line, severity) {
1052 ErrnoLogMessage::~ErrnoLogMessage() {
1053 stream() << ": " << SystemErrorCodeToString(err_);
1054 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1055 // field) and use Alias in hopes that it makes it into crash dumps.
1056 int last_error = err_;
1057 base::debug::Alias(&last_error);
1059 #endif // defined(OS_WIN)
1061 void CloseLogFile() {
1062 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
1063 LoggingLock logging_lock;
1065 CloseLogFileUnlocked();
1068 void RawLog(int level, const char* message) {
1069 if (level >= g_min_log_level && message) {
1070 size_t bytes_written = 0;
1071 const size_t message_len = strlen(message);
1073 while (bytes_written < message_len) {
1075 write(STDERR_FILENO, message + bytes_written,
1076 message_len - bytes_written));
1078 // Give up, nothing we can do now.
1081 bytes_written += rv;
1084 if (message_len > 0 && message[message_len - 1] != '\n') {
1086 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1088 // Give up, nothing we can do now.
1095 if (level == LOG_FATAL)
1096 base::debug::BreakDebugger();
1099 // This was defined at the beginning of this file.
1103 bool IsLoggingToFileEnabled() {
1104 return g_logging_destination & LOG_TO_FILE;
1107 std::wstring GetLogFileFullPath() {
1108 if (g_log_file_name)
1109 return *g_log_file_name;
1110 return std::wstring();
1114 BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
1115 LogMessage(file, line, LOG_ERROR).stream()
1116 << "NOTREACHED() hit.";
1119 } // namespace logging
1121 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
1122 return out << (wstr ? base::WideToUTF8(wstr) : std::string());