blob: cce9c722ab9dab0e9b69b0a16d8ef1db137b59c9 [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
avi9b6f42932015-12-26 22:15:1410#include "base/macros.h"
11#include "build/build_config.h"
avi51ba3e692015-12-26 17:30:5012
[email protected]b16ef312008-08-19 18:36:2313#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:5014#include <io.h>
alex-accc1bde62017-04-19 08:33:5515#include <windows.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>
alex-accc1bde62017-04-19 08:33:5554#include <stack>
[email protected]c914d8a2014-04-23 01:11:0155#include <string>
alex-accc1bde62017-04-19 08:33:5556#include <utility>
[email protected]b16ef312008-08-19 18:36:2357
initial.commitd7cae122008-07-26 21:49:3858#include "base/base_switches.h"
alex-accc1bde62017-04-19 08:33:5559#include "base/callback.h"
initial.commitd7cae122008-07-26 21:49:3860#include "base/command_line.h"
alex-accc1bde62017-04-19 08:33:5561#include "base/debug/activity_tracker.h"
[email protected]eb4c4d032012-04-03 18:45:0562#include "base/debug/alias.h"
[email protected]58580352010-10-26 04:07:5063#include "base/debug/debugger.h"
64#include "base/debug/stack_trace.h"
alex-accc1bde62017-04-19 08:33:5565#include "base/lazy_instance.h"
[email protected]2025d002012-11-14 20:54:3566#include "base/posix/eintr_wrapper.h"
[email protected]eb62f7262013-03-30 14:29:0067#include "base/strings/string_piece.h"
[email protected]c914d8a2014-04-23 01:11:0168#include "base/strings/string_util.h"
69#include "base/strings/stringprintf.h"
mark4c7449c2015-11-10 19:53:4270#include "base/strings/sys_string_conversions.h"
[email protected]a4ea1f12013-06-07 18:37:0771#include "base/strings/utf_string_conversions.h"
[email protected]bc581a682011-01-01 23:16:2072#include "base/synchronization/lock_impl.h"
[email protected]63e66802012-01-18 21:21:0973#include "base/threading/platform_thread.h"
[email protected]99b7c57f2010-09-29 19:26:3674#include "base/vlog.h"
[email protected]53c7ce42010-12-14 16:20:0475#if defined(OS_POSIX)
brettw6ee6fd62015-06-09 18:05:2476#include "base/posix/safe_strerror.h"
[email protected]53c7ce42010-12-14 16:20:0477#endif
[email protected]52a261f2009-03-03 15:01:1278
[email protected]3132e35c2011-07-07 20:46:5079#if defined(OS_ANDROID)
80#include <android/log.h>
81#endif
82
initial.commitd7cae122008-07-26 21:49:3883namespace logging {
84
[email protected]064aa162011-12-03 00:30:0885namespace {
86
thestig3e4787d2015-05-19 19:31:5287VlogInfo* g_vlog_info = nullptr;
88VlogInfo* g_vlog_info_prev = nullptr;
initial.commitd7cae122008-07-26 21:49:3889
90const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]f2c05492014-06-17 12:04:2391 "INFO", "WARNING", "ERROR", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3892
thestig75f87352014-12-03 21:42:2793const char* log_severity_name(int severity) {
[email protected]80f360a2014-01-23 01:36:1994 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
95 return log_severity_names[severity];
96 return "UNKNOWN";
97}
98
thestig3e4787d2015-05-19 19:31:5299int g_min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:32100
thestig3e4787d2015-05-19 19:31:52101LoggingDestination g_logging_destination = LOG_DEFAULT;
initial.commitd7cae122008-07-26 21:49:38102
[email protected]a33c9892008-08-25 20:10:31103// For LOG_ERROR and above, always print to stderr.
104const int kAlwaysPrintErrorLevel = LOG_ERROR;
105
[email protected]614e9fa2008-08-11 22:52:59106// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:38107// will be lazily initialized to the default value when it is
108// first needed.
[email protected]f6abeba2008-08-08 13:27:28109#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59110typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:28111#else
[email protected]614e9fa2008-08-11 22:52:59112typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:28113#endif
thestig3e4787d2015-05-19 19:31:52114PathString* g_log_file_name = nullptr;
initial.commitd7cae122008-07-26 21:49:38115
thestig3e4787d2015-05-19 19:31:52116// This file is lazily opened and the handle may be nullptr
117FileHandle g_log_file = nullptr;
initial.commitd7cae122008-07-26 21:49:38118
thestig3e4787d2015-05-19 19:31:52119// What should be prepended to each message?
120bool g_log_process_id = false;
121bool g_log_thread_id = false;
122bool g_log_timestamp = true;
123bool g_log_tickcount = false;
initial.commitd7cae122008-07-26 21:49:38124
[email protected]81e0a852010-08-17 00:38:12125// Should we pop up fatal debug messages in a dialog?
126bool show_error_dialogs = false;
127
initial.commitd7cae122008-07-26 21:49:38128// An assert handler override specified by the client to be called instead of
alex-accc1bde62017-04-19 08:33:55129// the debug message dialog and process termination. Assert handlers are stored
130// in stack to allow overriding and restoring.
131base::LazyInstance<std::stack<LogAssertHandlerFunction>>::Leaky
132 log_assert_handler_stack = LAZY_INSTANCE_INITIALIZER;
133
[email protected]2b07b8412009-11-25 15:26:34134// A log message handler that gets notified of every log message we process.
thestig3e4787d2015-05-19 19:31:52135LogMessageHandlerFunction log_message_handler = nullptr;
initial.commitd7cae122008-07-26 21:49:38136
[email protected]f6abeba2008-08-08 13:27:28137// Helper functions to wrap platform differences.
138
avi9b6f42932015-12-26 22:15:14139int32_t CurrentProcessId() {
[email protected]f8588472008-11-05 23:17:24140#if defined(OS_WIN)
141 return GetCurrentProcessId();
142#elif defined(OS_POSIX)
143 return getpid();
144#endif
145}
146
avi9b6f42932015-12-26 22:15:14147uint64_t TickCount() {
[email protected]f8588472008-11-05 23:17:24148#if defined(OS_WIN)
149 return GetTickCount();
150#elif defined(OS_MACOSX)
151 return mach_absolute_time();
[email protected]19ea84ca2010-11-12 08:37:08152#elif defined(OS_NACL)
153 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
154 // So we have to use clock() for now.
155 return clock();
[email protected]e43eddf12009-12-29 00:32:52156#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07157 struct timespec ts;
158 clock_gettime(CLOCK_MONOTONIC, &ts);
159
avi9b6f42932015-12-26 22:15:14160 uint64_t absolute_micro = static_cast<int64_t>(ts.tv_sec) * 1000000 +
161 static_cast<int64_t>(ts.tv_nsec) / 1000;
[email protected]052f1b52008-11-06 21:43:07162
163 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24164#endif
165}
166
[email protected]614e9fa2008-08-11 22:52:59167void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28168#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59169 DeleteFile(log_name.c_str());
thestig75f87352014-12-03 21:42:27170#elif defined(OS_NACL)
[email protected]ac07ec52013-04-22 17:32:45171 // Do nothing; unlink() isn't supported on NaCl.
[email protected]f6abeba2008-08-08 13:27:28172#else
[email protected]614e9fa2008-08-11 22:52:59173 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28174#endif
175}
initial.commitd7cae122008-07-26 21:49:38176
[email protected]5f95d532010-10-01 17:16:58177PathString GetDefaultLogFile() {
[email protected]5b84fe32010-09-14 22:24:55178#if defined(OS_WIN)
179 // On Windows we use the same path as the exe.
180 wchar_t module_name[MAX_PATH];
thestig3e4787d2015-05-19 19:31:52181 GetModuleFileName(nullptr, module_name, MAX_PATH);
[email protected]5f95d532010-10-01 17:16:58182
scottmgfc5b7072015-01-27 21:46:28183 PathString log_name = module_name;
184 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
[email protected]5f95d532010-10-01 17:16:58185 if (last_backslash != PathString::npos)
scottmgfc5b7072015-01-27 21:46:28186 log_name.erase(last_backslash + 1);
187 log_name += L"debug.log";
188 return log_name;
[email protected]5b84fe32010-09-14 22:24:55189#elif defined(OS_POSIX)
190 // On other platforms we just use the current directory.
[email protected]5f95d532010-10-01 17:16:58191 return PathString("debug.log");
[email protected]5b84fe32010-09-14 22:24:55192#endif
193}
194
ananta61762fb2015-09-18 01:00:09195// We don't need locks on Windows for atomically appending to files. The OS
196// provides this functionality.
197#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55198// This class acts as a wrapper for locking the logging files.
199// LoggingLock::Init() should be called from the main thread before any logging
200// is done. Then whenever logging, be sure to have a local LoggingLock
201// instance on the stack. This will ensure that the lock is unlocked upon
202// exiting the frame.
203// LoggingLocks can not be nested.
204class LoggingLock {
205 public:
206 LoggingLock() {
207 LockLogging();
208 }
209
210 ~LoggingLock() {
211 UnlockLogging();
212 }
213
214 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
215 if (initialized)
216 return;
217 lock_log_file = lock_log;
[email protected]5f95d532010-10-01 17:16:58218
ananta61762fb2015-09-18 01:00:09219 if (lock_log_file != LOCK_LOG_FILE)
[email protected]bc581a682011-01-01 23:16:20220 log_lock = new base::internal::LockImpl();
ananta61762fb2015-09-18 01:00:09221
[email protected]5b84fe32010-09-14 22:24:55222 initialized = true;
223 }
224
225 private:
226 static void LockLogging() {
227 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09228#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55229 pthread_mutex_lock(&log_mutex);
230#endif
231 } else {
232 // use the lock
233 log_lock->Lock();
234 }
235 }
236
237 static void UnlockLogging() {
238 if (lock_log_file == LOCK_LOG_FILE) {
ananta61762fb2015-09-18 01:00:09239#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55240 pthread_mutex_unlock(&log_mutex);
241#endif
242 } else {
243 log_lock->Unlock();
244 }
245 }
246
247 // The lock is used if log file locking is false. It helps us avoid problems
248 // with multiple threads writing to the log file at the same time. Use
249 // LockImpl directly instead of using Lock, because Lock makes logging calls.
[email protected]bc581a682011-01-01 23:16:20250 static base::internal::LockImpl* log_lock;
[email protected]5b84fe32010-09-14 22:24:55251
252 // When we don't use a lock, we are using a global mutex. We need to do this
253 // because LockFileEx is not thread safe.
ananta61762fb2015-09-18 01:00:09254#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55255 static pthread_mutex_t log_mutex;
256#endif
257
258 static bool initialized;
259 static LogLockingState lock_log_file;
260};
261
262// static
263bool LoggingLock::initialized = false;
264// static
thestig3e4787d2015-05-19 19:31:52265base::internal::LockImpl* LoggingLock::log_lock = nullptr;
[email protected]5b84fe32010-09-14 22:24:55266// static
267LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
268
ananta61762fb2015-09-18 01:00:09269#if defined(OS_POSIX)
[email protected]5b84fe32010-09-14 22:24:55270pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
271#endif
272
ananta61762fb2015-09-18 01:00:09273#endif // OS_WIN
274
thestig3e4787d2015-05-19 19:31:52275// Called by logging functions to ensure that |g_log_file| is initialized
initial.commitd7cae122008-07-26 21:49:38276// and can be used for writing. Returns false if the file could not be
thestig3e4787d2015-05-19 19:31:52277// initialized. |g_log_file| will be nullptr in this case.
initial.commitd7cae122008-07-26 21:49:38278bool InitializeLogFileHandle() {
thestig3e4787d2015-05-19 19:31:52279 if (g_log_file)
initial.commitd7cae122008-07-26 21:49:38280 return true;
281
thestig3e4787d2015-05-19 19:31:52282 if (!g_log_file_name) {
[email protected]614e9fa2008-08-11 22:52:59283 // Nobody has called InitLogging to specify a debug log file, so here we
284 // initialize the log file name to a default.
thestig3e4787d2015-05-19 19:31:52285 g_log_file_name = new PathString(GetDefaultLogFile());
initial.commitd7cae122008-07-26 21:49:38286 }
287
thestig3e4787d2015-05-19 19:31:52288 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]614e9fa2008-08-11 22:52:59289#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09290 // The FILE_APPEND_DATA access mask ensures that the file is atomically
291 // appended to across accesses from multiple threads.
292 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa364399(v=vs.85).aspx
293 // https://msdn.microsoft.com/en-us/library/windows/desktop/aa363858(v=vs.85).aspx
294 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52295 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
296 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
297 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
anantaf2651872016-06-16 22:21:02298 // We are intentionally not using FilePath or FileUtil here to reduce the
299 // dependencies of the logging implementation. For e.g. FilePath and
300 // FileUtil depend on shell32 and user32.dll. This is not acceptable for
301 // some consumers of base logging like chrome_elf, etc.
302 // Please don't change the code below to use FilePath.
[email protected]1d8c2702008-08-19 23:39:32303 // try the current directory
anantaf2651872016-06-16 22:21:02304 wchar_t system_buffer[MAX_PATH];
305 system_buffer[0] = 0;
306 DWORD len = ::GetCurrentDirectory(arraysize(system_buffer),
307 system_buffer);
308 if (len == 0 || len > arraysize(system_buffer))
ananta61762fb2015-09-18 01:00:09309 return false;
310
anantaf2651872016-06-16 22:21:02311 *g_log_file_name = system_buffer;
312 // Append a trailing backslash if needed.
313 if (g_log_file_name->back() != L'\\')
314 *g_log_file_name += L"\\";
315 *g_log_file_name += L"debug.log";
ananta61762fb2015-09-18 01:00:09316
317 g_log_file = CreateFile(g_log_file_name->c_str(), FILE_APPEND_DATA,
thestig3e4787d2015-05-19 19:31:52318 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
319 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
320 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
321 g_log_file = nullptr;
[email protected]1d8c2702008-08-19 23:39:32322 return false;
323 }
initial.commitd7cae122008-07-26 21:49:38324 }
[email protected]78c6dd62009-06-08 23:29:11325#elif defined(OS_POSIX)
thestig3e4787d2015-05-19 19:31:52326 g_log_file = fopen(g_log_file_name->c_str(), "a");
327 if (g_log_file == nullptr)
[email protected]78c6dd62009-06-08 23:29:11328 return false;
[email protected]f6abeba2008-08-08 13:27:28329#endif
[email protected]1d8c2702008-08-19 23:39:32330 }
331
initial.commitd7cae122008-07-26 21:49:38332 return true;
333}
334
[email protected]17dcf752013-07-15 21:47:09335void CloseFile(FileHandle log) {
336#if defined(OS_WIN)
337 CloseHandle(log);
338#else
339 fclose(log);
340#endif
341}
342
343void CloseLogFileUnlocked() {
thestig3e4787d2015-05-19 19:31:52344 if (!g_log_file)
[email protected]17dcf752013-07-15 21:47:09345 return;
346
thestig3e4787d2015-05-19 19:31:52347 CloseFile(g_log_file);
348 g_log_file = nullptr;
[email protected]17dcf752013-07-15 21:47:09349}
350
[email protected]064aa162011-12-03 00:30:08351} // namespace
352
scottmg3c957a52016-12-10 20:57:59353// This is never instantiated, it's just used for EAT_STREAM_PARAMETERS to have
354// an object of the correct type on the LHS of the unused part of the ternary
355// operator.
356std::ostream* g_swallow_stream;
357
[email protected]5e3f7c22013-06-21 21:15:33358LoggingSettings::LoggingSettings()
359 : logging_dest(LOG_DEFAULT),
thestig3e4787d2015-05-19 19:31:52360 log_file(nullptr),
[email protected]5e3f7c22013-06-21 21:15:33361 lock_log(LOCK_LOG_FILE),
[email protected]1a1505512014-03-10 18:23:38362 delete_old(APPEND_TO_OLD_LOG_FILE) {}
[email protected]064aa162011-12-03 00:30:08363
[email protected]5e3f7c22013-06-21 21:15:33364bool BaseInitLoggingImpl(const LoggingSettings& settings) {
[email protected]ac07ec52013-04-22 17:32:45365#if defined(OS_NACL)
[email protected]5e3f7c22013-06-21 21:15:33366 // Can log only to the system debug log.
367 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
[email protected]ac07ec52013-04-22 17:32:45368#endif
pgal.u-szeged421dddb2014-11-25 12:55:02369 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
thestig3e4787d2015-05-19 19:31:52370 // Don't bother initializing |g_vlog_info| unless we use one of the
[email protected]99b7c57f2010-09-29 19:26:36371 // vlog switches.
372 if (command_line->HasSwitch(switches::kV) ||
373 command_line->HasSwitch(switches::kVModule)) {
thestig3e4787d2015-05-19 19:31:52374 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
[email protected]064aa162011-12-03 00:30:08375 // by another thread. Don't delete the old VLogInfo, just create a second
376 // one. We keep track of both to avoid memory leak warnings.
377 CHECK(!g_vlog_info_prev);
378 g_vlog_info_prev = g_vlog_info;
379
[email protected]99b7c57f2010-09-29 19:26:36380 g_vlog_info =
381 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
[email protected]162ac0f2010-11-04 15:50:49382 command_line->GetSwitchValueASCII(switches::kVModule),
thestig3e4787d2015-05-19 19:31:52383 &g_min_log_level);
[email protected]99b7c57f2010-09-29 19:26:36384 }
385
thestig3e4787d2015-05-19 19:31:52386 g_logging_destination = settings.logging_dest;
initial.commitd7cae122008-07-26 21:49:38387
[email protected]5e3f7c22013-06-21 21:15:33388 // ignore file options unless logging to file is set.
thestig3e4787d2015-05-19 19:31:52389 if ((g_logging_destination & LOG_TO_FILE) == 0)
[email protected]c7d5da992010-10-28 00:20:21390 return true;
initial.commitd7cae122008-07-26 21:49:38391
ananta61762fb2015-09-18 01:00:09392#if !defined(OS_WIN)
[email protected]17dcf752013-07-15 21:47:09393 LoggingLock::Init(settings.lock_log, settings.log_file);
394 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09395#endif
[email protected]17dcf752013-07-15 21:47:09396
397 // Calling InitLogging twice or after some log call has already opened the
398 // default log file will re-initialize to the new options.
399 CloseLogFileUnlocked();
400
thestig3e4787d2015-05-19 19:31:52401 if (!g_log_file_name)
402 g_log_file_name = new PathString();
403 *g_log_file_name = settings.log_file;
[email protected]5e3f7c22013-06-21 21:15:33404 if (settings.delete_old == DELETE_OLD_LOG_FILE)
thestig3e4787d2015-05-19 19:31:52405 DeleteFilePath(*g_log_file_name);
initial.commitd7cae122008-07-26 21:49:38406
[email protected]c7d5da992010-10-28 00:20:21407 return InitializeLogFileHandle();
initial.commitd7cae122008-07-26 21:49:38408}
409
410void SetMinLogLevel(int level) {
thestig3e4787d2015-05-19 19:31:52411 g_min_log_level = std::min(LOG_FATAL, level);
initial.commitd7cae122008-07-26 21:49:38412}
413
414int GetMinLogLevel() {
thestig3e4787d2015-05-19 19:31:52415 return g_min_log_level;
initial.commitd7cae122008-07-26 21:49:38416}
417
skobesc78c0ad72015-12-07 20:21:23418bool ShouldCreateLogMessage(int severity) {
419 if (severity < g_min_log_level)
420 return false;
421
422 // Return true here unless we know ~LogMessage won't do anything. Note that
423 // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
424 // when g_logging_destination is LOG_NONE.
425 return g_logging_destination != LOG_NONE || log_message_handler ||
426 severity >= kAlwaysPrintErrorLevel;
427}
428
[email protected]162ac0f2010-11-04 15:50:49429int GetVlogVerbosity() {
430 return std::max(-1, LOG_INFO - GetMinLogLevel());
431}
432
[email protected]99b7c57f2010-09-29 19:26:36433int GetVlogLevelHelper(const char* file, size_t N) {
434 DCHECK_GT(N, 0U);
thestig3e4787d2015-05-19 19:31:52435 // Note: |g_vlog_info| may change on a different thread during startup
436 // (but will always be valid or nullptr).
[email protected]064aa162011-12-03 00:30:08437 VlogInfo* vlog_info = g_vlog_info;
438 return vlog_info ?
439 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
[email protected]162ac0f2010-11-04 15:50:49440 GetVlogVerbosity();
[email protected]99b7c57f2010-09-29 19:26:36441}
442
initial.commitd7cae122008-07-26 21:49:38443void SetLogItems(bool enable_process_id, bool enable_thread_id,
444 bool enable_timestamp, bool enable_tickcount) {
thestig3e4787d2015-05-19 19:31:52445 g_log_process_id = enable_process_id;
446 g_log_thread_id = enable_thread_id;
447 g_log_timestamp = enable_timestamp;
448 g_log_tickcount = enable_tickcount;
initial.commitd7cae122008-07-26 21:49:38449}
450
[email protected]81e0a852010-08-17 00:38:12451void SetShowErrorDialogs(bool enable_dialogs) {
452 show_error_dialogs = enable_dialogs;
453}
454
alex-accc1bde62017-04-19 08:33:55455ScopedLogAssertHandler::ScopedLogAssertHandler(
456 LogAssertHandlerFunction handler) {
457 log_assert_handler_stack.Get().push(std::move(handler));
458}
459
460ScopedLogAssertHandler::~ScopedLogAssertHandler() {
461 log_assert_handler_stack.Get().pop();
initial.commitd7cae122008-07-26 21:49:38462}
463
[email protected]2b07b8412009-11-25 15:26:34464void SetLogMessageHandler(LogMessageHandlerFunction handler) {
465 log_message_handler = handler;
466}
467
[email protected]64e5cc02010-11-03 19:20:27468LogMessageHandlerFunction GetLogMessageHandler() {
469 return log_message_handler;
470}
471
[email protected]6d445d32010-09-30 19:10:03472// Explicit instantiations for commonly used comparisons.
473template std::string* MakeCheckOpString<int, int>(
474 const int&, const int&, const char* names);
475template std::string* MakeCheckOpString<unsigned long, unsigned long>(
476 const unsigned long&, const unsigned long&, const char* names);
477template std::string* MakeCheckOpString<unsigned long, unsigned int>(
478 const unsigned long&, const unsigned int&, const char* names);
479template std::string* MakeCheckOpString<unsigned int, unsigned long>(
480 const unsigned int&, const unsigned long&, const char* names);
481template std::string* MakeCheckOpString<std::string, std::string>(
482 const std::string&, const std::string&, const char* name);
[email protected]2b07b8412009-11-25 15:26:34483
jbroman6bcfec422016-05-26 00:28:46484void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p) {
brucedawson93a60b8c2016-04-28 20:46:16485 (*os) << "nullptr";
486}
487
[email protected]f2c05492014-06-17 12:04:23488#if !defined(NDEBUG)
[email protected]d81baca42010-03-01 13:10:22489// Displays a message box to the user with the error message in it.
490// Used for fatal messages, where we close the app simultaneously.
[email protected]561513f2010-12-16 23:29:25491// This is for developers only; we don't use this in circumstances
492// (like release builds) where users could see it, since users don't
493// understand these messages anyway.
[email protected]d81baca42010-03-01 13:10:22494void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38495 if (str.empty())
496 return;
497
[email protected]81e0a852010-08-17 00:38:12498 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44499 return;
500
[email protected]f6abeba2008-08-08 13:27:28501#if defined(OS_WIN)
brettwe33526852015-10-03 00:46:01502 MessageBoxW(nullptr, base::UTF8ToUTF16(str).c_str(), L"Fatal error",
503 MB_OK | MB_ICONHAND | MB_TOPMOST);
[email protected]f6abeba2008-08-08 13:27:28504#else
[email protected]561513f2010-12-16 23:29:25505 // We intentionally don't implement a dialog on other platforms.
506 // You can just look at stderr.
thestig3e4787d2015-05-19 19:31:52507#endif // defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38508}
[email protected]f2c05492014-06-17 12:04:23509#endif // !defined(NDEBUG)
initial.commitd7cae122008-07-26 21:49:38510
[email protected]3f85caa2009-04-14 16:52:11511#if defined(OS_WIN)
512LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
513}
514
515LogMessage::SaveLastError::~SaveLastError() {
516 ::SetLastError(last_error_);
517}
518#endif // defined(OS_WIN)
519
[email protected]eae9c062011-01-11 00:50:59520LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
521 : severity_(severity), file_(file), line_(line) {
522 Init(file, line);
523}
524
tnagel4a045d3f2015-07-12 14:19:28525LogMessage::LogMessage(const char* file, int line, const char* condition)
526 : severity_(LOG_FATAL), file_(file), line_(line) {
527 Init(file, line);
528 stream_ << "Check failed: " << condition << ". ";
529}
530
[email protected]9c7132e2011-02-08 07:39:08531LogMessage::LogMessage(const char* file, int line, std::string* result)
[email protected]162ac0f2010-11-04 15:50:49532 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commitd7cae122008-07-26 21:49:38533 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08534 stream_ << "Check failed: " << *result;
535 delete result;
initial.commitd7cae122008-07-26 21:49:38536}
537
[email protected]fb62a532009-02-12 01:19:05538LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
[email protected]9c7132e2011-02-08 07:39:08539 std::string* result)
[email protected]162ac0f2010-11-04 15:50:49540 : severity_(severity), file_(file), line_(line) {
[email protected]fb62a532009-02-12 01:19:05541 Init(file, line);
[email protected]9c7132e2011-02-08 07:39:08542 stream_ << "Check failed: " << *result;
543 delete result;
[email protected]fb62a532009-02-12 01:19:05544}
545
initial.commitd7cae122008-07-26 21:49:38546LogMessage::~LogMessage() {
alex-accc1bde62017-04-19 08:33:55547 size_t stack_start = stream_.tellp();
jam79dc59a2015-08-17 03:38:16548#if !defined(OFFICIAL_BUILD) && !defined(OS_NACL) && !defined(__UCLIBC__)
brucedawson7c559eb2015-09-05 00:34:42549 if (severity_ == LOG_FATAL && !base::debug::BeingDebugged()) {
550 // Include a stack trace on a fatal, unless a debugger is attached.
[email protected]58580352010-10-26 04:07:50551 base::debug::StackTrace trace;
[email protected]d1ccc35a2010-03-24 05:03:24552 stream_ << std::endl; // Newline to separate from log message.
553 trace.OutputToStream(&stream_);
554 }
[email protected]1d8c2702008-08-19 23:39:32555#endif
[email protected]d1ccc35a2010-03-24 05:03:24556 stream_ << std::endl;
557 std::string str_newline(stream_.str());
558
[email protected]2b07b8412009-11-25 15:26:34559 // Give any log message handler first dibs on the message.
[email protected]5e3f7c22013-06-21 21:15:33560 if (log_message_handler &&
561 log_message_handler(severity_, file_, line_,
562 message_start_, str_newline)) {
[email protected]162ac0f2010-11-04 15:50:49563 // The handler took care of it, no further processing.
[email protected]2b07b8412009-11-25 15:26:34564 return;
[email protected]162ac0f2010-11-04 15:50:49565 }
initial.commitd7cae122008-07-26 21:49:38566
thestig3e4787d2015-05-19 19:31:52567 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
[email protected]f6abeba2008-08-08 13:27:28568#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38569 OutputDebugStringA(str_newline.c_str());
mark4c7449c2015-11-10 19:53:42570#elif defined(OS_MACOSX)
571 // In LOG_TO_SYSTEM_DEBUG_LOG mode, log messages are always written to
572 // stderr. If stderr is /dev/null, also log via ASL (Apple System Log). If
573 // there's something weird about stderr, assume that log messages are going
574 // nowhere and log via ASL too. Messages logged via ASL show up in
575 // Console.app.
576 //
577 // Programs started by launchd, as UI applications normally are, have had
578 // stderr connected to /dev/null since OS X 10.8. Prior to that, stderr was
579 // a pipe to launchd, which logged what it received (see log_redirect_fd in
580 // 10.7.5 launchd-392.39/launchd/src/launchd_core_logic.c).
581 //
582 // Another alternative would be to determine whether stderr is a pipe to
583 // launchd and avoid logging via ASL only in that case. See 10.7.5
584 // CF-635.21/CFUtilities.c also_do_stderr(). This would result in logging to
585 // both stderr and ASL even in tests, where it's undesirable to log to the
586 // system log at all.
587 //
588 // Note that the ASL client by default discards messages whose levels are
589 // below ASL_LEVEL_NOTICE. It's possible to change that with
590 // asl_set_filter(), but this is pointless because syslogd normally applies
591 // the same filter.
592 const bool log_via_asl = []() {
593 struct stat stderr_stat;
594 if (fstat(fileno(stderr), &stderr_stat) == -1) {
595 return true;
596 }
597 if (!S_ISCHR(stderr_stat.st_mode)) {
598 return false;
599 }
600
601 struct stat dev_null_stat;
602 if (stat(_PATH_DEVNULL, &dev_null_stat) == -1) {
603 return true;
604 }
605
606 return !S_ISCHR(dev_null_stat.st_mode) ||
607 stderr_stat.st_rdev == dev_null_stat.st_rdev;
608 }();
609
610 if (log_via_asl) {
611 // Log roughly the same way that CFLog() and NSLog() would. See 10.10.5
612 // CF-1153.18/CFUtilities.c __CFLogCString().
613 //
614 // The ASL facility is set to the main bundle ID if available. Otherwise,
615 // "com.apple.console" is used.
616 CFBundleRef main_bundle = CFBundleGetMainBundle();
617 CFStringRef main_bundle_id_cf =
618 main_bundle ? CFBundleGetIdentifier(main_bundle) : nullptr;
619 std::string asl_facility =
620 main_bundle_id_cf ? base::SysCFStringRefToUTF8(main_bundle_id_cf)
621 : std::string("com.apple.console");
622
623 class ASLClient {
624 public:
625 explicit ASLClient(const std::string& asl_facility)
626 : client_(asl_open(nullptr,
627 asl_facility.c_str(),
628 ASL_OPT_NO_DELAY)) {}
629 ~ASLClient() { asl_close(client_); }
630
631 aslclient get() const { return client_; }
632
633 private:
634 aslclient client_;
635 DISALLOW_COPY_AND_ASSIGN(ASLClient);
636 } asl_client(asl_facility);
637
638 class ASLMessage {
639 public:
640 ASLMessage() : message_(asl_new(ASL_TYPE_MSG)) {}
641 ~ASLMessage() { asl_free(message_); }
642
643 aslmsg get() const { return message_; }
644
645 private:
646 aslmsg message_;
647 DISALLOW_COPY_AND_ASSIGN(ASLMessage);
648 } asl_message;
649
650 // By default, messages are only readable by the admin group. Explicitly
651 // make them readable by the user generating the messages.
652 char euid_string[12];
653 snprintf(euid_string, arraysize(euid_string), "%d", geteuid());
654 asl_set(asl_message.get(), ASL_KEY_READ_UID, euid_string);
655
656 // Map Chrome log severities to ASL log levels.
657 const char* const asl_level_string = [](LogSeverity severity) {
658 // ASL_LEVEL_* are ints, but ASL needs equivalent strings. This
659 // non-obvious two-step macro trick achieves what's needed.
660 // https://gcc.gnu.org/onlinedocs/cpp/Stringification.html
661#define ASL_LEVEL_STR(level) ASL_LEVEL_STR_X(level)
662#define ASL_LEVEL_STR_X(level) #level
663 switch (severity) {
664 case LOG_INFO:
665 return ASL_LEVEL_STR(ASL_LEVEL_INFO);
666 case LOG_WARNING:
667 return ASL_LEVEL_STR(ASL_LEVEL_WARNING);
668 case LOG_ERROR:
669 return ASL_LEVEL_STR(ASL_LEVEL_ERR);
670 case LOG_FATAL:
671 return ASL_LEVEL_STR(ASL_LEVEL_CRIT);
672 default:
673 return severity < 0 ? ASL_LEVEL_STR(ASL_LEVEL_DEBUG)
674 : ASL_LEVEL_STR(ASL_LEVEL_NOTICE);
675 }
676#undef ASL_LEVEL_STR
677#undef ASL_LEVEL_STR_X
678 }(severity_);
679 asl_set(asl_message.get(), ASL_KEY_LEVEL, asl_level_string);
680
681 asl_set(asl_message.get(), ASL_KEY_MSG, str_newline.c_str());
682
683 asl_send(asl_client.get(), asl_message.get());
684 }
[email protected]3132e35c2011-07-07 20:46:50685#elif defined(OS_ANDROID)
[email protected]efbae7da2013-05-21 22:39:25686 android_LogPriority priority =
687 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
[email protected]3132e35c2011-07-07 20:46:50688 switch (severity_) {
689 case LOG_INFO:
690 priority = ANDROID_LOG_INFO;
691 break;
692 case LOG_WARNING:
693 priority = ANDROID_LOG_WARN;
694 break;
695 case LOG_ERROR:
[email protected]3132e35c2011-07-07 20:46:50696 priority = ANDROID_LOG_ERROR;
697 break;
698 case LOG_FATAL:
699 priority = ANDROID_LOG_FATAL;
700 break;
701 }
702 __android_log_write(priority, "chromium", str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18703#endif
[email protected]51105382014-03-14 17:02:15704 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]469006c2010-09-24 15:43:06705 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31706 } else if (severity_ >= kAlwaysPrintErrorLevel) {
707 // When we're only outputting to a log file, above a certain log level, we
708 // should still output to stderr so that we can better detect and diagnose
709 // problems with unit tests, especially on the buildbots.
[email protected]51105382014-03-14 17:02:15710 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
[email protected]1ce41052009-12-02 00:34:02711 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28712 }
[email protected]52a261f2009-03-03 15:01:12713
initial.commitd7cae122008-07-26 21:49:38714 // write to log file
thestig3e4787d2015-05-19 19:31:52715 if ((g_logging_destination & LOG_TO_FILE) != 0) {
[email protected]17dcf752013-07-15 21:47:09716 // We can have multiple threads and/or processes, so try to prevent them
717 // from clobbering each other's writes.
718 // If the client app did not call InitLogging, and the lock has not
719 // been created do it now. We do this on demand, but if two threads try
720 // to do this at the same time, there will be a race condition to create
721 // the lock. This is why InitLogging should be called from the main
722 // thread at the beginning of execution.
ananta61762fb2015-09-18 01:00:09723#if !defined(OS_WIN)
thestig3e4787d2015-05-19 19:31:52724 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
[email protected]5b84fe32010-09-14 22:24:55725 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09726#endif
[email protected]5b84fe32010-09-14 22:24:55727 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28728#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55729 DWORD num_written;
thestig3e4787d2015-05-19 19:31:52730 WriteFile(g_log_file,
[email protected]5b84fe32010-09-14 22:24:55731 static_cast<const void*>(str_newline.c_str()),
732 static_cast<DWORD>(str_newline.length()),
733 &num_written,
thestig3e4787d2015-05-19 19:31:52734 nullptr);
[email protected]cba21962010-08-31 22:35:55735#else
[email protected]51105382014-03-14 17:02:15736 ignore_result(fwrite(
thestig3e4787d2015-05-19 19:31:52737 str_newline.data(), str_newline.size(), 1, g_log_file));
738 fflush(g_log_file);
[email protected]cba21962010-08-31 22:35:55739#endif
initial.commitd7cae122008-07-26 21:49:38740 }
741 }
742
743 if (severity_ == LOG_FATAL) {
bcwhite7a30eb42016-12-02 21:23:40744 // Write the log message to the global activity tracker, if running.
745 base::debug::GlobalActivityTracker* tracker =
746 base::debug::GlobalActivityTracker::Get();
747 if (tracker)
748 tracker->RecordLogMessage(str_newline);
749
[email protected]eb4c4d032012-04-03 18:45:05750 // Ensure the first characters of the string are on the stack so they
751 // are contained in minidumps for diagnostic purposes.
752 char str_stack[1024];
753 str_newline.copy(str_stack, arraysize(str_stack));
754 base::debug::Alias(str_stack);
755
alex-accc1bde62017-04-19 08:33:55756 if (!(log_assert_handler_stack == nullptr) &&
757 !log_assert_handler_stack.Get().empty()) {
758 LogAssertHandlerFunction log_assert_handler =
759 log_assert_handler_stack.Get().top();
760
761 if (log_assert_handler) {
762 log_assert_handler.Run(
763 file_, line_,
764 base::StringPiece(str_newline.c_str() + message_start_,
765 stack_start - message_start_),
766 base::StringPiece(str_newline.c_str() + stack_start));
767 }
[email protected]1ffe08c12008-08-13 11:15:11768 } else {
[email protected]82d89ab2014-02-28 18:25:34769 // Don't use the string with the newline, get a fresh version to send to
770 // the debug message process. We also don't display assertions to the
771 // user in release mode. The enduser can't do anything with this
772 // information, and displaying message boxes when the application is
773 // hosed can cause additional problems.
[email protected]4d5901272008-11-06 00:33:50774#ifndef NDEBUG
brucedawson7c559eb2015-09-05 00:34:42775 if (!base::debug::BeingDebugged()) {
776 // Displaying a dialog is unnecessary when debugging and can complicate
777 // debugging.
778 DisplayDebugMessageInDialog(stream_.str());
779 }
[email protected]4d5901272008-11-06 00:33:50780#endif
[email protected]82d89ab2014-02-28 18:25:34781 // Crash the process to generate a dump.
782 base::debug::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38783 }
784 }
785}
786
[email protected]eae9c062011-01-11 00:50:59787// writes the common header info to the stream
788void LogMessage::Init(const char* file, int line) {
789 base::StringPiece filename(file);
790 size_t last_slash_pos = filename.find_last_of("\\/");
791 if (last_slash_pos != base::StringPiece::npos)
792 filename.remove_prefix(last_slash_pos + 1);
793
794 // TODO(darin): It might be nice if the columns were fixed width.
795
796 stream_ << '[';
thestig3e4787d2015-05-19 19:31:52797 if (g_log_process_id)
[email protected]eae9c062011-01-11 00:50:59798 stream_ << CurrentProcessId() << ':';
thestig3e4787d2015-05-19 19:31:52799 if (g_log_thread_id)
[email protected]63e66802012-01-18 21:21:09800 stream_ << base::PlatformThread::CurrentId() << ':';
thestig3e4787d2015-05-19 19:31:52801 if (g_log_timestamp) {
djkurtz543a3be2016-11-30 14:17:34802#if defined(OS_POSIX)
803 timeval tv;
804 gettimeofday(&tv, nullptr);
805 time_t t = tv.tv_sec;
806 struct tm local_time;
[email protected]eae9c062011-01-11 00:50:59807 localtime_r(&t, &local_time);
[email protected]eae9c062011-01-11 00:50:59808 struct tm* tm_time = &local_time;
809 stream_ << std::setfill('0')
810 << std::setw(2) << 1 + tm_time->tm_mon
811 << std::setw(2) << tm_time->tm_mday
812 << '/'
813 << std::setw(2) << tm_time->tm_hour
814 << std::setw(2) << tm_time->tm_min
815 << std::setw(2) << tm_time->tm_sec
djkurtz543a3be2016-11-30 14:17:34816 << '.'
817 << std::setw(6) << tv.tv_usec
[email protected]eae9c062011-01-11 00:50:59818 << ':';
djkurtz543a3be2016-11-30 14:17:34819#elif defined(OS_WIN)
820 SYSTEMTIME local_time;
821 GetLocalTime(&local_time);
822 stream_ << std::setfill('0')
823 << std::setw(2) << local_time.wMonth
824 << std::setw(2) << local_time.wDay
825 << '/'
826 << std::setw(2) << local_time.wHour
827 << std::setw(2) << local_time.wMinute
828 << std::setw(2) << local_time.wSecond
829 << '.'
830 << std::setw(3) << local_time.wMilliseconds
831 << ':';
832#endif
[email protected]eae9c062011-01-11 00:50:59833 }
thestig3e4787d2015-05-19 19:31:52834 if (g_log_tickcount)
[email protected]eae9c062011-01-11 00:50:59835 stream_ << TickCount() << ':';
836 if (severity_ >= 0)
[email protected]80f360a2014-01-23 01:36:19837 stream_ << log_severity_name(severity_);
[email protected]eae9c062011-01-11 00:50:59838 else
839 stream_ << "VERBOSE" << -severity_;
840
841 stream_ << ":" << filename << "(" << line << ")] ";
842
pkasting9cf9b94a2014-10-01 22:18:43843 message_start_ = stream_.str().length();
[email protected]eae9c062011-01-11 00:50:59844}
845
[email protected]d8617a62009-10-09 23:52:20846#if defined(OS_WIN)
847// This has already been defined in the header, but defining it again as DWORD
848// ensures that the type used in the header is equivalent to DWORD. If not,
849// the redefinition is a compile error.
850typedef DWORD SystemErrorCode;
851#endif
852
853SystemErrorCode GetLastSystemErrorCode() {
854#if defined(OS_WIN)
855 return ::GetLastError();
856#elif defined(OS_POSIX)
857 return errno;
858#else
859#error Not implemented
860#endif
861}
862
863#if defined(OS_WIN)
[email protected]c914d8a2014-04-23 01:11:01864BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
thestig75f87352014-12-03 21:42:27865 const int kErrorMessageBufferSize = 256;
866 char msgbuf[kErrorMessageBufferSize];
[email protected]c914d8a2014-04-23 01:11:01867 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
thestig3e4787d2015-05-19 19:31:52868 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
869 arraysize(msgbuf), nullptr);
[email protected]c914d8a2014-04-23 01:11:01870 if (len) {
871 // Messages returned by system end with line breaks.
872 return base::CollapseWhitespaceASCII(msgbuf, true) +
873 base::StringPrintf(" (0x%X)", error_code);
874 }
875 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
876 GetLastError(), error_code);
[email protected]d8617a62009-10-09 23:52:20877}
[email protected]c914d8a2014-04-23 01:11:01878#elif defined(OS_POSIX)
879BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
brettw6ee6fd62015-06-09 18:05:24880 return base::safe_strerror(error_code);
[email protected]c914d8a2014-04-23 01:11:01881}
882#else
883#error Not implemented
thestig3e4787d2015-05-19 19:31:52884#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20885
[email protected]c914d8a2014-04-23 01:11:01886
887#if defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20888Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
889 int line,
890 LogSeverity severity,
891 SystemErrorCode err)
892 : err_(err),
[email protected]d8617a62009-10-09 23:52:20893 log_message_(file, line, severity) {
894}
895
896Win32ErrorLogMessage::~Win32ErrorLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01897 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]20909e72012-04-05 16:57:06898 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
899 // field) and use Alias in hopes that it makes it into crash dumps.
900 DWORD last_error = err_;
901 base::debug::Alias(&last_error);
[email protected]d8617a62009-10-09 23:52:20902}
903#elif defined(OS_POSIX)
904ErrnoLogMessage::ErrnoLogMessage(const char* file,
905 int line,
906 LogSeverity severity,
907 SystemErrorCode err)
908 : err_(err),
909 log_message_(file, line, severity) {
910}
911
912ErrnoLogMessage::~ErrnoLogMessage() {
[email protected]c914d8a2014-04-23 01:11:01913 stream() << ": " << SystemErrorCodeToString(err_);
[email protected]d8617a62009-10-09 23:52:20914}
thestig3e4787d2015-05-19 19:31:52915#endif // defined(OS_WIN)
[email protected]d8617a62009-10-09 23:52:20916
initial.commitd7cae122008-07-26 21:49:38917void CloseLogFile() {
ananta61762fb2015-09-18 01:00:09918#if !defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55919 LoggingLock logging_lock;
ananta61762fb2015-09-18 01:00:09920#endif
[email protected]17dcf752013-07-15 21:47:09921 CloseLogFileUnlocked();
initial.commitd7cae122008-07-26 21:49:38922}
923
[email protected]e36ddc82009-12-08 04:22:50924void RawLog(int level, const char* message) {
erikchen0c9fe712016-03-11 22:07:49925 if (level >= g_min_log_level && message) {
[email protected]e36ddc82009-12-08 04:22:50926 size_t bytes_written = 0;
927 const size_t message_len = strlen(message);
928 int rv;
929 while (bytes_written < message_len) {
930 rv = HANDLE_EINTR(
931 write(STDERR_FILENO, message + bytes_written,
932 message_len - bytes_written));
933 if (rv < 0) {
934 // Give up, nothing we can do now.
935 break;
936 }
937 bytes_written += rv;
938 }
939
940 if (message_len > 0 && message[message_len - 1] != '\n') {
941 do {
942 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
943 if (rv < 0) {
944 // Give up, nothing we can do now.
945 break;
946 }
947 } while (rv != 1);
948 }
949 }
950
951 if (level == LOG_FATAL)
[email protected]58580352010-10-26 04:07:50952 base::debug::BreakDebugger();
[email protected]e36ddc82009-12-08 04:22:50953}
954
[email protected]34a907732012-01-20 06:33:27955// This was defined at the beginning of this file.
956#undef write
957
[email protected]f01b88a2013-02-27 22:04:00958#if defined(OS_WIN)
ananta61762fb2015-09-18 01:00:09959bool IsLoggingToFileEnabled() {
960 return g_logging_destination & LOG_TO_FILE;
961}
962
[email protected]f01b88a2013-02-27 22:04:00963std::wstring GetLogFileFullPath() {
thestig3e4787d2015-05-19 19:31:52964 if (g_log_file_name)
965 return *g_log_file_name;
[email protected]f01b88a2013-02-27 22:04:00966 return std::wstring();
967}
968#endif
969
tnagel80388e682015-05-26 13:27:56970BASE_EXPORT void LogErrorNotReached(const char* file, int line) {
tnagelff3f34a2015-05-24 12:59:14971 LogMessage(file, line, LOG_ERROR).stream()
972 << "NOTREACHED() hit.";
973}
974
[email protected]96fd0032009-04-24 00:13:08975} // namespace logging
initial.commitd7cae122008-07-26 21:49:38976
[email protected]81411c62014-07-08 23:03:06977std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
erikchen0c9fe712016-03-11 22:07:49978 return out << (wstr ? base::WideToUTF8(wstr) : std::string());
initial.commitd7cae122008-07-26 21:49:38979}