blob: cea6edae4a37cef2519ff32045c46c0a3c73e4d0 [file] [log] [blame]
[email protected]63e66802012-01-18 21:21:091// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
[email protected]b16ef312008-08-19 18:36:235#include "base/logging.h"
[email protected]f6abeba2008-08-08 13:27:286
avi51ba3e692015-12-26 17:30:507#include <limits.h>
avi9b6f42932015-12-26 22:15:148#include <stdint.h>
9
bcwhite7a30eb42016-12-02 21:23:4010#include "base/debug/activity_tracker.h"
avi9b6f42932015-12-26 22:15:1411#include "base/macros.h"
12#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5013
[email protected]b16ef312008-08-19 18:36:2314#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5015#include <io.h>
[email protected]f6abeba2008-08-08 13:27:2816typedef HANDLE FileHandle;
17typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5018// 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
[email protected]052f1b52008-11-06 21:43:0722#elif defined(OS_MACOSX)
mark4c7449c2015-11-10 19:53:4223#include <asl.h>
24#include <CoreFoundation/CoreFoundation.h>
[email protected]f6abeba2008-08-08 13:27:2825#include <mach/mach.h>
26#include <mach/mach_time.h>
27#include <mach-o/dyld.h>
[email protected]e43eddf12009-12-29 00:32:5228#elif defined(OS_POSIX)
[email protected]19ea84ca2010-11-12 08:37:0829#if defined(OS_NACL)
thestig75f87352014-12-03 21:42:2730#include <sys/time.h> // timespec doesn't seem to be in <time.h>
[email protected]19ea84ca2010-11-12 08:37:0831#endif
[email protected]052f1b52008-11-06 21:43:0732#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5933#endif
34
35#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2036#include <errno.h>
mark4c7449c2015-11-10 19:53:4237#include <paths.h>
[email protected]166326c62010-08-05 15:50:2338#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2839#include <stdio.h>
[email protected]eb62f7262013-03-30 14:29:0040#include <stdlib.h>
[email protected]f6abeba2008-08-08 13:27:2841#include <string.h>
mark4c7449c2015-11-10 19:53:4242#include <sys/stat.h>
[email protected]f6abeba2008-08-08 13:27:2843#include <unistd.h>
44#define MAX_PATH PATH_MAX
45typedef FILE* FileHandle;
46typedef pthread_mutex_t* MutexHandle;
47#endif
48
[email protected]1f88b5162011-04-01 00:02:2949#include <algorithm>
50#include <cstring>
initial.commitd7cae122008-07-26 21:49:3851#include <ctime>
52#include <iomanip>
[email protected]1f88b5162011-04-01 00:02:2953#include <ostream>
[email protected]c914d8a2014-04-23 01:11:0154#include <string>
[email protected]b16ef312008-08-19 18:36:2355
initial.commitd7cae122008-07-26 21:49:3856#include "base/base_switches.h"
57#include "base/command_line.h"
[email protected]eb4c4d032012-04-03 18:45:0558#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5059#include "base/debug/debugger.h"
60#include "base/debug/stack_trace.h"
[email protected]2025d002012-11-14 20:54:3561#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0062#include "base/strings/string_piece.h"
[email protected]c914d8a2014-04-23 01:11:0163#include "base/strings/string_util.h"
64#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:4265#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:0766#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2067#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0968#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3669#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0470#if defined(OS_POSIX)
brettw6ee6fd62015-06-09 18:05:2471#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:0472#endif
[email protected]52a261f2009-03-03 15:01:1273
[email protected]3132e35c2011-07-07 20:46:5074#if defined(OS_ANDROID)
75#include <android/log.h>
76#endif
77
initial.commitd7cae122008-07-26 21:49:3878namespace logging {
79
[email protected]064aa162011-12-03 00:30:0880namespace {
81
thestig3e4787d2015-05-19 19:31:5282VlogInfo* g_vlog_info = nullptr;
83VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:3884
85const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]f2c05492014-06-17 12:04:2386 "INFO", "WARNING", "ERROR", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3887
thestig75f87352014-12-03 21:42:2788const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:1989 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
90 return log_severity_names[severity];
91 return "UNKNOWN";
92}
93
thestig3e4787d2015-05-19 19:31:5294int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3295
thestig3e4787d2015-05-19 19:31:5296LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:3897
[email protected]a33c9892008-08-25 20:10:3198// For LOG_ERROR and above, always print to stderr.
99const int kAlwaysPrintErrorLevel = LOG_ERROR;
100
[email protected]614e9fa2008-08-11 22:52:59101// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38102// will be lazily initialized to the default value when it is
103// first needed.
[email protected]f6abeba2008-08-08 13:27:28104#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59105typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:28106#else
[email protected]614e9fa2008-08-11 22:52:59107typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28108#endif
thestig3e4787d2015-05-19 19:31:52109PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38110
thestig3e4787d2015-05-19 19:31:52111// This file is lazily opened and the handle may be nullptr
112FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38113
thestig3e4787d2015-05-19 19:31:52114// What should be prepended to each message?
115bool g_log_process_id = false;
116bool g_log_thread_id = false;
117bool g_log_timestamp = true;
118bool g_log_tickcount = false;
initial.commitd7cae122008-07-26 21:49:38119
[email protected]81e0a852010-08-17 00:38:12120// Should we pop up fatal debug messages in a dialog?
121bool show_error_dialogs = false;
122
initial.commitd7cae122008-07-26 21:49:38123// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05124// the debug message dialog and process termination.
thestig3e4787d2015-05-19 19:31:52125LogAssertHandlerFunction log_assert_handler = nullptr;
[email protected]2b07b8412009-11-25 15:26:34126// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52127LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38128
[email protected]f6abeba2008-08-08 13:27:28129// Helper functions to wrap platform differences.
130
avi9b6f42932015-12-26 22:15:14131int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24132#if defined(OS_WIN)
133 return GetCurrentProcessId();
134#elif defined(OS_POSIX)
135 return getpid();
136#endif
137}
138
avi9b6f42932015-12-26 22:15:14139uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24140#if defined(OS_WIN)
141 return GetTickCount();
142#elif defined(OS_MACOSX)
143 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08144#elif defined(OS_NACL)
145 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
146 // So we have to use clock() for now.
147 return clock();
[email protected]e43eddf12009-12-29 00:32:52148#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07149 struct timespec ts;
150 clock_gettime(CLOCK_MONOTONIC, &ts);
151
avi9b6f42932015-12-26 22:15:14152 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
153 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07154
155 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24156#endif
157}
158
[email protected]614e9fa2008-08-11 22:52:59159void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28160#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59161 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27162#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45163 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28164#else
[email protected]614e9fa2008-08-11 22:52:59165 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28166#endif
167}
initial.commitd7cae122008-07-26 21:49:38168
[email protected]5f95d532010-10-01 17:16:58169PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55170#if defined(OS_WIN)
171 // On Windows we use the same path as the exe.
172 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52173 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58174
scottmgfc5b7072015-01-27 21:46:28175 PathString log_name = module_name;
176 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58177 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28178 log_name.erase(last_backslash + 1);
179 log_name += L"debug.log";
180 return log_name;
[email protected]5b84fe32010-09-14 22:24:55181#elif defined(OS_POSIX)
182 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58183 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55184#endif
185}
186
ananta61762fb2015-09-18 01:00:09187// We don't need locks on Windows for atomically appending to files. The OS
188// provides this functionality.
189#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55190// This class acts as a wrapper for locking the logging files.
191// LoggingLock::Init() should be called from the main thread before any logging
192// is done. Then whenever logging, be sure to have a local LoggingLock
193// instance on the stack. This will ensure that the lock is unlocked upon
194// exiting the frame.
195// LoggingLocks can not be nested.
196class LoggingLock {
197 public:
198 LoggingLock() {
199 LockLogging();
200 }
201
202 ~LoggingLock() {
203 UnlockLogging();
204 }
205
206 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
207 if (initialized)
208 return;
209 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58210
ananta61762fb2015-09-18 01:00:09211 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20212 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09213
[email protected]5b84fe32010-09-14 22:24:55214 initialized = true;
215 }
216
217 private:
218 static void LockLogging() {
219 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09220#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55221 pthread_mutex_lock(&log_mutex);
222#endif
223 } else {
224 // use the lock
225 log_lock->Lock();
226 }
227 }
228
229 static void UnlockLogging() {
230 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09231#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55232 pthread_mutex_unlock(&log_mutex);
233#endif
234 } else {
235 log_lock->Unlock();
236 }
237 }
238
239 // The lock is used if log file locking is false. It helps us avoid problems
240 // with multiple threads writing to the log file at the same time. Use
241 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20242 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55243
244 // When we don't use a lock, we are using a global mutex. We need to do this
245 // because LockFileEx is not thread safe.
ananta61762fb2015-09-18 01:00:09246#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55247 static pthread_mutex_t log_mutex;
248#endif
249
250 static bool initialized;
251 static LogLockingState lock_log_file;
252};
253
254// static
255bool LoggingLock::initialized = false;
256// static
thestig3e4787d2015-05-19 19:31:52257base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55258// static
259LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
260
ananta61762fb2015-09-18 01:00:09261#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55262pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
263#endif
264
ananta61762fb2015-09-18 01:00:09265#endif // OS_WIN
266
thestig3e4787d2015-05-19 19:31:52267// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38268// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52269// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38270bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52271 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38272 return true;
273
thestig3e4787d2015-05-19 19:31:52274 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59275 // Nobody has called InitLogging to specify a debug log file, so here we
276 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52277 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38278 }
279
thestig3e4787d2015-05-19 19:31:52280 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59281#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09282 // The FILE_APPEND_DATA access mask ensures that the file is atomically
283 // appended to across accesses from multiple threads.
284 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
285 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
286 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52287 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
288 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
289 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02290 // We are intentionally not using FilePath or FileUtil here to reduce the
291 // dependencies of the logging implementation. For e.g. FilePath and
292 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
293 // some consumers of base logging like chrome_elf, etc.
294 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32295 // try the current directory
anantaf2651872016-06-16 22:21:02296 wchar_t system_buffer[MAX_PATH];
297 system_buffer[0] = 0;
298 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
299 system_buffer);
300 if (len == 0 || len > arraysize(system_buffer))
ananta61762fb2015-09-18 01:00:09301 return false;
302
anantaf2651872016-06-16 22:21:02303 *g_log_file_name = system_buffer;
304 // Append a trailing backslash if needed.
305 if (g_log_file_name->back() != L'\\')
306 *g_log_file_name += L"\\";
307 *g_log_file_name += L"debug.log";
ananta61762fb2015-09-18 01:00:09308
309 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52310 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
311 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
312 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
313 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32314 return false;
315 }
initial.commitd7cae122008-07-26 21:49:38316 }
[email protected]78c6dd62009-06-08 23:29:11317#elif defined(OS_POSIX)
thestig3e4787d2015-05-19 19:31:52318 g_log_file = fopen(g_log_file_name->c_str(), "a");
319 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11320 return false;
[email protected]f6abeba2008-08-08 13:27:28321#endif
[email protected]1d8c2702008-08-19 23:39:32322 }
323
initial.commitd7cae122008-07-26 21:49:38324 return true;
325}
326
[email protected]17dcf752013-07-15 21:47:09327void CloseFile(FileHandle log) {
328#if defined(OS_WIN)
329 CloseHandle(log);
330#else
331 fclose(log);
332#endif
333}
334
335void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52336 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09337 return;
338
thestig3e4787d2015-05-19 19:31:52339 CloseFile(g_log_file);
340 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09341}
342
[email protected]064aa162011-12-03 00:30:08343} // namespace
344
scottmg3c957a52016-12-10 20:57:59345// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
346// an object of the correct type on the LHS of the unused part of the ternary
347// operator.
348std::ostream* g_swallow_stream;
349
[email protected]5e3f7c22013-06-21 21:15:33350LoggingSettings::LoggingSettings()
351 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52352 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33353 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38354 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08355
[email protected]5e3f7c22013-06-21 21:15:33356bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45357#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33358 // Can log only to the system debug log.
359 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45360#endif
pgal.u-szeged421dddb2014-11-25 12:55:02361 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52362 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36363 // vlog switches.
364 if (command_line->HasSwitch(switches::kV) ||
365 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52366 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08367 // by another thread. Don't delete the old VLogInfo, just create a second
368 // one. We keep track of both to avoid memory leak warnings.
369 CHECK(!g_vlog_info_prev);
370 g_vlog_info_prev = g_vlog_info;
371
[email protected]99b7c57f2010-09-29 19:26:36372 g_vlog_info =
373 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49374 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52375 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36376 }
377
thestig3e4787d2015-05-19 19:31:52378 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38379
[email protected]5e3f7c22013-06-21 21:15:33380 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52381 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21382 return true;
initial.commitd7cae122008-07-26 21:49:38383
ananta61762fb2015-09-18 01:00:09384#if !defined(OS_WIN)
[email protected]17dcf752013-07-15 21:47:09385 LoggingLock::Init(settings.lock_log, settings.log_file);
386 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09387#endif
[email protected]17dcf752013-07-15 21:47:09388
389 // Calling InitLogging twice or after some log call has already opened the
390 // default log file will re-initialize to the new options.
391 CloseLogFileUnlocked();
392
thestig3e4787d2015-05-19 19:31:52393 if (!g_log_file_name)
394 g_log_file_name = new PathString();
395 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33396 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52397 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38398
[email protected]c7d5da992010-10-28 00:20:21399 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38400}
401
402void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52403 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38404}
405
406int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52407 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38408}
409
skobesc78c0ad72015-12-07 20:21:23410bool ShouldCreateLogMessage(int severity) {
411 if (severity < g_min_log_level)
412 return false;
413
414 // Return true here unless we know ~LogMessage won't do anything. Note that
415 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
416 // when g_logging_destination is LOG_NONE.
417 return g_logging_destination != LOG_NONE || log_message_handler ||
418 severity >= kAlwaysPrintErrorLevel;
419}
420
[email protected]162ac0f2010-11-04 15:50:49421int GetVlogVerbosity() {
422 return std::max(-1, LOG_INFO - GetMinLogLevel());
423}
424
[email protected]99b7c57f2010-09-29 19:26:36425int GetVlogLevelHelper(const char* file, size_t N) {
426 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52427 // Note: |g_vlog_info| may change on a different thread during startup
428 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08429 VlogInfo* vlog_info = g_vlog_info;
430 return vlog_info ?
431 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49432 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36433}
434
initial.commitd7cae122008-07-26 21:49:38435void SetLogItems(bool enable_process_id, bool enable_thread_id,
436 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52437 g_log_process_id = enable_process_id;
438 g_log_thread_id = enable_thread_id;
439 g_log_timestamp = enable_timestamp;
440 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38441}
442
[email protected]81e0a852010-08-17 00:38:12443void SetShowErrorDialogs(bool enable_dialogs) {
444 show_error_dialogs = enable_dialogs;
445}
446
initial.commitd7cae122008-07-26 21:49:38447void SetLogAssertHandler(LogAssertHandlerFunction handler) {
448 log_assert_handler = handler;
449}
450
[email protected]2b07b8412009-11-25 15:26:34451void SetLogMessageHandler(LogMessageHandlerFunction handler) {
452 log_message_handler = handler;
453}
454
[email protected]64e5cc02010-11-03 19:20:27455LogMessageHandlerFunction GetLogMessageHandler() {
456 return log_message_handler;
457}
458
[email protected]6d445d32010-09-30 19:10:03459// Explicit instantiations for commonly used comparisons.
460template std::string* MakeCheckOpString<int, int>(
461 const int&, const int&, const char* names);
462template std::string* MakeCheckOpString<unsigned long, unsigned long>(
463 const unsigned long&, const unsigned long&, const char* names);
464template std::string* MakeCheckOpString<unsigned long, unsigned int>(
465 const unsigned long&, const unsigned int&, const char* names);
466template std::string* MakeCheckOpString<unsigned int, unsigned long>(
467 const unsigned int&, const unsigned long&, const char* names);
468template std::string* MakeCheckOpString<std::string, std::string>(
469 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34470
jbroman6bcfec422016-05-26 00:28:46471void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16472 (*os) << "nullptr";
473}
474
[email protected]f2c05492014-06-17 12:04:23475#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22476// Displays a message box to the user with the error message in it.
477// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25478// This is for developers only; we don't use this in circumstances
479// (like release builds) where users could see it, since users don't
480// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22481void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38482 if (str.empty())
483 return;
484
[email protected]81e0a852010-08-17 00:38:12485 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44486 return;
487
[email protected]f6abeba2008-08-08 13:27:28488#if defined(OS_WIN)
brettwe33526852015-10-03 00:46:01489 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
490 MB_OK | MB_ICONHAND | MB_TOPMOST);
[email protected]f6abeba2008-08-08 13:27:28491#else
[email protected]561513f2010-12-16 23:29:25492 // We intentionally don't implement a dialog on other platforms.
493 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52494#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38495}
[email protected]f2c05492014-06-17 12:04:23496#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38497
[email protected]3f85caa2009-04-14 16:52:11498#if defined(OS_WIN)
499LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
500}
501
502LogMessage::SaveLastError::~SaveLastError() {
503 ::SetLastError(last_error_);
504}
505#endif // defined(OS_WIN)
506
[email protected]eae9c062011-01-11 00:50:59507LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
508 : severity_(severity), file_(file), line_(line) {
509 Init(file, line);
510}
511
tnagel4a045d3f2015-07-12 14:19:28512LogMessage::LogMessage(const char* file, int line, const char* condition)
513 : severity_(LOG_FATAL), file_(file), line_(line) {
514 Init(file, line);
515 stream_ << "Check failed: " << condition << ". ";
516}
517
[email protected]9c7132e2011-02-08 07:39:08518LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49519 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38520 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08521 stream_ << "Check failed: " << *result;
522 delete result;
initial.commitd7cae122008-07-26 21:49:38523}
524
[email protected]fb62a532009-02-12 01:19:05525LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08526 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49527 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05528 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08529 stream_ << "Check failed: " << *result;
530 delete result;
[email protected]fb62a532009-02-12 01:19:05531}
532
initial.commitd7cae122008-07-26 21:49:38533LogMessage::~LogMessage() {
jam79dc59a2015-08-17 03:38:16534#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__)
brucedawson7c559eb2015-09-05 00:34:42535 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
536 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50537 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24538 stream_ << std::endl; // Newline to separate from log message.
539 trace.OutputToStream(&stream_);
540 }
[email protected]1d8c2702008-08-19 23:39:32541#endif
[email protected]d1ccc35a2010-03-24 05:03:24542 stream_ << std::endl;
543 std::string str_newline(stream_.str());
544
[email protected]2b07b8412009-11-25 15:26:34545 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33546 if (log_message_handler &&
547 log_message_handler(severity_, file_, line_,
548 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49549 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34550 return;
[email protected]162ac0f2010-11-04 15:50:49551 }
initial.commitd7cae122008-07-26 21:49:38552
thestig3e4787d2015-05-19 19:31:52553 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28554#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38555 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42556#elif defined(OS_MACOSX)
557 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
558 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log). If
559 // there's something weird about stderr, assume that log messages are going
560 // nowhere and log via ASL too. Messages logged via ASL show up in
561 // Console.app.
562 //
563 // Programs started by launchd, as UI applications normally are, have had
564 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
565 // a pipe to launchd, which logged what it received (see log_redirect_fd in
566 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
567 //
568 // Another alternative would be to determine whether stderr is a pipe to
569 // launchd and avoid logging via ASL only in that case. See 10.7.5
570 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
571 // both stderr and ASL even in tests, where it's undesirable to log to the
572 // system log at all.
573 //
574 // Note that the ASL client by default discards messages whose levels are
575 // below ASL_LEVEL_NOTICE. It's possible to change that with
576 // asl_set_filter(), but this is pointless because syslogd normally applies
577 // the same filter.
578 const bool log_via_asl = []() {
579 struct stat stderr_stat;
580 if (fstat(fileno(stderr), &stderr_stat) == -1) {
581 return true;
582 }
583 if (!S_ISCHR(stderr_stat.st_mode)) {
584 return false;
585 }
586
587 struct stat dev_null_stat;
588 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
589 return true;
590 }
591
592 return !S_ISCHR(dev_null_stat.st_mode) ||
593 stderr_stat.st_rdev == dev_null_stat.st_rdev;
594 }();
595
596 if (log_via_asl) {
597 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
598 // CF-1153.18/CFUtilities.c __CFLogCString().
599 //
600 // The ASL facility is set to the main bundle ID if available. Otherwise,
601 // "com.apple.console" is used.
602 CFBundleRef main_bundle = CFBundleGetMainBundle();
603 CFStringRef main_bundle_id_cf =
604 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
605 std::string asl_facility =
606 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
607 : std::string("com.apple.console");
608
609 class ASLClient {
610 public:
611 explicit ASLClient(const std::string& asl_facility)
612 : client_(asl_open(nullptr,
613 asl_facility.c_str(),
614 ASL_OPT_NO_DELAY)) {}
615 ~ASLClient() { asl_close(client_); }
616
617 aslclient get() const { return client_; }
618
619 private:
620 aslclient client_;
621 DISALLOW_COPY_AND_ASSIGN(ASLClient);
622 } asl_client(asl_facility);
623
624 class ASLMessage {
625 public:
626 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
627 ~ASLMessage() { asl_free(message_); }
628
629 aslmsg get() const { return message_; }
630
631 private:
632 aslmsg message_;
633 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
634 } asl_message;
635
636 // By default, messages are only readable by the admin group. Explicitly
637 // make them readable by the user generating the messages.
638 char euid_string[12];
639 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
640 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
641
642 // Map Chrome log severities to ASL log levels.
643 const char* const asl_level_string = [](LogSeverity severity) {
644 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
645 // non-obvious two-step macro trick achieves what's needed.
646 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
647#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
648#define ASL_LEVEL_STR_X(level) #level
649 switch (severity) {
650 case LOG_INFO:
651 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
652 case LOG_WARNING:
653 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
654 case LOG_ERROR:
655 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
656 case LOG_FATAL:
657 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
658 default:
659 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
660 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
661 }
662#undef ASL_LEVEL_STR
663#undef ASL_LEVEL_STR_X
664 }(severity_);
665 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
666
667 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
668
669 asl_send(asl_client.get(), asl_message.get());
670 }
[email protected]3132e35c2011-07-07 20:46:50671#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25672 android_LogPriority priority =
673 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50674 switch (severity_) {
675 case LOG_INFO:
676 priority = ANDROID_LOG_INFO;
677 break;
678 case LOG_WARNING:
679 priority = ANDROID_LOG_WARN;
680 break;
681 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50682 priority = ANDROID_LOG_ERROR;
683 break;
684 case LOG_FATAL:
685 priority = ANDROID_LOG_FATAL;
686 break;
687 }
688 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18689#endif
[email protected]51105382014-03-14 17:02:15690 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06691 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31692 } else if (severity_ >= kAlwaysPrintErrorLevel) {
693 // When we're only outputting to a log file, above a certain log level, we
694 // should still output to stderr so that we can better detect and diagnose
695 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15696 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02697 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28698 }
[email protected]52a261f2009-03-03 15:01:12699
initial.commitd7cae122008-07-26 21:49:38700 // write to log file
thestig3e4787d2015-05-19 19:31:52701 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09702 // We can have multiple threads and/or processes, so try to prevent them
703 // from clobbering each other's writes.
704 // If the client app did not call InitLogging, and the lock has not
705 // been created do it now. We do this on demand, but if two threads try
706 // to do this at the same time, there will be a race condition to create
707 // the lock. This is why InitLogging should be called from the main
708 // thread at the beginning of execution.
ananta61762fb2015-09-18 01:00:09709#if !defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52710 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55711 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09712#endif
[email protected]5b84fe32010-09-14 22:24:55713 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28714#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55715 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52716 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55717 static_cast<const void*>(str_newline.c_str()),
718 static_cast<DWORD>(str_newline.length()),
719 &num_written,
thestig3e4787d2015-05-19 19:31:52720 nullptr);
[email protected]cba21962010-08-31 22:35:55721#else
[email protected]51105382014-03-14 17:02:15722 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52723 str_newline.data(), str_newline.size(), 1, g_log_file));
724 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55725#endif
initial.commitd7cae122008-07-26 21:49:38726 }
727 }
728
729 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40730 // Write the log message to the global activity tracker, if running.
731 base::debug::GlobalActivityTracker* tracker =
732 base::debug::GlobalActivityTracker::Get();
733 if (tracker)
734 tracker->RecordLogMessage(str_newline);
735
[email protected]eb4c4d032012-04-03 18:45:05736 // Ensure the first characters of the string are on the stack so they
737 // are contained in minidumps for diagnostic purposes.
738 char str_stack[1024];
739 str_newline.copy(str_stack, arraysize(str_stack));
740 base::debug::Alias(str_stack);
741
[email protected]82d89ab2014-02-28 18:25:34742 if (log_assert_handler) {
743 // Make a copy of the string for the handler out of paranoia.
744 log_assert_handler(std::string(stream_.str()));
[email protected]1ffe08c12008-08-13 11:15:11745 } else {
[email protected]82d89ab2014-02-28 18:25:34746 // Don't use the string with the newline, get a fresh version to send to
747 // the debug message process. We also don't display assertions to the
748 // user in release mode. The enduser can't do anything with this
749 // information, and displaying message boxes when the application is
750 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50751#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42752 if (!base::debug::BeingDebugged()) {
753 // Displaying a dialog is unnecessary when debugging and can complicate
754 // debugging.
755 DisplayDebugMessageInDialog(stream_.str());
756 }
[email protected]4d5901272008-11-06 00:33:50757#endif
[email protected]82d89ab2014-02-28 18:25:34758 // Crash the process to generate a dump.
759 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38760 }
761 }
762}
763
[email protected]eae9c062011-01-11 00:50:59764// writes the common header info to the stream
765void LogMessage::Init(const char* file, int line) {
766 base::StringPiece filename(file);
767 size_t last_slash_pos = filename.find_last_of("\\/");
768 if (last_slash_pos != base::StringPiece::npos)
769 filename.remove_prefix(last_slash_pos + 1);
770
771 // TODO(darin): It might be nice if the columns were fixed width.
772
773 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52774 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59775 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52776 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09777 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52778 if (g_log_timestamp) {
djkurtz543a3be2016-11-30 14:17:34779#if defined(OS_POSIX)
780 timeval tv;
781 gettimeofday(&tv, nullptr);
782 time_t t = tv.tv_sec;
783 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59784 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59785 struct tm* tm_time = &local_time;
786 stream_ << std::setfill('0')
787 << std::setw(2) << 1 + tm_time->tm_mon
788 << std::setw(2) << tm_time->tm_mday
789 << '/'
790 << std::setw(2) << tm_time->tm_hour
791 << std::setw(2) << tm_time->tm_min
792 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34793 << '.'
794 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59795 << ':';
djkurtz543a3be2016-11-30 14:17:34796#elif defined(OS_WIN)
797 SYSTEMTIME local_time;
798 GetLocalTime(&local_time);
799 stream_ << std::setfill('0')
800 << std::setw(2) << local_time.wMonth
801 << std::setw(2) << local_time.wDay
802 << '/'
803 << std::setw(2) << local_time.wHour
804 << std::setw(2) << local_time.wMinute
805 << std::setw(2) << local_time.wSecond
806 << '.'
807 << std::setw(3) << local_time.wMilliseconds
808 << ':';
809#endif
[email protected]eae9c062011-01-11 00:50:59810 }
thestig3e4787d2015-05-19 19:31:52811 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59812 stream_ << TickCount() << ':';
813 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19814 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59815 else
816 stream_ << "VERBOSE" << -severity_;
817
818 stream_ << ":" << filename << "(" << line << ")] ";
819
pkasting9cf9b942014-10-01 22:18:43820 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59821}
822
[email protected]d8617a62009-10-09 23:52:20823#if defined(OS_WIN)
824// This has already been defined in the header, but defining it again as DWORD
825// ensures that the type used in the header is equivalent to DWORD. If not,
826// the redefinition is a compile error.
827typedef DWORD SystemErrorCode;
828#endif
829
830SystemErrorCode GetLastSystemErrorCode() {
831#if defined(OS_WIN)
832 return ::GetLastError();
833#elif defined(OS_POSIX)
834 return errno;
835#else
836#error Not implemented
837#endif
838}
839
840#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01841BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27842 const int kErrorMessageBufferSize = 256;
843 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01844 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52845 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
846 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01847 if (len) {
848 // Messages returned by system end with line breaks.
849 return base::CollapseWhitespaceASCII(msgbuf, true) +
850 base::StringPrintf(" (0x%X)", error_code);
851 }
852 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
853 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20854}
[email protected]c914d8a2014-04-23 01:11:01855#elif defined(OS_POSIX)
856BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
brettw6ee6fd62015-06-09 18:05:24857 return base::safe_strerror(error_code);
[email protected]c914d8a2014-04-23 01:11:01858}
859#else
860#error Not implemented
thestig3e4787d2015-05-19 19:31:52861#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20862
[email protected]c914d8a2014-04-23 01:11:01863
864#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20865Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
866 int line,
867 LogSeverity severity,
868 SystemErrorCode err)
869 : err_(err),
[email protected]d8617a62009-10-09 23:52:20870 log_message_(file, line, severity) {
871}
872
873Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01874 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06875 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
876 // field) and use Alias in hopes that it makes it into crash dumps.
877 DWORD last_error = err_;
878 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20879}
880#elif defined(OS_POSIX)
881ErrnoLogMessage::ErrnoLogMessage(const char* file,
882 int line,
883 LogSeverity severity,
884 SystemErrorCode err)
885 : err_(err),
886 log_message_(file, line, severity) {
887}
888
889ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01890 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]d8617a62009-10-09 23:52:20891}
thestig3e4787d2015-05-19 19:31:52892#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20893
initial.commitd7cae122008-07-26 21:49:38894void CloseLogFile() {
ananta61762fb2015-09-18 01:00:09895#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55896 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09897#endif
[email protected]17dcf752013-07-15 21:47:09898 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38899}
900
[email protected]e36ddc82009-12-08 04:22:50901void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:49902 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:50903 size_t bytes_written = 0;
904 const size_t message_len = strlen(message);
905 int rv;
906 while (bytes_written < message_len) {
907 rv = HANDLE_EINTR(
908 write(STDERR_FILENO, message + bytes_written,
909 message_len - bytes_written));
910 if (rv < 0) {
911 // Give up, nothing we can do now.
912 break;
913 }
914 bytes_written += rv;
915 }
916
917 if (message_len > 0 && message[message_len - 1] != '\n') {
918 do {
919 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
920 if (rv < 0) {
921 // Give up, nothing we can do now.
922 break;
923 }
924 } while (rv != 1);
925 }
926 }
927
928 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50929 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50930}
931
[email protected]34a907732012-01-20 06:33:27932// This was defined at the beginning of this file.
933#undef write
934
[email protected]f01b88a2013-02-27 22:04:00935#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09936bool IsLoggingToFileEnabled() {
937 return g_logging_destination & LOG_TO_FILE;
938}
939
[email protected]f01b88a2013-02-27 22:04:00940std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:52941 if (g_log_file_name)
942 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:00943 return std::wstring();
944}
945#endif
946
tnagel80388e682015-05-26 13:27:56947BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:14948 LogMessage(file, line, LOG_ERROR).stream()
949 << "NOTREACHED() hit.";
950}
951
[email protected]96fd0032009-04-24 00:13:08952} // namespace logging
initial.commitd7cae122008-07-26 21:49:38953
[email protected]81411c62014-07-08 23:03:06954std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:49955 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:38956}