blob: 8f75aa07057e8488abc058d33a195a972babfdfc [file] [log] [blame]
rsesek@chromium.org4fd393b2012-01-19 06:21:09 +09001// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botf003cfe2008-08-24 09:55:55 +09002// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit3f4a7322008-07-27 06:49:38 +09004
darin@google.com12d40bb2008-08-20 03:36:23 +09005#include "base/logging.h"
pinkerton@google.com56053fe2008-08-08 22:27:28 +09006
darin@google.com12d40bb2008-08-20 03:36:23 +09007#if defined(OS_WIN)
willchan@chromium.org85113a12009-12-08 13:22:50 +09008#include <io.h>
pinkerton@google.com56053fe2008-08-08 22:27:28 +09009#include <windows.h>
10typedef HANDLE FileHandle;
11typedef HANDLE MutexHandle;
willchan@chromium.org85113a12009-12-08 13:22:50 +090012// Windows warns on using write(). It prefers _write().
13#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
14// Windows doesn't define STDERR_FILENO. Define it here.
15#define STDERR_FILENO 2
estade@chromium.orgf7855502008-11-07 06:43:07 +090016#elif defined(OS_MACOSX)
pinkerton@google.com56053fe2008-08-08 22:27:28 +090017#include <mach/mach.h>
18#include <mach/mach_time.h>
19#include <mach-o/dyld.h>
evan@chromium.org875bb6e2009-12-29 09:32:52 +090020#elif defined(OS_POSIX)
abarth@chromium.orge7162862010-11-12 17:37:08 +090021#if defined(OS_NACL)
abarth@chromium.orge7162862010-11-12 17:37:08 +090022#include <sys/time.h> // timespec doesn't seem to be in <time.h>
23#else
estade@chromium.orgf7855502008-11-07 06:43:07 +090024#include <sys/syscall.h>
abarth@chromium.orge7162862010-11-12 17:37:08 +090025#endif
estade@chromium.orgf7855502008-11-07 06:43:07 +090026#include <time.h>
evanm@google.com4487dd72008-08-12 07:52:59 +090027#endif
28
29#if defined(OS_POSIX)
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +090030#include <errno.h>
bulach@chromium.org6d1153e2010-08-06 00:50:23 +090031#include <pthread.h>
pinkerton@google.com56053fe2008-08-08 22:27:28 +090032#include <stdio.h>
tfarina@chromium.orgb6d49112013-03-30 23:29:00 +090033#include <stdlib.h>
pinkerton@google.com56053fe2008-08-08 22:27:28 +090034#include <string.h>
35#include <unistd.h>
36#define MAX_PATH PATH_MAX
37typedef FILE* FileHandle;
38typedef pthread_mutex_t* MutexHandle;
39#endif
40
rvargas@google.comfa62cd22011-04-01 09:02:29 +090041#include <algorithm>
42#include <cstring>
initial.commit3f4a7322008-07-27 06:49:38 +090043#include <ctime>
44#include <iomanip>
rvargas@google.comfa62cd22011-04-01 09:02:29 +090045#include <ostream>
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +090046#include <string>
darin@google.com12d40bb2008-08-20 03:36:23 +090047
initial.commit3f4a7322008-07-27 06:49:38 +090048#include "base/base_switches.h"
49#include "base/command_line.h"
apatrick@chromium.org35e38992012-04-04 03:45:05 +090050#include "base/debug/alias.h"
brettw@chromium.org2f49b122010-10-26 13:07:50 +090051#include "base/debug/debugger.h"
52#include "base/debug/stack_trace.h"
brettw@chromium.orgb1788fb2012-11-15 05:54:35 +090053#include "base/posix/eintr_wrapper.h"
tfarina@chromium.orgb6d49112013-03-30 23:29:00 +090054#include "base/strings/string_piece.h"
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +090055#include "base/strings/string_util.h"
56#include "base/strings/stringprintf.h"
avi@chromium.org17f60622013-06-08 03:37:07 +090057#include "base/strings/utf_string_conversions.h"
brettw@chromium.orge439a962011-01-02 08:16:20 +090058#include "base/synchronization/lock_impl.h"
rsesek@chromium.org4fd393b2012-01-19 06:21:09 +090059#include "base/threading/platform_thread.h"
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +090060#include "base/vlog.h"
dmaclach@chromium.org3cae3402010-12-15 01:20:04 +090061#if defined(OS_POSIX)
62#include "base/safe_strerror_posix.h"
63#endif
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +090064
michaelbai@google.com01ef2f22011-07-08 05:46:50 +090065#if defined(OS_ANDROID)
66#include <android/log.h>
67#endif
68
initial.commit3f4a7322008-07-27 06:49:38 +090069namespace logging {
70
stevenjb@chromium.org6c56fa42011-12-03 09:30:08 +090071namespace {
72
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +090073VlogInfo* g_vlog_info = NULL;
stevenjb@chromium.org6c56fa42011-12-03 09:30:08 +090074VlogInfo* g_vlog_info_prev = NULL;
initial.commit3f4a7322008-07-27 06:49:38 +090075
76const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
viettrungluu@chromium.org96925ac2014-06-17 21:04:23 +090077 "INFO", "WARNING", "ERROR", "FATAL" };
initial.commit3f4a7322008-07-27 06:49:38 +090078
tsepez@chromium.orgeef2c1c2014-01-23 10:36:19 +090079const char* log_severity_name(int severity)
80{
81 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
82 return log_severity_names[severity];
83 return "UNKNOWN";
84}
85
initial.commit3f4a7322008-07-27 06:49:38 +090086int min_log_level = 0;
mmentovai@google.comf0944f32008-08-20 08:39:32 +090087
akalin@chromium.org6d987202013-06-22 06:15:33 +090088LoggingDestination logging_destination = LOG_DEFAULT;
initial.commit3f4a7322008-07-27 06:49:38 +090089
erikkay@google.coma1ca46c2008-08-26 05:10:31 +090090// For LOG_ERROR and above, always print to stderr.
91const int kAlwaysPrintErrorLevel = LOG_ERROR;
92
evanm@google.com4487dd72008-08-12 07:52:59 +090093// Which log file to use? This is initialized by InitLogging or
initial.commit3f4a7322008-07-27 06:49:38 +090094// will be lazily initialized to the default value when it is
95// first needed.
pinkerton@google.com56053fe2008-08-08 22:27:28 +090096#if defined(OS_WIN)
evanm@google.com4487dd72008-08-12 07:52:59 +090097typedef std::wstring PathString;
pinkerton@google.com56053fe2008-08-08 22:27:28 +090098#else
evanm@google.com4487dd72008-08-12 07:52:59 +090099typedef std::string PathString;
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900100#endif
evanm@google.com4487dd72008-08-12 07:52:59 +0900101PathString* log_file_name = NULL;
initial.commit3f4a7322008-07-27 06:49:38 +0900102
103// this file is lazily opened and the handle may be NULL
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900104FileHandle log_file = NULL;
initial.commit3f4a7322008-07-27 06:49:38 +0900105
106// what should be prepended to each message?
107bool log_process_id = false;
108bool log_thread_id = false;
109bool log_timestamp = true;
110bool log_tickcount = false;
111
cmasone@google.comf7802482010-08-17 09:38:12 +0900112// Should we pop up fatal debug messages in a dialog?
113bool show_error_dialogs = false;
114
initial.commit3f4a7322008-07-27 06:49:38 +0900115// An assert handler override specified by the client to be called instead of
huanr@chromium.org656253e2009-02-12 10:19:05 +0900116// the debug message dialog and process termination.
initial.commit3f4a7322008-07-27 06:49:38 +0900117LogAssertHandlerFunction log_assert_handler = NULL;
siggi@chromium.org4db65792009-11-26 00:26:34 +0900118// A log message handler that gets notified of every log message we process.
119LogMessageHandlerFunction log_message_handler = NULL;
initial.commit3f4a7322008-07-27 06:49:38 +0900120
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900121// Helper functions to wrap platform differences.
122
estade@chromium.org1160a8b2008-11-06 08:17:24 +0900123int32 CurrentProcessId() {
124#if defined(OS_WIN)
125 return GetCurrentProcessId();
126#elif defined(OS_POSIX)
127 return getpid();
128#endif
129}
130
estade@chromium.org1160a8b2008-11-06 08:17:24 +0900131uint64 TickCount() {
132#if defined(OS_WIN)
133 return GetTickCount();
134#elif defined(OS_MACOSX)
135 return mach_absolute_time();
abarth@chromium.orge7162862010-11-12 17:37:08 +0900136#elif defined(OS_NACL)
137 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
138 // So we have to use clock() for now.
139 return clock();
evan@chromium.org875bb6e2009-12-29 09:32:52 +0900140#elif defined(OS_POSIX)
estade@chromium.orgf7855502008-11-07 06:43:07 +0900141 struct timespec ts;
142 clock_gettime(CLOCK_MONOTONIC, &ts);
143
144 uint64 absolute_micro =
145 static_cast<int64>(ts.tv_sec) * 1000000 +
146 static_cast<int64>(ts.tv_nsec) / 1000;
147
148 return absolute_micro;
estade@chromium.org1160a8b2008-11-06 08:17:24 +0900149#endif
150}
151
evanm@google.com4487dd72008-08-12 07:52:59 +0900152void DeleteFilePath(const PathString& log_name) {
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900153#if defined(OS_WIN)
evanm@google.com4487dd72008-08-12 07:52:59 +0900154 DeleteFile(log_name.c_str());
teravest@chromium.orge72bc482013-04-23 02:32:45 +0900155#elif defined (OS_NACL)
156 // Do nothing; unlink() isn't supported on NaCl.
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900157#else
evanm@google.com4487dd72008-08-12 07:52:59 +0900158 unlink(log_name.c_str());
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900159#endif
160}
initial.commit3f4a7322008-07-27 06:49:38 +0900161
hansl@google.com6a29af52010-10-02 02:16:58 +0900162PathString GetDefaultLogFile() {
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900163#if defined(OS_WIN)
164 // On Windows we use the same path as the exe.
165 wchar_t module_name[MAX_PATH];
166 GetModuleFileName(NULL, module_name, MAX_PATH);
hansl@google.com6a29af52010-10-02 02:16:58 +0900167
168 PathString log_file = module_name;
169 PathString::size_type last_backslash =
170 log_file.rfind('\\', log_file.size());
171 if (last_backslash != PathString::npos)
172 log_file.erase(last_backslash + 1);
173 log_file += L"debug.log";
174 return log_file;
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900175#elif defined(OS_POSIX)
176 // On other platforms we just use the current directory.
hansl@google.com6a29af52010-10-02 02:16:58 +0900177 return PathString("debug.log");
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900178#endif
179}
180
181// This class acts as a wrapper for locking the logging files.
182// LoggingLock::Init() should be called from the main thread before any logging
183// is done. Then whenever logging, be sure to have a local LoggingLock
184// instance on the stack. This will ensure that the lock is unlocked upon
185// exiting the frame.
186// LoggingLocks can not be nested.
187class LoggingLock {
188 public:
189 LoggingLock() {
190 LockLogging();
191 }
192
193 ~LoggingLock() {
194 UnlockLogging();
195 }
196
197 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
198 if (initialized)
199 return;
200 lock_log_file = lock_log;
201 if (lock_log_file == LOCK_LOG_FILE) {
202#if defined(OS_WIN)
203 if (!log_mutex) {
204 std::wstring safe_name;
205 if (new_log_file)
206 safe_name = new_log_file;
207 else
hansl@google.com6a29af52010-10-02 02:16:58 +0900208 safe_name = GetDefaultLogFile();
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900209 // \ is not a legal character in mutex names so we replace \ with /
210 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
211 std::wstring t(L"Global\\");
212 t.append(safe_name);
213 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
hansl@google.com6a29af52010-10-02 02:16:58 +0900214
215 if (log_mutex == NULL) {
216#if DEBUG
217 // Keep the error code for debugging
218 int error = GetLastError(); // NOLINT
brettw@chromium.org2f49b122010-10-26 13:07:50 +0900219 base::debug::BreakDebugger();
hansl@google.com6a29af52010-10-02 02:16:58 +0900220#endif
221 // Return nicely without putting initialized to true.
222 return;
223 }
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900224 }
225#endif
226 } else {
brettw@chromium.orge439a962011-01-02 08:16:20 +0900227 log_lock = new base::internal::LockImpl();
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900228 }
229 initialized = true;
230 }
231
232 private:
233 static void LockLogging() {
234 if (lock_log_file == LOCK_LOG_FILE) {
235#if defined(OS_WIN)
236 ::WaitForSingleObject(log_mutex, INFINITE);
237 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
238 // abort the process here. UI tests might be crashy sometimes,
239 // and aborting the test binary only makes the problem worse.
240 // We also don't use LOG macros because that might lead to an infinite
241 // loop. For more info see http://crbug.com/18028.
242#elif defined(OS_POSIX)
243 pthread_mutex_lock(&log_mutex);
244#endif
245 } else {
246 // use the lock
247 log_lock->Lock();
248 }
249 }
250
251 static void UnlockLogging() {
252 if (lock_log_file == LOCK_LOG_FILE) {
253#if defined(OS_WIN)
254 ReleaseMutex(log_mutex);
255#elif defined(OS_POSIX)
256 pthread_mutex_unlock(&log_mutex);
257#endif
258 } else {
259 log_lock->Unlock();
260 }
261 }
262
263 // The lock is used if log file locking is false. It helps us avoid problems
264 // with multiple threads writing to the log file at the same time. Use
265 // LockImpl directly instead of using Lock, because Lock makes logging calls.
brettw@chromium.orge439a962011-01-02 08:16:20 +0900266 static base::internal::LockImpl* log_lock;
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900267
268 // When we don't use a lock, we are using a global mutex. We need to do this
269 // because LockFileEx is not thread safe.
270#if defined(OS_WIN)
271 static MutexHandle log_mutex;
272#elif defined(OS_POSIX)
273 static pthread_mutex_t log_mutex;
274#endif
275
276 static bool initialized;
277 static LogLockingState lock_log_file;
278};
279
280// static
281bool LoggingLock::initialized = false;
282// static
brettw@chromium.orge439a962011-01-02 08:16:20 +0900283base::internal::LockImpl* LoggingLock::log_lock = NULL;
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900284// static
285LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
286
287#if defined(OS_WIN)
288// static
289MutexHandle LoggingLock::log_mutex = NULL;
290#elif defined(OS_POSIX)
291pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
292#endif
293
initial.commit3f4a7322008-07-27 06:49:38 +0900294// Called by logging functions to ensure that debug_file is initialized
295// and can be used for writing. Returns false if the file could not be
296// initialized. debug_file will be NULL in this case.
297bool InitializeLogFileHandle() {
298 if (log_file)
299 return true;
300
evanm@google.com4487dd72008-08-12 07:52:59 +0900301 if (!log_file_name) {
302 // Nobody has called InitLogging to specify a debug log file, so here we
303 // initialize the log file name to a default.
hansl@google.com6a29af52010-10-02 02:16:58 +0900304 log_file_name = new PathString(GetDefaultLogFile());
initial.commit3f4a7322008-07-27 06:49:38 +0900305 }
306
akalin@chromium.org6d987202013-06-22 06:15:33 +0900307 if ((logging_destination & LOG_TO_FILE) != 0) {
evanm@google.com4487dd72008-08-12 07:52:59 +0900308#if defined(OS_WIN)
mmentovai@google.comf0944f32008-08-20 08:39:32 +0900309 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commit3f4a7322008-07-27 06:49:38 +0900310 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
311 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
312 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
mmentovai@google.comf0944f32008-08-20 08:39:32 +0900313 // try the current directory
314 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
315 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
316 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
317 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
318 log_file = NULL;
319 return false;
320 }
initial.commit3f4a7322008-07-27 06:49:38 +0900321 }
mmentovai@google.comf0944f32008-08-20 08:39:32 +0900322 SetFilePointer(log_file, 0, 0, FILE_END);
dkegel@google.com43c36742009-06-09 08:29:11 +0900323#elif defined(OS_POSIX)
324 log_file = fopen(log_file_name->c_str(), "a");
325 if (log_file == NULL)
326 return false;
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900327#endif
mmentovai@google.comf0944f32008-08-20 08:39:32 +0900328 }
329
initial.commit3f4a7322008-07-27 06:49:38 +0900330 return true;
331}
332
akalin@chromium.org2e983c52013-07-16 06:47:09 +0900333void CloseFile(FileHandle log) {
334#if defined(OS_WIN)
335 CloseHandle(log);
336#else
337 fclose(log);
338#endif
339}
340
341void CloseLogFileUnlocked() {
342 if (!log_file)
343 return;
344
345 CloseFile(log_file);
346 log_file = NULL;
347}
348
stevenjb@chromium.org6c56fa42011-12-03 09:30:08 +0900349} // namespace
350
akalin@chromium.org6d987202013-06-22 06:15:33 +0900351LoggingSettings::LoggingSettings()
352 : logging_dest(LOG_DEFAULT),
353 log_file(NULL),
354 lock_log(LOCK_LOG_FILE),
wangxianzhu@chromium.org75a5cd92014-03-11 03:23:38 +0900355 delete_old(APPEND_TO_OLD_LOG_FILE) {}
stevenjb@chromium.org6c56fa42011-12-03 09:30:08 +0900356
akalin@chromium.org6d987202013-06-22 06:15:33 +0900357bool BaseInitLoggingImpl(const LoggingSettings& settings) {
teravest@chromium.orge72bc482013-04-23 02:32:45 +0900358#if defined(OS_NACL)
akalin@chromium.org6d987202013-06-22 06:15:33 +0900359 // Can log only to the system debug log.
360 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
teravest@chromium.orge72bc482013-04-23 02:32:45 +0900361#endif
bbudge@chromium.orgd673b622012-02-29 06:35:44 +0900362 CommandLine* command_line = CommandLine::ForCurrentProcess();
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900363 // Don't bother initializing g_vlog_info unless we use one of the
364 // vlog switches.
365 if (command_line->HasSwitch(switches::kV) ||
366 command_line->HasSwitch(switches::kVModule)) {
stevenjb@chromium.org6c56fa42011-12-03 09:30:08 +0900367 // NOTE: If g_vlog_info has already been initialized, it might be in use
368 // by another thread. Don't delete the old VLogInfo, just create a second
369 // one. We keep track of both to avoid memory leak warnings.
370 CHECK(!g_vlog_info_prev);
371 g_vlog_info_prev = g_vlog_info;
372
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900373 g_vlog_info =
374 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
siggi@chromium.org25396e12010-11-05 00:50:49 +0900375 command_line->GetSwitchValueASCII(switches::kVModule),
376 &min_log_level);
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900377 }
378
akalin@chromium.org6d987202013-06-22 06:15:33 +0900379 logging_destination = settings.logging_dest;
initial.commit3f4a7322008-07-27 06:49:38 +0900380
akalin@chromium.org6d987202013-06-22 06:15:33 +0900381 // ignore file options unless logging to file is set.
382 if ((logging_destination & LOG_TO_FILE) == 0)
gspencer@chromium.org49c808a2010-10-28 09:20:21 +0900383 return true;
initial.commit3f4a7322008-07-27 06:49:38 +0900384
akalin@chromium.org2e983c52013-07-16 06:47:09 +0900385 LoggingLock::Init(settings.lock_log, settings.log_file);
386 LoggingLock logging_lock;
387
388 // Calling InitLogging twice or after some log call has already opened the
389 // default log file will re-initialize to the new options.
390 CloseLogFileUnlocked();
391
evanm@google.com4487dd72008-08-12 07:52:59 +0900392 if (!log_file_name)
393 log_file_name = new PathString();
akalin@chromium.org6d987202013-06-22 06:15:33 +0900394 *log_file_name = settings.log_file;
395 if (settings.delete_old == DELETE_OLD_LOG_FILE)
evanm@google.com4487dd72008-08-12 07:52:59 +0900396 DeleteFilePath(*log_file_name);
initial.commit3f4a7322008-07-27 06:49:38 +0900397
gspencer@chromium.org49c808a2010-10-28 09:20:21 +0900398 return InitializeLogFileHandle();
initial.commit3f4a7322008-07-27 06:49:38 +0900399}
400
401void SetMinLogLevel(int level) {
viettrungluu@chromium.org96925ac2014-06-17 21:04:23 +0900402 min_log_level = std::min(LOG_FATAL, level);
initial.commit3f4a7322008-07-27 06:49:38 +0900403}
404
405int GetMinLogLevel() {
406 return min_log_level;
407}
408
siggi@chromium.org25396e12010-11-05 00:50:49 +0900409int GetVlogVerbosity() {
410 return std::max(-1, LOG_INFO - GetMinLogLevel());
411}
412
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900413int GetVlogLevelHelper(const char* file, size_t N) {
414 DCHECK_GT(N, 0U);
stevenjb@chromium.org6c56fa42011-12-03 09:30:08 +0900415 // Note: g_vlog_info may change on a different thread during startup
416 // (but will always be valid or NULL).
417 VlogInfo* vlog_info = g_vlog_info;
418 return vlog_info ?
419 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
siggi@chromium.org25396e12010-11-05 00:50:49 +0900420 GetVlogVerbosity();
akalin@chromium.orgf0ee79c2010-09-30 04:26:36 +0900421}
422
initial.commit3f4a7322008-07-27 06:49:38 +0900423void SetLogItems(bool enable_process_id, bool enable_thread_id,
424 bool enable_timestamp, bool enable_tickcount) {
425 log_process_id = enable_process_id;
426 log_thread_id = enable_thread_id;
427 log_timestamp = enable_timestamp;
428 log_tickcount = enable_tickcount;
429}
430
cmasone@google.comf7802482010-08-17 09:38:12 +0900431void SetShowErrorDialogs(bool enable_dialogs) {
432 show_error_dialogs = enable_dialogs;
433}
434
initial.commit3f4a7322008-07-27 06:49:38 +0900435void SetLogAssertHandler(LogAssertHandlerFunction handler) {
436 log_assert_handler = handler;
437}
438
siggi@chromium.org4db65792009-11-26 00:26:34 +0900439void SetLogMessageHandler(LogMessageHandlerFunction handler) {
440 log_message_handler = handler;
441}
442
hansl@google.com519197c2010-11-04 04:20:27 +0900443LogMessageHandlerFunction GetLogMessageHandler() {
444 return log_message_handler;
445}
446
erg@google.com6575f362010-10-01 04:10:03 +0900447// MSVC doesn't like complex extern templates and DLLs.
448#if !defined(COMPILER_MSVC)
449// Explicit instantiations for commonly used comparisons.
450template std::string* MakeCheckOpString<int, int>(
451 const int&, const int&, const char* names);
452template std::string* MakeCheckOpString<unsigned long, unsigned long>(
453 const unsigned long&, const unsigned long&, const char* names);
454template std::string* MakeCheckOpString<unsigned long, unsigned int>(
455 const unsigned long&, const unsigned int&, const char* names);
456template std::string* MakeCheckOpString<unsigned int, unsigned long>(
457 const unsigned int&, const unsigned long&, const char* names);
458template std::string* MakeCheckOpString<std::string, std::string>(
459 const std::string&, const std::string&, const char* name);
460#endif
siggi@chromium.org4db65792009-11-26 00:26:34 +0900461
viettrungluu@chromium.org96925ac2014-06-17 21:04:23 +0900462#if !defined(NDEBUG)
evan@chromium.org5f1eade2010-03-01 22:10:22 +0900463// Displays a message box to the user with the error message in it.
464// Used for fatal messages, where we close the app simultaneously.
evan@chromium.orge6bd8fa2010-12-17 08:29:25 +0900465// This is for developers only; we don't use this in circumstances
466// (like release builds) where users could see it, since users don't
467// understand these messages anyway.
evan@chromium.org5f1eade2010-03-01 22:10:22 +0900468void DisplayDebugMessageInDialog(const std::string& str) {
initial.commit3f4a7322008-07-27 06:49:38 +0900469 if (str.empty())
470 return;
471
cmasone@google.comf7802482010-08-17 09:38:12 +0900472 if (!show_error_dialogs)
phajdan.jr@chromium.orgd4794e62010-07-30 05:33:44 +0900473 return;
474
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900475#if defined(OS_WIN)
evan@chromium.org5f1eade2010-03-01 22:10:22 +0900476 // For Windows programs, it's possible that the message loop is
477 // messed up on a fatal error, and creating a MessageBox will cause
478 // that message loop to be run. Instead, we try to spawn another
479 // process that displays its command line. We look for "Debug
480 // Message.exe" in the same directory as the application. If it
481 // exists, we use it, otherwise, we use a regular message box.
initial.commit3f4a7322008-07-27 06:49:38 +0900482 wchar_t prog_name[MAX_PATH];
483 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
484 wchar_t* backslash = wcsrchr(prog_name, '\\');
485 if (backslash)
486 backslash[1] = 0;
487 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
488
avi@chromium.org0e569b92013-12-26 16:07:56 +0900489 std::wstring cmdline = base::UTF8ToWide(str);
mark@chromium.orga332aa92009-03-26 07:12:02 +0900490 if (cmdline.empty())
491 return;
initial.commit3f4a7322008-07-27 06:49:38 +0900492
493 STARTUPINFO startup_info;
494 memset(&startup_info, 0, sizeof(startup_info));
495 startup_info.cb = sizeof(startup_info);
496
497 PROCESS_INFORMATION process_info;
mark@chromium.orga332aa92009-03-26 07:12:02 +0900498 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commit3f4a7322008-07-27 06:49:38 +0900499 NULL, &startup_info, &process_info)) {
500 WaitForSingleObject(process_info.hProcess, INFINITE);
501 CloseHandle(process_info.hThread);
502 CloseHandle(process_info.hProcess);
503 } else {
504 // debug process broken, let's just do a message box
mark@chromium.orga332aa92009-03-26 07:12:02 +0900505 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commit3f4a7322008-07-27 06:49:38 +0900506 MB_OK | MB_ICONHAND | MB_TOPMOST);
507 }
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900508#else
evan@chromium.orge6bd8fa2010-12-17 08:29:25 +0900509 // We intentionally don't implement a dialog on other platforms.
510 // You can just look at stderr.
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900511#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900512}
viettrungluu@chromium.org96925ac2014-06-17 21:04:23 +0900513#endif // !defined(NDEBUG)
initial.commit3f4a7322008-07-27 06:49:38 +0900514
tommi@google.com82788e12009-04-15 01:52:11 +0900515#if defined(OS_WIN)
516LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
517}
518
519LogMessage::SaveLastError::~SaveLastError() {
520 ::SetLastError(last_error_);
521}
522#endif // defined(OS_WIN)
523
erg@google.com37c078e2011-01-11 09:50:59 +0900524LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
525 : severity_(severity), file_(file), line_(line) {
526 Init(file, line);
527}
528
akalin@chromium.org63dab762011-02-08 16:39:08 +0900529LogMessage::LogMessage(const char* file, int line, std::string* result)
siggi@chromium.org25396e12010-11-05 00:50:49 +0900530 : severity_(LOG_FATAL), file_(file), line_(line) {
initial.commit3f4a7322008-07-27 06:49:38 +0900531 Init(file, line);
akalin@chromium.org63dab762011-02-08 16:39:08 +0900532 stream_ << "Check failed: " << *result;
533 delete result;
initial.commit3f4a7322008-07-27 06:49:38 +0900534}
535
huanr@chromium.org656253e2009-02-12 10:19:05 +0900536LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
akalin@chromium.org63dab762011-02-08 16:39:08 +0900537 std::string* result)
siggi@chromium.org25396e12010-11-05 00:50:49 +0900538 : severity_(severity), file_(file), line_(line) {
huanr@chromium.org656253e2009-02-12 10:19:05 +0900539 Init(file, line);
akalin@chromium.org63dab762011-02-08 16:39:08 +0900540 stream_ << "Check failed: " << *result;
541 delete result;
huanr@chromium.org656253e2009-02-12 10:19:05 +0900542}
543
initial.commit3f4a7322008-07-27 06:49:38 +0900544LogMessage::~LogMessage() {
mostynb@opera.comb98da342014-04-19 08:40:16 +0900545#if !defined(NDEBUG) && !defined(OS_NACL) && !defined(__UCLIBC__)
oshima@chromium.orgf79db072010-03-24 14:03:24 +0900546 if (severity_ == LOG_FATAL) {
547 // Include a stack trace on a fatal.
brettw@chromium.org2f49b122010-10-26 13:07:50 +0900548 base::debug::StackTrace trace;
oshima@chromium.orgf79db072010-03-24 14:03:24 +0900549 stream_ << std::endl; // Newline to separate from log message.
550 trace.OutputToStream(&stream_);
551 }
mmentovai@google.comf0944f32008-08-20 08:39:32 +0900552#endif
oshima@chromium.orgf79db072010-03-24 14:03:24 +0900553 stream_ << std::endl;
554 std::string str_newline(stream_.str());
555
siggi@chromium.org4db65792009-11-26 00:26:34 +0900556 // Give any log message handler first dibs on the message.
akalin@chromium.org6d987202013-06-22 06:15:33 +0900557 if (log_message_handler &&
558 log_message_handler(severity_, file_, line_,
559 message_start_, str_newline)) {
siggi@chromium.org25396e12010-11-05 00:50:49 +0900560 // The handler took care of it, no further processing.
siggi@chromium.org4db65792009-11-26 00:26:34 +0900561 return;
siggi@chromium.org25396e12010-11-05 00:50:49 +0900562 }
initial.commit3f4a7322008-07-27 06:49:38 +0900563
akalin@chromium.org6d987202013-06-22 06:15:33 +0900564 if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900565#if defined(OS_WIN)
initial.commit3f4a7322008-07-27 06:49:38 +0900566 OutputDebugStringA(str_newline.c_str());
michaelbai@google.com01ef2f22011-07-08 05:46:50 +0900567#elif defined(OS_ANDROID)
acolwell@chromium.org7d65ee62013-05-22 07:39:25 +0900568 android_LogPriority priority =
569 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
michaelbai@google.com01ef2f22011-07-08 05:46:50 +0900570 switch (severity_) {
571 case LOG_INFO:
572 priority = ANDROID_LOG_INFO;
573 break;
574 case LOG_WARNING:
575 priority = ANDROID_LOG_WARN;
576 break;
577 case LOG_ERROR:
michaelbai@google.com01ef2f22011-07-08 05:46:50 +0900578 priority = ANDROID_LOG_ERROR;
579 break;
580 case LOG_FATAL:
581 priority = ANDROID_LOG_FATAL;
582 break;
583 }
584 __android_log_write(priority, "chromium", str_newline.c_str());
erikkay@google.com7139eb22008-08-27 02:48:18 +0900585#endif
joaoe@opera.com1e706822014-03-15 02:02:15 +0900586 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
darin@chromium.org33fd3122010-09-25 00:43:06 +0900587 fflush(stderr);
erikkay@google.coma1ca46c2008-08-26 05:10:31 +0900588 } else if (severity_ >= kAlwaysPrintErrorLevel) {
589 // When we're only outputting to a log file, above a certain log level, we
590 // should still output to stderr so that we can better detect and diagnose
591 // problems with unit tests, especially on the buildbots.
joaoe@opera.com1e706822014-03-15 02:02:15 +0900592 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
derat@chromium.orge4ef1ac2009-12-02 09:34:02 +0900593 fflush(stderr);
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900594 }
maruel@chromium.org8fe7adc2009-03-04 00:01:12 +0900595
initial.commit3f4a7322008-07-27 06:49:38 +0900596 // write to log file
akalin@chromium.org6d987202013-06-22 06:15:33 +0900597 if ((logging_destination & LOG_TO_FILE) != 0) {
akalin@chromium.org2e983c52013-07-16 06:47:09 +0900598 // We can have multiple threads and/or processes, so try to prevent them
599 // from clobbering each other's writes.
600 // If the client app did not call InitLogging, and the lock has not
601 // been created do it now. We do this on demand, but if two threads try
602 // to do this at the same time, there will be a race condition to create
603 // the lock. This is why InitLogging should be called from the main
604 // thread at the beginning of execution.
605 LoggingLock::Init(LOCK_LOG_FILE, NULL);
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900606 LoggingLock logging_lock;
607 if (InitializeLogFileHandle()) {
pinkerton@google.com56053fe2008-08-08 22:27:28 +0900608#if defined(OS_WIN)
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900609 SetFilePointer(log_file, 0, 0, SEEK_END);
610 DWORD num_written;
611 WriteFile(log_file,
612 static_cast<const void*>(str_newline.c_str()),
613 static_cast<DWORD>(str_newline.length()),
614 &num_written,
615 NULL);
davemoore@chromium.org7e79d072010-09-01 07:35:55 +0900616#else
joaoe@opera.com1e706822014-03-15 02:02:15 +0900617 ignore_result(fwrite(
618 str_newline.data(), str_newline.size(), 1, log_file));
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900619 fflush(log_file);
davemoore@chromium.org7e79d072010-09-01 07:35:55 +0900620#endif
initial.commit3f4a7322008-07-27 06:49:38 +0900621 }
622 }
623
624 if (severity_ == LOG_FATAL) {
apatrick@chromium.org35e38992012-04-04 03:45:05 +0900625 // Ensure the first characters of the string are on the stack so they
626 // are contained in minidumps for diagnostic purposes.
627 char str_stack[1024];
628 str_newline.copy(str_stack, arraysize(str_stack));
629 base::debug::Alias(str_stack);
630
rch@chromium.org434edfb2014-03-01 03:25:34 +0900631 if (log_assert_handler) {
632 // Make a copy of the string for the handler out of paranoia.
633 log_assert_handler(std::string(stream_.str()));
deanm@google.comc2b652a2008-08-13 20:15:11 +0900634 } else {
rch@chromium.org434edfb2014-03-01 03:25:34 +0900635 // Don't use the string with the newline, get a fresh version to send to
636 // the debug message process. We also don't display assertions to the
637 // user in release mode. The enduser can't do anything with this
638 // information, and displaying message boxes when the application is
639 // hosed can cause additional problems.
brettw@google.comed61ae42008-11-06 09:33:50 +0900640#ifndef NDEBUG
rch@chromium.org434edfb2014-03-01 03:25:34 +0900641 DisplayDebugMessageInDialog(stream_.str());
brettw@google.comed61ae42008-11-06 09:33:50 +0900642#endif
rch@chromium.org434edfb2014-03-01 03:25:34 +0900643 // Crash the process to generate a dump.
644 base::debug::BreakDebugger();
initial.commit3f4a7322008-07-27 06:49:38 +0900645 }
646 }
647}
648
erg@google.com37c078e2011-01-11 09:50:59 +0900649// writes the common header info to the stream
650void LogMessage::Init(const char* file, int line) {
651 base::StringPiece filename(file);
652 size_t last_slash_pos = filename.find_last_of("\\/");
653 if (last_slash_pos != base::StringPiece::npos)
654 filename.remove_prefix(last_slash_pos + 1);
655
656 // TODO(darin): It might be nice if the columns were fixed width.
657
658 stream_ << '[';
659 if (log_process_id)
660 stream_ << CurrentProcessId() << ':';
661 if (log_thread_id)
rsesek@chromium.org4fd393b2012-01-19 06:21:09 +0900662 stream_ << base::PlatformThread::CurrentId() << ':';
erg@google.com37c078e2011-01-11 09:50:59 +0900663 if (log_timestamp) {
664 time_t t = time(NULL);
665 struct tm local_time = {0};
666#if _MSC_VER >= 1400
667 localtime_s(&local_time, &t);
668#else
669 localtime_r(&t, &local_time);
670#endif
671 struct tm* tm_time = &local_time;
672 stream_ << std::setfill('0')
673 << std::setw(2) << 1 + tm_time->tm_mon
674 << std::setw(2) << tm_time->tm_mday
675 << '/'
676 << std::setw(2) << tm_time->tm_hour
677 << std::setw(2) << tm_time->tm_min
678 << std::setw(2) << tm_time->tm_sec
679 << ':';
680 }
681 if (log_tickcount)
682 stream_ << TickCount() << ':';
683 if (severity_ >= 0)
tsepez@chromium.orgeef2c1c2014-01-23 10:36:19 +0900684 stream_ << log_severity_name(severity_);
erg@google.com37c078e2011-01-11 09:50:59 +0900685 else
686 stream_ << "VERBOSE" << -severity_;
687
688 stream_ << ":" << filename << "(" << line << ")] ";
689
690 message_start_ = stream_.tellp();
691}
692
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900693#if defined(OS_WIN)
694// This has already been defined in the header, but defining it again as DWORD
695// ensures that the type used in the header is equivalent to DWORD. If not,
696// the redefinition is a compile error.
697typedef DWORD SystemErrorCode;
698#endif
699
700SystemErrorCode GetLastSystemErrorCode() {
701#if defined(OS_WIN)
702 return ::GetLastError();
703#elif defined(OS_POSIX)
704 return errno;
705#else
706#error Not implemented
707#endif
708}
709
710#if defined(OS_WIN)
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +0900711BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
712 const int error_message_buffer_size = 256;
713 char msgbuf[error_message_buffer_size];
714 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
715 DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf,
716 arraysize(msgbuf), NULL);
717 if (len) {
718 // Messages returned by system end with line breaks.
719 return base::CollapseWhitespaceASCII(msgbuf, true) +
720 base::StringPrintf(" (0x%X)", error_code);
721 }
722 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
723 GetLastError(), error_code);
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900724}
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +0900725#elif defined(OS_POSIX)
726BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
727 return safe_strerror(error_code);
728}
729#else
730#error Not implemented
731#endif
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900732
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +0900733
734#if defined(OS_WIN)
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900735Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
736 int line,
737 LogSeverity severity,
738 SystemErrorCode err)
739 : err_(err),
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900740 log_message_(file, line, severity) {
741}
742
743Win32ErrorLogMessage::~Win32ErrorLogMessage() {
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +0900744 stream() << ": " << SystemErrorCodeToString(err_);
sky@chromium.orgd2a1c272012-04-06 01:57:06 +0900745 // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
746 // field) and use Alias in hopes that it makes it into crash dumps.
747 DWORD last_error = err_;
748 base::debug::Alias(&last_error);
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900749}
750#elif defined(OS_POSIX)
751ErrnoLogMessage::ErrnoLogMessage(const char* file,
752 int line,
753 LogSeverity severity,
754 SystemErrorCode err)
755 : err_(err),
756 log_message_(file, line, severity) {
757}
758
759ErrnoLogMessage::~ErrnoLogMessage() {
vitalybuka@chromium.orge8717362014-04-23 10:11:01 +0900760 stream() << ": " << SystemErrorCodeToString(err_);
tschmelcher@chromium.orgf29a4fc2009-10-10 08:52:20 +0900761}
762#endif // OS_WIN
763
initial.commit3f4a7322008-07-27 06:49:38 +0900764void CloseLogFile() {
davemoore@chromium.orgc4dae762010-09-15 07:24:55 +0900765 LoggingLock logging_lock;
akalin@chromium.org2e983c52013-07-16 06:47:09 +0900766 CloseLogFileUnlocked();
initial.commit3f4a7322008-07-27 06:49:38 +0900767}
768
willchan@chromium.org85113a12009-12-08 13:22:50 +0900769void RawLog(int level, const char* message) {
770 if (level >= min_log_level) {
771 size_t bytes_written = 0;
772 const size_t message_len = strlen(message);
773 int rv;
774 while (bytes_written < message_len) {
775 rv = HANDLE_EINTR(
776 write(STDERR_FILENO, message + bytes_written,
777 message_len - bytes_written));
778 if (rv < 0) {
779 // Give up, nothing we can do now.
780 break;
781 }
782 bytes_written += rv;
783 }
784
785 if (message_len > 0 && message[message_len - 1] != '\n') {
786 do {
787 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
788 if (rv < 0) {
789 // Give up, nothing we can do now.
790 break;
791 }
792 } while (rv != 1);
793 }
794 }
795
796 if (level == LOG_FATAL)
brettw@chromium.org2f49b122010-10-26 13:07:50 +0900797 base::debug::BreakDebugger();
willchan@chromium.org85113a12009-12-08 13:22:50 +0900798}
799
akalin@chromium.org227369d2012-01-20 15:33:27 +0900800// This was defined at the beginning of this file.
801#undef write
802
ananta@chromium.org76bc94e2013-02-28 07:04:00 +0900803#if defined(OS_WIN)
804std::wstring GetLogFileFullPath() {
805 if (log_file_name)
806 return *log_file_name;
807 return std::wstring();
808}
809#endif
810
ajwong@chromium.org24cb89e2009-04-24 09:13:08 +0900811} // namespace logging
initial.commit3f4a7322008-07-27 06:49:38 +0900812
jyasskin@chromium.orgf01cfba2014-07-09 08:03:06 +0900813std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
avi@chromium.org0e569b92013-12-26 16:07:56 +0900814 return out << base::WideToUTF8(std::wstring(wstr));
initial.commit3f4a7322008-07-27 06:49:38 +0900815}