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"
7 // logging.h is a widely included header and its size has significant impact on
8 // build time. Try not to raise this limit unless absolutely necessary. See
9 // https://chromium.googlesource.com/chromium/src/+/HEAD/docs/wmax_tokens.md
11 #pragma clang max_tokens_here 350000
15 #error "logging.h should not include check.h"
21 #include "base/pending_task.h"
22 #include "base/stl_util.h"
23 #include "base/task/common/task_annotator.h"
24 #include "base/trace_event/base_tracing.h"
25 #include "build/build_config.h"
30 typedef HANDLE FileHandle;
31 typedef HANDLE MutexHandle;
32 // Windows warns on using write(). It prefers _write().
33 #define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
34 // Windows doesn't define STDERR_FILENO. Define it here.
35 #define STDERR_FILENO 2
37 #elif defined(OS_MACOSX)
38 // In MacOS 10.12 and iOS 10.0 and later ASL (Apple System Log) was deprecated
39 // in favor of OS_LOG (Unified Logging).
40 #include <AvailabilityMacros.h>
42 #if !defined(__IPHONE_10_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_10_0
45 #else // !defined(OS_IOS)
46 #if !defined(MAC_OS_X_VERSION_10_12) || \
47 MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_12
50 #endif // defined(OS_IOS)
58 #include <CoreFoundation/CoreFoundation.h>
59 #include <mach/mach.h>
60 #include <mach/mach_time.h>
61 #include <mach-o/dyld.h>
63 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
65 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
70 #if defined(OS_FUCHSIA)
71 #include <lib/syslog/global.h>
72 #include <lib/syslog/logger.h>
73 #include <zircon/process.h>
74 #include <zircon/syscalls.h>
77 #if defined(OS_ANDROID)
78 #include <android/log.h>
81 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
89 #include "base/process/process_handle.h"
90 #define MAX_PATH PATH_MAX
91 typedef FILE* FileHandle;
92 typedef pthread_mutex_t* MutexHandle;
103 #include "base/base_switches.h"
104 #include "base/callback.h"
105 #include "base/command_line.h"
106 #include "base/containers/stack.h"
107 #include "base/debug/activity_tracker.h"
108 #include "base/debug/alias.h"
109 #include "base/debug/debugger.h"
110 #include "base/debug/stack_trace.h"
111 #include "base/debug/task_trace.h"
112 #include "base/no_destructor.h"
113 #include "base/path_service.h"
114 #include "base/posix/eintr_wrapper.h"
115 #include "base/strings/string_piece.h"
116 #include "base/strings/string_split.h"
117 #include "base/strings/string_util.h"
118 #include "base/strings/stringprintf.h"
119 #include "base/strings/sys_string_conversions.h"
120 #include "base/strings/utf_string_conversions.h"
121 #include "base/synchronization/lock_impl.h"
122 #include "base/threading/platform_thread.h"
123 #include "base/vlog.h"
126 #include "base/win/win_util.h"
129 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
130 #include "base/posix/safe_strerror.h"
133 #if defined(OS_CHROMEOS)
134 #include "base/files/scoped_file.h"
137 #if defined(OS_TIZEN)
138 #define LOG_TAG "CHROMIUM"
139 #include <dlog/dlog.h>
146 VlogInfo* g_vlog_info = nullptr;
147 VlogInfo* g_vlog_info_prev = nullptr;
149 const char* const log_severity_names[] = {"INFO", "WARNING", "ERROR", "FATAL"};
150 static_assert(LOG_NUM_SEVERITIES == base::size(log_severity_names),
151 "Incorrect number of log_severity_names");
153 const char* log_severity_name(int severity) {
154 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
155 return log_severity_names[severity];
159 int g_min_log_level = 0;
161 // Specifies the process' logging sink(s), represented as a combination of
162 // LoggingDestination values joined by bitwise OR.
163 int g_logging_destination = LOG_DEFAULT;
165 // For LOG_ERROR and above, always print to stderr.
166 const int kAlwaysPrintErrorLevel = LOG_ERROR;
168 // Which log file to use? This is initialized by InitLogging or
169 // will be lazily initialized to the default value when it is
171 using PathString = base::FilePath::StringType;
172 PathString* g_log_file_name = nullptr;
174 // This file is lazily opened and the handle may be nullptr
175 FileHandle g_log_file = nullptr;
177 // What should be prepended to each message?
178 bool g_log_process_id = false;
179 bool g_log_thread_id = false;
180 bool g_log_timestamp = true;
181 bool g_log_tickcount = false;
182 const char* g_log_prefix = nullptr;
184 // Should we pop up fatal debug messages in a dialog?
185 bool show_error_dialogs = false;
187 // An assert handler override specified by the client to be called instead of
188 // the debug message dialog and process termination. Assert handlers are stored
189 // in stack to allow overriding and restoring.
190 base::stack<LogAssertHandlerFunction>& GetLogAssertHandlerStack() {
191 static base::NoDestructor<base::stack<LogAssertHandlerFunction>> instance;
195 // A log message handler that gets notified of every log message we process.
196 LogMessageHandlerFunction log_message_handler = nullptr;
198 #if !defined(OS_TIZEN)
199 // Helper functions to wrap platform differences.
201 int32_t CurrentProcessId() {
203 return GetCurrentProcessId();
204 #elif defined(OS_FUCHSIA)
205 zx_info_handle_basic_t basic = {};
206 zx_object_get_info(zx_process_self(), ZX_INFO_HANDLE_BASIC, &basic,
207 sizeof(basic), nullptr, nullptr);
209 #elif defined(OS_POSIX)
214 uint64_t TickCount() {
216 return GetTickCount();
217 #elif defined(OS_FUCHSIA)
218 return zx_clock_get_monotonic() /
219 static_cast<zx_time_t>(base::Time::kNanosecondsPerMicrosecond);
220 #elif defined(OS_MACOSX)
221 return mach_absolute_time();
222 #elif defined(OS_NACL)
223 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
224 // So we have to use clock() for now.
226 #elif defined(OS_POSIX)
228 clock_gettime(CLOCK_MONOTONIC, &ts);
230 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
231 static_cast<int64_t>(ts.tv_nsec) / 1000;
233 return absolute_micro;
238 void DeleteFilePath(const PathString& log_name) {
240 DeleteFile(log_name.c_str());
241 #elif defined(OS_NACL)
242 // Do nothing; unlink() isn't supported on NaCl.
243 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
244 unlink(log_name.c_str());
246 #error Unsupported platform
250 PathString GetDefaultLogFile() {
252 // On Windows we use the same path as the exe.
253 wchar_t module_name[MAX_PATH];
254 GetModuleFileName(nullptr, module_name, MAX_PATH);
256 PathString log_name = module_name;
257 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
258 if (last_backslash != PathString::npos)
259 log_name.erase(last_backslash + 1);
260 log_name += FILE_PATH_LITERAL("debug.log");
262 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
263 // On other platforms we just use the current directory.
264 return PathString("debug.log");
268 // We don't need locks on Windows for atomically appending to files. The OS
269 // provides this functionality.
270 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
271 // This class acts as a wrapper for locking the logging files.
272 // LoggingLock::Init() should be called from the main thread before any logging
273 // is done. Then whenever logging, be sure to have a local LoggingLock
274 // instance on the stack. This will ensure that the lock is unlocked upon
275 // exiting the frame.
276 // LoggingLocks can not be nested.
287 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
290 lock_log_file = lock_log;
292 if (lock_log_file != LOCK_LOG_FILE)
293 log_lock = new base::internal::LockImpl();
299 static void LockLogging() {
300 if (lock_log_file == LOCK_LOG_FILE) {
301 pthread_mutex_lock(&log_mutex);
308 static void UnlockLogging() {
309 if (lock_log_file == LOCK_LOG_FILE) {
310 pthread_mutex_unlock(&log_mutex);
316 // The lock is used if log file locking is false. It helps us avoid problems
317 // with multiple threads writing to the log file at the same time. Use
318 // LockImpl directly instead of using Lock, because Lock makes logging calls.
319 static base::internal::LockImpl* log_lock;
321 // When we don't use a lock, we are using a global mutex. We need to do this
322 // because LockFileEx is not thread safe.
323 static pthread_mutex_t log_mutex;
325 static bool initialized;
326 static LogLockingState lock_log_file;
330 bool LoggingLock::initialized = false;
332 base::internal::LockImpl* LoggingLock::log_lock = nullptr;
334 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
336 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
338 #endif // OS_POSIX || OS_FUCHSIA
340 // Called by logging functions to ensure that |g_log_file| is initialized
341 // and can be used for writing. Returns false if the file could not be
342 // initialized. |g_log_file| will be nullptr in this case.
343 bool InitializeLogFileHandle() {
347 if (!g_log_file_name) {
348 // Nobody has called InitLogging to specify a debug log file, so here we
349 // initialize the log file name to a default.
350 g_log_file_name = new PathString(GetDefaultLogFile());
353 if ((g_logging_destination & LOG_TO_FILE) == 0)
357 // The FILE_APPEND_DATA access mask ensures that the file is atomically
358 // appended to across accesses from multiple threads.
359 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
360 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
361 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
362 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
363 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
364 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
365 // We are intentionally not using FilePath or FileUtil here to reduce the
366 // dependencies of the logging implementation. For e.g. FilePath and
367 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
368 // some consumers of base logging like chrome_elf, etc.
369 // Please don't change the code below to use FilePath.
370 // try the current directory
371 wchar_t system_buffer[MAX_PATH];
372 system_buffer[0] = 0;
373 DWORD len = ::GetCurrentDirectory(base::size(system_buffer), system_buffer);
374 if (len == 0 || len > base::size(system_buffer))
377 *g_log_file_name = system_buffer;
378 // Append a trailing backslash if needed.
379 if (g_log_file_name->back() != L'\\')
380 *g_log_file_name += FILE_PATH_LITERAL("\\");
381 *g_log_file_name += FILE_PATH_LITERAL("debug.log");
383 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
384 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
385 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
386 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
387 g_log_file = nullptr;
391 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
392 g_log_file = fopen(g_log_file_name->c_str(), "a");
393 if (g_log_file == nullptr)
396 #error Unsupported platform
402 void CloseFile(FileHandle log) {
405 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
408 #error Unsupported platform
412 void CloseLogFileUnlocked() {
416 CloseFile(g_log_file);
417 g_log_file = nullptr;
419 // If we initialized logging via an externally-provided file descriptor, we
420 // won't have a log path set and shouldn't try to reopen the log file.
421 if (!g_log_file_name)
422 g_logging_destination &= ~LOG_TO_FILE;
427 #if defined(DCHECK_IS_CONFIGURABLE)
428 // In DCHECK-enabled Chrome builds, allow the meaning of LOG_DCHECK to be
429 // determined at run-time. We default it to INFO, to avoid it triggering
430 // crashes before the run-time has explicitly chosen the behaviour.
431 BASE_EXPORT logging::LogSeverity LOG_DCHECK = LOG_INFO;
432 #endif // defined(DCHECK_IS_CONFIGURABLE)
434 // This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
435 // an object of the correct type on the LHS of the unused part of the ternary
437 std::ostream* g_swallow_stream;
439 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
441 // Can log only to the system debug log and stderr.
442 CHECK_EQ(settings.logging_dest & ~(LOG_TO_SYSTEM_DEBUG_LOG | LOG_TO_STDERR),
446 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
447 // Don't bother initializing |g_vlog_info| unless we use one of the
449 if (command_line->HasSwitch(switches::kV) ||
450 command_line->HasSwitch(switches::kVModule)) {
451 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
452 // by another thread. Don't delete the old VLogInfo, just create a second
453 // one. We keep track of both to avoid memory leak warnings.
454 CHECK(!g_vlog_info_prev);
455 g_vlog_info_prev = g_vlog_info;
458 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
459 command_line->GetSwitchValueASCII(switches::kVModule),
463 g_logging_destination = settings.logging_dest;
465 #if defined(OS_FUCHSIA)
466 if (g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) {
467 fx_logger_config_t config;
468 config.min_severity = FX_LOG_INFO;
469 config.console_fd = -1;
470 config.log_service_channel = ZX_HANDLE_INVALID;
471 std::string log_tag = command_line->GetProgram().BaseName().AsUTF8Unsafe();
472 const char* log_tag_data = log_tag.data();
473 config.tags = &log_tag_data;
475 fx_log_reconfigure(&config);
479 // ignore file options unless logging to file is set.
480 if ((g_logging_destination & LOG_TO_FILE) == 0)
483 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
484 LoggingLock::Init(settings.lock_log, settings.log_file_path);
485 LoggingLock logging_lock;
488 // Calling InitLogging twice or after some log call has already opened the
489 // default log file will re-initialize to the new options.
490 CloseLogFileUnlocked();
492 #if defined(OS_CHROMEOS)
493 if (settings.log_file) {
494 DCHECK(!settings.log_file_path);
495 g_log_file = settings.log_file;
500 if (!g_log_file_name)
501 g_log_file_name = new PathString();
502 *g_log_file_name = settings.log_file_path;
503 if (settings.delete_old == DELETE_OLD_LOG_FILE)
504 DeleteFilePath(*g_log_file_name);
506 return InitializeLogFileHandle();
509 void SetMinLogLevel(int level) {
510 g_min_log_level = std::min(LOG_FATAL, level);
513 int GetMinLogLevel() {
514 return g_min_log_level;
517 bool ShouldCreateLogMessage(int severity) {
518 if (severity < g_min_log_level)
521 // Return true here unless we know ~LogMessage won't do anything.
522 return g_logging_destination != LOG_NONE || log_message_handler ||
523 severity >= kAlwaysPrintErrorLevel;
526 // Returns true when LOG_TO_STDERR flag is set, or |severity| is high.
527 // If |severity| is high then true will be returned when no log destinations are
528 // set, or only LOG_TO_FILE is set, since that is useful for local development
530 bool ShouldLogToStderr(int severity) {
531 if (g_logging_destination & LOG_TO_STDERR)
533 if (severity >= kAlwaysPrintErrorLevel)
534 return (g_logging_destination & ~LOG_TO_FILE) == LOG_NONE;
538 int GetVlogVerbosity() {
539 return std::max(-1, LOG_INFO - GetMinLogLevel());
542 int GetVlogLevelHelper(const char* file, size_t N) {
544 // Note: |g_vlog_info| may change on a different thread during startup
545 // (but will always be valid or nullptr).
546 VlogInfo* vlog_info = g_vlog_info;
548 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
552 void SetLogItems(bool enable_process_id, bool enable_thread_id,
553 bool enable_timestamp, bool enable_tickcount) {
554 g_log_process_id = enable_process_id;
555 g_log_thread_id = enable_thread_id;
556 g_log_timestamp = enable_timestamp;
557 g_log_tickcount = enable_tickcount;
560 void SetLogPrefix(const char* prefix) {
562 base::ContainsOnlyChars(prefix, "abcdefghijklmnopqrstuvwxyz"));
563 g_log_prefix = prefix;
566 void SetShowErrorDialogs(bool enable_dialogs) {
567 show_error_dialogs = enable_dialogs;
570 ScopedLogAssertHandler::ScopedLogAssertHandler(
571 LogAssertHandlerFunction handler) {
572 GetLogAssertHandlerStack().push(std::move(handler));
575 ScopedLogAssertHandler::~ScopedLogAssertHandler() {
576 GetLogAssertHandlerStack().pop();
579 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
580 log_message_handler = handler;
583 LogMessageHandlerFunction GetLogMessageHandler() {
584 return log_message_handler;
588 // Displays a message box to the user with the error message in it.
589 // Used for fatal messages, where we close the app simultaneously.
590 // This is for developers only; we don't use this in circumstances
591 // (like release builds) where users could see it, since users don't
592 // understand these messages anyway.
593 void DisplayDebugMessageInDialog(const std::string& str) {
597 if (!show_error_dialogs)
601 // We intentionally don't implement a dialog on other platforms.
602 // You can just look at stderr.
603 if (base::win::IsUser32AndGdi32Available()) {
604 MessageBoxW(nullptr, base::as_wcstr(base::UTF8ToUTF16(str)), L"Fatal error",
605 MB_OK | MB_ICONHAND | MB_TOPMOST);
607 OutputDebugStringW(base::as_wcstr(base::UTF8ToUTF16(str)));
609 #endif // defined(OS_WIN)
611 #endif // !defined(NDEBUG)
613 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
614 : severity_(severity), file_(file), line_(line) {
618 LogMessage::LogMessage(const char* file, int line, const char* condition)
619 : severity_(LOG_FATAL), file_(file), line_(line) {
621 stream_ << "Check failed: " << condition << ". ";
624 LogMessage::~LogMessage() {
625 size_t stack_start = stream_.tellp();
626 #if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__) && \
628 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
629 // Include a stack trace on a fatal, unless a debugger is attached.
630 base::debug::StackTrace stack_trace;
631 stream_ << std::endl; // Newline to separate from log message.
632 stack_trace.OutputToStream(&stream_);
633 base::debug::TaskTrace task_trace;
634 if (!task_trace.empty())
635 task_trace.OutputToStream(&stream_);
637 // Include the IPC context, if any.
638 // TODO(chrisha): Integrate with symbolization once those tools exist!
639 const auto* task = base::TaskAnnotator::CurrentTaskForThread();
640 if (task && task->ipc_hash) {
641 stream_ << "IPC message handler context: "
642 << base::StringPrintf("0x%08X", task->ipc_hash) << std::endl;
646 stream_ << std::endl;
647 std::string str_newline(stream_.str());
649 file_, base::StringPiece(str_newline).substr(message_start_), line_);
651 // Give any log message handler first dibs on the message.
652 if (log_message_handler &&
653 log_message_handler(severity_, file_, line_,
654 message_start_, str_newline)) {
655 // The handler took care of it, no further processing.
659 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
661 OutputDebugStringA(str_newline.c_str());
662 #elif defined(OS_MACOSX)
663 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
664 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log) or
665 // its successor OS_LOG. If there's something weird about stderr, assume
666 // that log messages are going nowhere and log via ASL/OS_LOG too.
667 // Messages logged via ASL/OS_LOG show up in Console.app.
669 // Programs started by launchd, as UI applications normally are, have had
670 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
671 // a pipe to launchd, which logged what it received (see log_redirect_fd in
672 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
674 // Another alternative would be to determine whether stderr is a pipe to
675 // launchd and avoid logging via ASL only in that case. See 10.7.5
676 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
677 // both stderr and ASL/OS_LOG even in tests, where it's undesirable to log
678 // to the system log at all.
680 // Note that the ASL client by default discards messages whose levels are
681 // below ASL_LEVEL_NOTICE. It's possible to change that with
682 // asl_set_filter(), but this is pointless because syslogd normally applies
684 const bool log_to_system = []() {
685 struct stat stderr_stat;
686 if (fstat(fileno(stderr), &stderr_stat) == -1) {
689 if (!S_ISCHR(stderr_stat.st_mode)) {
693 struct stat dev_null_stat;
694 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
698 return !S_ISCHR(dev_null_stat.st_mode) ||
699 stderr_stat.st_rdev == dev_null_stat.st_rdev;
703 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
704 // CF-1153.18/CFUtilities.c __CFLogCString().
705 CFBundleRef main_bundle = CFBundleGetMainBundle();
706 CFStringRef main_bundle_id_cf =
707 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
708 std::string main_bundle_id =
709 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
712 // The facility is set to the main bundle ID if available. Otherwise,
713 // "com.apple.console" is used.
714 const class ASLClient {
716 explicit ASLClient(const std::string& facility)
717 : client_(asl_open(nullptr, facility.c_str(), ASL_OPT_NO_DELAY)) {}
718 ~ASLClient() { asl_close(client_); }
720 aslclient get() const { return client_; }
724 DISALLOW_COPY_AND_ASSIGN(ASLClient);
725 } asl_client(main_bundle_id.empty() ? main_bundle_id
726 : "com.apple.console");
728 const class ASLMessage {
730 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
731 ~ASLMessage() { asl_free(message_); }
733 aslmsg get() const { return message_; }
737 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
740 // By default, messages are only readable by the admin group. Explicitly
741 // make them readable by the user generating the messages.
742 char euid_string[12];
743 snprintf(euid_string, base::size(euid_string), "%d", geteuid());
744 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
746 // Map Chrome log severities to ASL log levels.
747 const char* const asl_level_string = [](LogSeverity severity) {
748 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
749 // non-obvious two-step macro trick achieves what's needed.
750 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
751 #define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
752 #define ASL_LEVEL_STR_X(level) #level
755 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
757 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
759 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
761 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
763 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
764 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
767 #undef ASL_LEVEL_STR_X
769 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
771 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
773 asl_send(asl_client.get(), asl_message.get());
774 #else // !defined(USE_ASL)
777 explicit OSLog(const char* subsystem)
778 : os_log_(subsystem ? os_log_create(subsystem, "chromium_logging")
781 if (os_log_ != OS_LOG_DEFAULT) {
785 os_log_t get() const { return os_log_; }
789 DISALLOW_COPY_AND_ASSIGN(OSLog);
790 } log(main_bundle_id.empty() ? nullptr : main_bundle_id.c_str());
791 const os_log_type_t os_log_type = [](LogSeverity severity) {
794 return OS_LOG_TYPE_INFO;
796 return OS_LOG_TYPE_DEFAULT;
798 return OS_LOG_TYPE_ERROR;
800 return OS_LOG_TYPE_FAULT;
802 return severity < 0 ? OS_LOG_TYPE_DEBUG : OS_LOG_TYPE_DEFAULT;
805 os_log_with_type(log.get(), os_log_type, "%{public}s",
806 str_newline.c_str());
807 #endif // defined(USE_ASL)
809 #elif defined(OS_ANDROID)
810 android_LogPriority priority =
811 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
814 priority = ANDROID_LOG_INFO;
817 priority = ANDROID_LOG_WARN;
820 priority = ANDROID_LOG_ERROR;
823 priority = ANDROID_LOG_FATAL;
826 const char kAndroidLogTag[] = "chromium";
828 // Split the output by new lines to prevent the Android system from
829 // truncating the log.
830 std::vector<std::string> lines = base::SplitString(
831 str_newline, "\n", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
832 // str_newline has an extra newline appended to it (at the top of this
833 // function), so skip the last split element to avoid needlessly
834 // logging an empty string.
836 for (const auto& line : lines)
837 __android_log_write(priority, kAndroidLogTag, line.c_str());
839 // The Android system may truncate the string if it's too long.
840 __android_log_write(priority, kAndroidLogTag, str_newline.c_str());
842 #elif defined(OS_TIZEN)
843 log_priority priority = DLOG_UNKNOWN;
846 priority = DLOG_INFO;
849 priority = DLOG_WARN;
852 priority = DLOG_ERROR;
855 priority = DLOG_FATAL;
858 dlog_print(priority, LOG_TAG, "%s", str_newline.c_str());
859 #elif defined(OS_FUCHSIA)
860 fx_log_severity_t severity = FX_LOG_INFO;
863 severity = FX_LOG_INFO;
866 severity = FX_LOG_WARNING;
869 severity = FX_LOG_ERROR;
872 // Don't use FX_LOG_FATAL, otherwise fx_logger_log() will abort().
873 severity = FX_LOG_ERROR;
877 fx_logger_t* logger = fx_log_get_logger();
879 // Temporarily remove the trailing newline from |str_newline|'s C-string
880 // representation, since fx_logger will add a newline of its own.
881 str_newline.pop_back();
882 std::string message =
883 base::StringPrintf("%s(%d) %s", file_basename_, line_,
884 str_newline.c_str() + message_start_);
885 fx_logger_log(logger, severity, nullptr, message.data());
886 str_newline.push_back('\n');
891 if (ShouldLogToStderr(severity_)) {
892 #if defined(OS_TIZEN)
893 log_priority priority = DLOG_UNKNOWN;
896 priority = DLOG_INFO;
899 priority = DLOG_WARN;
902 priority = DLOG_ERROR;
905 priority = DLOG_FATAL;
908 dlog_print(priority, LOG_TAG, "%s", str_newline.c_str());
910 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
915 if ((g_logging_destination & LOG_TO_FILE) != 0) {
916 // We can have multiple threads and/or processes, so try to prevent them
917 // from clobbering each other's writes.
918 // If the client app did not call InitLogging, and the lock has not
919 // been created do it now. We do this on demand, but if two threads try
920 // to do this at the same time, there will be a race condition to create
921 // the lock. This is why InitLogging should be called from the main
922 // thread at the beginning of execution.
923 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
924 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
925 LoggingLock logging_lock;
927 if (InitializeLogFileHandle()) {
930 WriteFile(g_log_file,
931 static_cast<const void*>(str_newline.c_str()),
932 static_cast<DWORD>(str_newline.length()),
935 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
936 ignore_result(fwrite(
937 str_newline.data(), str_newline.size(), 1, g_log_file));
940 #error Unsupported platform
945 if (severity_ == LOG_FATAL) {
946 // Write the log message to the global activity tracker, if running.
947 base::debug::GlobalActivityTracker* tracker =
948 base::debug::GlobalActivityTracker::Get();
950 tracker->RecordLogMessage(str_newline);
952 // Ensure the first characters of the string are on the stack so they
953 // are contained in minidumps for diagnostic purposes. We place start
954 // and end marker values at either end, so we can scan captured stacks
955 // for the data easily.
957 uint32_t start_marker = 0xbedead01;
959 uint32_t end_marker = 0x5050dead;
961 base::strlcpy(str_stack.data, str_newline.data(),
962 base::size(str_stack.data));
963 base::debug::Alias(&str_stack);
965 if (!GetLogAssertHandlerStack().empty()) {
966 LogAssertHandlerFunction log_assert_handler =
967 GetLogAssertHandlerStack().top();
969 if (log_assert_handler) {
970 log_assert_handler.Run(
972 base::StringPiece(str_newline.c_str() + message_start_,
973 stack_start - message_start_),
974 base::StringPiece(str_newline.c_str() + stack_start));
977 // Don't use the string with the newline, get a fresh version to send to
978 // the debug message process. We also don't display assertions to the
979 // user in release mode. The enduser can't do anything with this
980 // information, and displaying message boxes when the application is
981 // hosed can cause additional problems.
983 if (!base::debug::BeingDebugged()) {
984 // Displaying a dialog is unnecessary when debugging and can complicate
986 DisplayDebugMessageInDialog(stream_.str());
989 // Crash the process to generate a dump.
990 #if defined(OFFICIAL_BUILD) && defined(NDEBUG)
993 base::debug::BreakDebugger();
999 // writes the common header info to the stream
1000 void LogMessage::Init(const char* file, int line) {
1001 base::StringPiece filename(file);
1002 size_t last_slash_pos = filename.find_last_of("\\/");
1003 if (last_slash_pos != base::StringPiece::npos)
1004 filename.remove_prefix(last_slash_pos + 1);
1006 // Stores the base name as the null-terminated suffix substring of |filename|.
1007 file_basename_ = filename.data();
1009 // TODO(darin): It might be nice if the columns were fixed width.
1012 #if !defined(OS_TIZEN)
1014 stream_ << g_log_prefix << ':';
1015 if (g_log_process_id)
1016 stream_ << base::GetUniqueIdForProcess() << ':';
1017 if (g_log_thread_id)
1018 stream_ << base::PlatformThread::CurrentId() << ':';
1019 if (g_log_timestamp) {
1021 SYSTEMTIME local_time;
1022 GetLocalTime(&local_time);
1023 stream_ << std::setfill('0')
1024 << std::setw(2) << local_time.wMonth
1025 << std::setw(2) << local_time.wDay
1027 << std::setw(2) << local_time.wHour
1028 << std::setw(2) << local_time.wMinute
1029 << std::setw(2) << local_time.wSecond
1032 << local_time.wMilliseconds
1034 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1036 gettimeofday(&tv, nullptr);
1037 time_t t = tv.tv_sec;
1038 struct tm local_time;
1039 localtime_r(&t, &local_time);
1040 struct tm* tm_time = &local_time;
1041 stream_ << std::setfill('0')
1042 << std::setw(2) << 1 + tm_time->tm_mon
1043 << std::setw(2) << tm_time->tm_mday
1045 << std::setw(2) << tm_time->tm_hour
1046 << std::setw(2) << tm_time->tm_min
1047 << std::setw(2) << tm_time->tm_sec
1049 << std::setw(6) << tv.tv_usec
1052 #error Unsupported platform
1055 if (g_log_tickcount)
1056 stream_ << TickCount() << ':';
1059 stream_ << log_severity_name(severity_);
1061 stream_ << "VERBOSE" << -severity_;
1063 stream_ << ":" << filename << "(" << line << ")] ";
1065 message_start_ = stream_.str().length();
1069 // This has already been defined in the header, but defining it again as DWORD
1070 // ensures that the type used in the header is equivalent to DWORD. If not,
1071 // the redefinition is a compile error.
1072 typedef DWORD SystemErrorCode;
1075 SystemErrorCode GetLastSystemErrorCode() {
1077 return ::GetLastError();
1078 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1083 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
1085 const int kErrorMessageBufferSize = 256;
1086 char msgbuf[kErrorMessageBufferSize];
1087 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
1088 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
1089 base::size(msgbuf), nullptr);
1091 // Messages returned by system end with line breaks.
1092 return base::CollapseWhitespaceASCII(msgbuf, true) +
1093 base::StringPrintf(" (0x%lX)", error_code);
1095 return base::StringPrintf("Error (0x%lX) while retrieving error. (0x%lX)",
1096 GetLastError(), error_code);
1097 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1098 return base::safe_strerror(error_code) +
1099 base::StringPrintf(" (%d)", error_code);
1100 #endif // defined(OS_WIN)
1105 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
1107 LogSeverity severity,
1108 SystemErrorCode err)
1109 : LogMessage(file, line, severity), err_(err) {}
1111 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
1112 stream() << ": " << SystemErrorCodeToString(err_);
1113 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1114 // field) and use Alias in hopes that it makes it into crash dumps.
1115 DWORD last_error = err_;
1116 base::debug::Alias(&last_error);
1118 #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
1119 ErrnoLogMessage::ErrnoLogMessage(const char* file,
1121 LogSeverity severity,
1122 SystemErrorCode err)
1123 : LogMessage(file, line, severity), err_(err) {}
1125 ErrnoLogMessage::~ErrnoLogMessage() {
1126 stream() << ": " << SystemErrorCodeToString(err_);
1127 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
1128 // field) and use Alias in hopes that it makes it into crash dumps.
1129 int last_error = err_;
1130 base::debug::Alias(&last_error);
1132 #endif // defined(OS_WIN)
1134 void CloseLogFile() {
1135 #if defined(OS_POSIX) || defined(OS_FUCHSIA)
1136 LoggingLock logging_lock;
1138 CloseLogFileUnlocked();
1141 #if defined(OS_CHROMEOS)
1142 FILE* DuplicateLogFILE() {
1143 if ((g_logging_destination & LOG_TO_FILE) == 0 || !InitializeLogFileHandle())
1146 int log_fd = fileno(g_log_file);
1149 base::ScopedFD dup_fd(dup(log_fd));
1152 FILE* duplicate = fdopen(dup_fd.get(), "a");
1155 ignore_result(dup_fd.release());
1160 void RawLog(int level, const char* message) {
1161 if (level >= g_min_log_level && message) {
1162 size_t bytes_written = 0;
1163 const size_t message_len = strlen(message);
1165 while (bytes_written < message_len) {
1167 write(STDERR_FILENO, message + bytes_written,
1168 message_len - bytes_written));
1170 // Give up, nothing we can do now.
1173 bytes_written += rv;
1176 if (message_len > 0 && message[message_len - 1] != '\n') {
1178 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
1180 // Give up, nothing we can do now.
1187 if (level == LOG_FATAL)
1188 base::debug::BreakDebugger();
1191 // This was defined at the beginning of this file.
1195 bool IsLoggingToFileEnabled() {
1196 return g_logging_destination & LOG_TO_FILE;
1199 std::wstring GetLogFileFullPath() {
1200 if (g_log_file_name)
1201 return *g_log_file_name;
1202 return std::wstring();
1206 } // namespace logging
1208 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
1209 return out << (wstr ? base::WideToUTF8(wstr) : std::string());