blob: b7c313ed28ba38702a6f6c1515fadfff20816f55 [file] [log] [blame]
[email protected]f1633932010-08-17 23:05:281// Copyright (c) 2010 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
[email protected]b16ef312008-08-19 18:36:237#if defined(OS_WIN)
[email protected]e36ddc82009-12-08 04:22:508#include <io.h>
[email protected]f6abeba2008-08-08 13:27:289#include <windows.h>
10typedef HANDLE FileHandle;
11typedef HANDLE MutexHandle;
[email protected]e36ddc82009-12-08 04:22:5012// 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
[email protected]052f1b52008-11-06 21:43:0716#elif defined(OS_MACOSX)
[email protected]f6abeba2008-08-08 13:27:2817#include <CoreFoundation/CoreFoundation.h>
18#include <mach/mach.h>
19#include <mach/mach_time.h>
20#include <mach-o/dyld.h>
[email protected]e43eddf12009-12-29 00:32:5221#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:0722#include <sys/syscall.h>
23#include <time.h>
[email protected]614e9fa2008-08-11 22:52:5924#endif
25
26#if defined(OS_POSIX)
[email protected]d8617a62009-10-09 23:52:2027#include <errno.h>
[email protected]166326c62010-08-05 15:50:2328#include <pthread.h>
[email protected]f6abeba2008-08-08 13:27:2829#include <stdlib.h>
30#include <stdio.h>
31#include <string.h>
32#include <unistd.h>
33#define MAX_PATH PATH_MAX
34typedef FILE* FileHandle;
35typedef pthread_mutex_t* MutexHandle;
36#endif
37
initial.commitd7cae122008-07-26 21:49:3838#include <ctime>
39#include <iomanip>
40#include <cstring>
initial.commitd7cae122008-07-26 21:49:3841#include <algorithm>
[email protected]b16ef312008-08-19 18:36:2342
initial.commitd7cae122008-07-26 21:49:3843#include "base/base_switches.h"
44#include "base/command_line.h"
[email protected]1ffe08c12008-08-13 11:15:1145#include "base/debug_util.h"
[email protected]e36ddc82009-12-08 04:22:5046#include "base/eintr_wrapper.h"
initial.commitd7cae122008-07-26 21:49:3847#include "base/lock_impl.h"
[email protected]d8617a62009-10-09 23:52:2048#if defined(OS_POSIX)
49#include "base/safe_strerror_posix.h"
50#endif
[email protected]d81baca42010-03-01 13:10:2251#include "base/process_util.h"
[email protected]4bdaceb42008-08-19 13:19:2452#include "base/string_piece.h"
[email protected]047a03f2009-10-07 02:10:2053#include "base/utf_string_conversions.h"
[email protected]52a261f2009-03-03 15:01:1254
initial.commitd7cae122008-07-26 21:49:3855namespace logging {
56
57bool g_enable_dcheck = false;
58
59const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]fb62a532009-02-12 01:19:0560 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3861
62int min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3263
64// The default set here for logging_destination will only be used if
65// InitLogging is not called. On Windows, use a file next to the exe;
66// on POSIX platforms, where it may not even be possible to locate the
67// executable on disk, use stderr.
[email protected]4c0040c2008-08-15 01:04:1168#if defined(OS_WIN)
[email protected]fe613522008-08-22 17:09:3469LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
[email protected]4c0040c2008-08-15 01:04:1170#elif defined(OS_POSIX)
[email protected]1d8c2702008-08-19 23:39:3271LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
[email protected]4c0040c2008-08-15 01:04:1172#endif
initial.commitd7cae122008-07-26 21:49:3873
74const int kMaxFilteredLogLevel = LOG_WARNING;
[email protected]614e9fa2008-08-11 22:52:5975std::string* log_filter_prefix;
initial.commitd7cae122008-07-26 21:49:3876
[email protected]a33c9892008-08-25 20:10:3177// For LOG_ERROR and above, always print to stderr.
78const int kAlwaysPrintErrorLevel = LOG_ERROR;
79
[email protected]614e9fa2008-08-11 22:52:5980// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3881// will be lazily initialized to the default value when it is
82// first needed.
[email protected]f6abeba2008-08-08 13:27:2883#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5984typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2885#else
[email protected]614e9fa2008-08-11 22:52:5986typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:2887#endif
[email protected]614e9fa2008-08-11 22:52:5988PathString* log_file_name = NULL;
initial.commitd7cae122008-07-26 21:49:3889
90// this file is lazily opened and the handle may be NULL
[email protected]f6abeba2008-08-08 13:27:2891FileHandle log_file = NULL;
initial.commitd7cae122008-07-26 21:49:3892
93// what should be prepended to each message?
94bool log_process_id = false;
95bool log_thread_id = false;
96bool log_timestamp = true;
97bool log_tickcount = false;
98
[email protected]81e0a852010-08-17 00:38:1299// Should we pop up fatal debug messages in a dialog?
100bool show_error_dialogs = false;
101
initial.commitd7cae122008-07-26 21:49:38102// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05103// the debug message dialog and process termination.
initial.commitd7cae122008-07-26 21:49:38104LogAssertHandlerFunction log_assert_handler = NULL;
[email protected]fb62a532009-02-12 01:19:05105// An report handler override specified by the client to be called instead of
106// the debug message dialog.
107LogReportHandlerFunction log_report_handler = NULL;
[email protected]2b07b8412009-11-25 15:26:34108// A log message handler that gets notified of every log message we process.
109LogMessageHandlerFunction log_message_handler = NULL;
initial.commitd7cae122008-07-26 21:49:38110
[email protected]f6abeba2008-08-08 13:27:28111// Helper functions to wrap platform differences.
112
[email protected]f8588472008-11-05 23:17:24113int32 CurrentProcessId() {
114#if defined(OS_WIN)
115 return GetCurrentProcessId();
116#elif defined(OS_POSIX)
117 return getpid();
118#endif
119}
120
121int32 CurrentThreadId() {
122#if defined(OS_WIN)
123 return GetCurrentThreadId();
124#elif defined(OS_MACOSX)
125 return mach_thread_self();
[email protected]052f1b52008-11-06 21:43:07126#elif defined(OS_LINUX)
127 return syscall(__NR_gettid);
[email protected]e43eddf12009-12-29 00:32:52128#elif defined(OS_FREEBSD)
129 // TODO(BSD): find a better thread ID
130 return reinterpret_cast<int64>(pthread_self());
[email protected]f8588472008-11-05 23:17:24131#endif
132}
133
134uint64 TickCount() {
135#if defined(OS_WIN)
136 return GetTickCount();
137#elif defined(OS_MACOSX)
138 return mach_absolute_time();
[email protected]e43eddf12009-12-29 00:32:52139#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07140 struct timespec ts;
141 clock_gettime(CLOCK_MONOTONIC, &ts);
142
143 uint64 absolute_micro =
144 static_cast<int64>(ts.tv_sec) * 1000000 +
145 static_cast<int64>(ts.tv_nsec) / 1000;
146
147 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24148#endif
149}
150
[email protected]f6abeba2008-08-08 13:27:28151void CloseFile(FileHandle log) {
152#if defined(OS_WIN)
153 CloseHandle(log);
154#else
155 fclose(log);
156#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());
[email protected]f6abeba2008-08-08 13:27:28162#else
[email protected]614e9fa2008-08-11 22:52:59163 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28164#endif
165}
initial.commitd7cae122008-07-26 21:49:38166
[email protected]b3c572a2010-08-31 21:48:58167PathString* GetDefaultLogFile() {
168#if defined(OS_WIN)
169 // On Windows we use the same path as the exe.
170 wchar_t module_name[MAX_PATH];
171 GetModuleFileName(NULL, module_name, MAX_PATH);
172 PathString *new_log_file = new std::wstring(module_name);
173 std::wstring::size_type last_backslash =
174 new_log_file->rfind('\\', new_log_file->size());
175 if (last_backslash != std::wstring::npos)
176 new_log_file->erase(last_backslash + 1);
177 *new_log_file += L"debug.log";
178 return new_log_file;
179#elif defined(OS_POSIX)
180 // On other platforms we just use the current directory.
181 return new std::string("debug.log");
182#endif
183}
184
185// This class acts as a wrapper for locking the logging files.
186// LoggingLock::Init() should be called from the main thread before any logging
187// is done. Then whenever logging, be sure to have a local LoggingLock
188// instance on the stack. This will ensure that the lock is unlocked upon
189// exiting the frame.
190// LoggingLocks can not be nested.
191class LoggingLock {
192 public:
193 LoggingLock() {
194 LockLogging();
195 }
196
197 ~LoggingLock() {
198 UnlockLogging();
199 }
200
201 static void Init(LogLockingState lock_log, PathString* new_log_file) {
202 if (initialized)
203 return;
204 lock_log_file = lock_log;
205 if (lock_log_file == LOCK_LOG_FILE) {
206#if defined(OS_WIN)
207 if (!log_mutex) {
208 // \ is not a legal character in mutex names so we replace \ with /
209 if (!new_log_file)
210 new_log_file = GetDefaultLogFile();
211 std::wstring safe_name(*new_log_file);
212 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
213 std::wstring t(L"Global\\");
214 t.append(safe_name);
215 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
216 }
217#endif
218 } else {
219 log_lock = new LockImpl();
220 }
221 initialized = true;
222 }
223
224 private:
225 static void LockLogging() {
226 if (lock_log_file == LOCK_LOG_FILE) {
227#if defined(OS_WIN)
228 ::WaitForSingleObject(log_mutex, INFINITE);
229 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
230 // abort the process here. UI tests might be crashy sometimes,
231 // and aborting the test binary only makes the problem worse.
232 // We also don't use LOG macros because that might lead to an infinite
233 // loop. For more info see http://crbug.com/18028.
234#elif defined(OS_POSIX)
235 pthread_mutex_lock(&log_mutex);
236#endif
237 } else {
238 // use the lock
239 log_lock->Lock();
240 }
241 }
242
243 static void UnlockLogging() {
244 if (lock_log_file == LOCK_LOG_FILE) {
245#if defined(OS_WIN)
246 ReleaseMutex(log_mutex);
247#elif defined(OS_POSIX)
248 pthread_mutex_unlock(&log_mutex);
249#endif
250 } else {
251 log_lock->Unlock();
252 }
253 }
254
255 // The lock is used if log file locking is false. It helps us avoid problems
256 // with multiple threads writing to the log file at the same time. Use
257 // LockImpl directly instead of using Lock, because Lock makes logging calls.
258 static LockImpl* log_lock;
259
260 // When we don't use a lock, we are using a global mutex. We need to do this
261 // because LockFileEx is not thread safe.
262#if defined(OS_WIN)
263 static MutexHandle log_mutex;
264#elif defined(OS_POSIX)
265 static pthread_mutex_t log_mutex;
266#endif
267
268 static bool initialized;
269 static LogLockingState lock_log_file;
270};
271
272// static
273bool LoggingLock::initialized = false;
274// static
275LockImpl* LoggingLock::log_lock = NULL;
276// static
277LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
278
279#if defined(OS_WIN)
280// static
281MutexHandle LoggingLock::log_mutex = NULL;
282#elif defined(OS_POSIX)
283pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
284#endif
285
initial.commitd7cae122008-07-26 21:49:38286// Called by logging functions to ensure that debug_file is initialized
287// and can be used for writing. Returns false if the file could not be
288// initialized. debug_file will be NULL in this case.
289bool InitializeLogFileHandle() {
290 if (log_file)
291 return true;
292
[email protected]614e9fa2008-08-11 22:52:59293 if (!log_file_name) {
294 // Nobody has called InitLogging to specify a debug log file, so here we
295 // initialize the log file name to a default.
[email protected]b3c572a2010-08-31 21:48:58296 log_file_name = GetDefaultLogFile();
initial.commitd7cae122008-07-26 21:49:38297 }
298
[email protected]1d8c2702008-08-19 23:39:32299 if (logging_destination == LOG_ONLY_TO_FILE ||
300 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
[email protected]614e9fa2008-08-11 22:52:59301#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32302 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38303 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
304 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
305 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32306 // try the current directory
307 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
308 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
309 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
310 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
311 log_file = NULL;
312 return false;
313 }
initial.commitd7cae122008-07-26 21:49:38314 }
[email protected]1d8c2702008-08-19 23:39:32315 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11316#elif defined(OS_POSIX)
317 log_file = fopen(log_file_name->c_str(), "a");
318 if (log_file == NULL)
319 return false;
[email protected]f6abeba2008-08-08 13:27:28320#endif
[email protected]1d8c2702008-08-19 23:39:32321 }
322
initial.commitd7cae122008-07-26 21:49:38323 return true;
324}
325
[email protected]ff3d0c32010-08-23 19:57:46326void BaseInitLoggingImpl(const PathChar* new_log_file,
327 LoggingDestination logging_dest,
328 LogLockingState lock_log,
329 OldFileDeletionState delete_old) {
[email protected]bb975362009-01-21 01:00:22330 g_enable_dcheck =
331 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableDCHECK);
[email protected]b3c572a2010-08-31 21:48:58332 PathString* new_log_file_name = new PathString();
333 *new_log_file_name = new_log_file;
334 LoggingLock::Init(lock_log, new_log_file_name);
335
336 LoggingLock logging_lock;
initial.commitd7cae122008-07-26 21:49:38337
338 if (log_file) {
339 // calling InitLogging twice or after some log call has already opened the
340 // default log file will re-initialize to the new options
[email protected]f6abeba2008-08-08 13:27:28341 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38342 log_file = NULL;
343 }
344
initial.commitd7cae122008-07-26 21:49:38345 logging_destination = logging_dest;
346
347 // ignore file options if logging is disabled or only to system
348 if (logging_destination == LOG_NONE ||
349 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
350 return;
351
[email protected]614e9fa2008-08-11 22:52:59352 if (!log_file_name)
353 log_file_name = new PathString();
354 *log_file_name = new_log_file;
initial.commitd7cae122008-07-26 21:49:38355 if (delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59356 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38357
initial.commitd7cae122008-07-26 21:49:38358 InitializeLogFileHandle();
[email protected]b3c572a2010-08-31 21:48:58359
initial.commitd7cae122008-07-26 21:49:38360}
361
362void SetMinLogLevel(int level) {
363 min_log_level = level;
364}
365
366int GetMinLogLevel() {
367 return min_log_level;
368}
369
370void SetLogFilterPrefix(const char* filter) {
371 if (log_filter_prefix) {
[email protected]614e9fa2008-08-11 22:52:59372 delete log_filter_prefix;
initial.commitd7cae122008-07-26 21:49:38373 log_filter_prefix = NULL;
374 }
375
[email protected]614e9fa2008-08-11 22:52:59376 if (filter)
377 log_filter_prefix = new std::string(filter);
initial.commitd7cae122008-07-26 21:49:38378}
379
380void SetLogItems(bool enable_process_id, bool enable_thread_id,
381 bool enable_timestamp, bool enable_tickcount) {
382 log_process_id = enable_process_id;
383 log_thread_id = enable_thread_id;
384 log_timestamp = enable_timestamp;
385 log_tickcount = enable_tickcount;
386}
387
[email protected]81e0a852010-08-17 00:38:12388void SetShowErrorDialogs(bool enable_dialogs) {
389 show_error_dialogs = enable_dialogs;
390}
391
initial.commitd7cae122008-07-26 21:49:38392void SetLogAssertHandler(LogAssertHandlerFunction handler) {
393 log_assert_handler = handler;
394}
395
[email protected]fb62a532009-02-12 01:19:05396void SetLogReportHandler(LogReportHandlerFunction handler) {
397 log_report_handler = handler;
398}
399
[email protected]2b07b8412009-11-25 15:26:34400void SetLogMessageHandler(LogMessageHandlerFunction handler) {
401 log_message_handler = handler;
402}
403
404
[email protected]d81baca42010-03-01 13:10:22405// Displays a message box to the user with the error message in it.
406// Used for fatal messages, where we close the app simultaneously.
407void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38408 if (str.empty())
409 return;
410
[email protected]81e0a852010-08-17 00:38:12411 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44412 return;
413
[email protected]f6abeba2008-08-08 13:27:28414#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22415 // For Windows programs, it's possible that the message loop is
416 // messed up on a fatal error, and creating a MessageBox will cause
417 // that message loop to be run. Instead, we try to spawn another
418 // process that displays its command line. We look for "Debug
419 // Message.exe" in the same directory as the application. If it
420 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38421 wchar_t prog_name[MAX_PATH];
422 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
423 wchar_t* backslash = wcsrchr(prog_name, '\\');
424 if (backslash)
425 backslash[1] = 0;
426 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
427
[email protected]047a03f2009-10-07 02:10:20428 std::wstring cmdline = UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02429 if (cmdline.empty())
430 return;
initial.commitd7cae122008-07-26 21:49:38431
432 STARTUPINFO startup_info;
433 memset(&startup_info, 0, sizeof(startup_info));
434 startup_info.cb = sizeof(startup_info);
435
436 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02437 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38438 NULL, &startup_info, &process_info)) {
439 WaitForSingleObject(process_info.hProcess, INFINITE);
440 CloseHandle(process_info.hThread);
441 CloseHandle(process_info.hProcess);
442 } else {
443 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02444 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38445 MB_OK | MB_ICONHAND | MB_TOPMOST);
446 }
[email protected]81e0a852010-08-17 00:38:12447#elif defined(USE_X11) && !defined(OS_CHROMEOS)
[email protected]d81baca42010-03-01 13:10:22448 // Shell out to xmessage, which behaves like debug_message.exe, but is
449 // way more retro. We could use zenity/kdialog but then we're starting
450 // to get into needing to check the desktop env and this dialog should
451 // only be coming up in Very Bad situations.
452 std::vector<std::string> argv;
453 argv.push_back("xmessage");
454 argv.push_back(str);
455 base::LaunchApp(argv, base::file_handle_mapping_vector(), true /* wait */,
456 NULL);
[email protected]f6abeba2008-08-08 13:27:28457#else
[email protected]d81baca42010-03-01 13:10:22458 // http://code.google.com/p/chromium/issues/detail?id=37026
459 NOTIMPLEMENTED();
[email protected]f6abeba2008-08-08 13:27:28460#endif
initial.commitd7cae122008-07-26 21:49:38461}
462
[email protected]3f85caa2009-04-14 16:52:11463#if defined(OS_WIN)
464LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
465}
466
467LogMessage::SaveLastError::~SaveLastError() {
468 ::SetLastError(last_error_);
469}
470#endif // defined(OS_WIN)
471
initial.commitd7cae122008-07-26 21:49:38472LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
473 int ctr)
474 : severity_(severity) {
475 Init(file, line);
476}
477
478LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
479 : severity_(LOG_FATAL) {
480 Init(file, line);
481 stream_ << "Check failed: " << (*result.str_);
482}
483
[email protected]fb62a532009-02-12 01:19:05484LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
485 const CheckOpString& result)
486 : severity_(severity) {
487 Init(file, line);
488 stream_ << "Check failed: " << (*result.str_);
489}
490
initial.commitd7cae122008-07-26 21:49:38491LogMessage::LogMessage(const char* file, int line)
492 : severity_(LOG_INFO) {
493 Init(file, line);
494}
495
496LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
497 : severity_(severity) {
498 Init(file, line);
499}
500
501// writes the common header info to the stream
502void LogMessage::Init(const char* file, int line) {
503 // log only the filename
504 const char* last_slash = strrchr(file, '\\');
505 if (last_slash)
506 file = last_slash + 1;
507
508 // TODO(darin): It might be nice if the columns were fixed width.
509
510 stream_ << '[';
511 if (log_process_id)
[email protected]f8588472008-11-05 23:17:24512 stream_ << CurrentProcessId() << ':';
initial.commitd7cae122008-07-26 21:49:38513 if (log_thread_id)
[email protected]f8588472008-11-05 23:17:24514 stream_ << CurrentThreadId() << ':';
initial.commitd7cae122008-07-26 21:49:38515 if (log_timestamp) {
[email protected]defcd8f32009-05-13 00:03:43516 time_t t = time(NULL);
initial.commitd7cae122008-07-26 21:49:38517 struct tm local_time = {0};
[email protected]defcd8f32009-05-13 00:03:43518#if _MSC_VER >= 1400
initial.commitd7cae122008-07-26 21:49:38519 localtime_s(&local_time, &t);
initial.commitd7cae122008-07-26 21:49:38520#else
[email protected]defcd8f32009-05-13 00:03:43521 localtime_r(&t, &local_time);
initial.commitd7cae122008-07-26 21:49:38522#endif
[email protected]defcd8f32009-05-13 00:03:43523 struct tm* tm_time = &local_time;
initial.commitd7cae122008-07-26 21:49:38524 stream_ << std::setfill('0')
525 << std::setw(2) << 1 + tm_time->tm_mon
526 << std::setw(2) << tm_time->tm_mday
527 << '/'
528 << std::setw(2) << tm_time->tm_hour
529 << std::setw(2) << tm_time->tm_min
530 << std::setw(2) << tm_time->tm_sec
531 << ':';
532 }
533 if (log_tickcount)
[email protected]f8588472008-11-05 23:17:24534 stream_ << TickCount() << ':';
[email protected]52a261f2009-03-03 15:01:12535 stream_ << log_severity_names[severity_] << ":" << file <<
536 "(" << line << ")] ";
initial.commitd7cae122008-07-26 21:49:38537
538 message_start_ = stream_.tellp();
539}
540
541LogMessage::~LogMessage() {
542 // TODO(brettw) modify the macros so that nothing is executed when the log
543 // level is too high.
544 if (severity_ < min_log_level)
545 return;
546
[email protected]d1ccc35a2010-03-24 05:03:24547#ifndef NDEBUG
548 if (severity_ == LOG_FATAL) {
549 // Include a stack trace on a fatal.
550 StackTrace trace;
551 stream_ << std::endl; // Newline to separate from log message.
552 trace.OutputToStream(&stream_);
553 }
[email protected]1d8c2702008-08-19 23:39:32554#endif
[email protected]d1ccc35a2010-03-24 05:03:24555 stream_ << std::endl;
556 std::string str_newline(stream_.str());
557
[email protected]2b07b8412009-11-25 15:26:34558 // Give any log message handler first dibs on the message.
559 if (log_message_handler && log_message_handler(severity_, str_newline))
560 return;
initial.commitd7cae122008-07-26 21:49:38561
562 if (log_filter_prefix && severity_ <= kMaxFilteredLogLevel &&
[email protected]614e9fa2008-08-11 22:52:59563 str_newline.compare(message_start_, log_filter_prefix->size(),
564 log_filter_prefix->data()) != 0) {
initial.commitd7cae122008-07-26 21:49:38565 return;
566 }
567
568 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
[email protected]f6abeba2008-08-08 13:27:28569 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
570#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38571 OutputDebugStringA(str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02572 if (severity_ >= kAlwaysPrintErrorLevel) {
573#else
574 {
[email protected]107bc0f12008-08-26 17:48:18575#endif
[email protected]1ce41052009-12-02 00:34:02576 // TODO(erikkay): this interferes with the layout tests since it grabs
577 // stderr and stdout and diffs them against known data. Our info and warn
578 // logs add noise to that. Ideally, the layout tests would set the log
579 // level to ignore anything below error. When that happens, we should
580 // take this fprintf out of the #else so that Windows users can benefit
581 // from the output when running tests from the command-line. In the
582 // meantime, we leave this in for Mac and Linux, but until this is fixed
583 // they won't be able to pass any layout tests that have info or warn
584 // logs. See http://b/1343647
585 fprintf(stderr, "%s", str_newline.c_str());
586 fflush(stderr);
587 }
[email protected]a33c9892008-08-25 20:10:31588 } 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.
592 fprintf(stderr, "%s", str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02593 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28594 }
[email protected]52a261f2009-03-03 15:01:12595
[email protected]b3c572a2010-08-31 21:48:58596 // We can have multiple threads and/or processes, so try to prevent them
597 // from clobbering each other's writes.
598 // If the client app did not call InitLogging, and the lock has not
599 // been created do it now. We do this on demand, but if two threads try
600 // to do this at the same time, there will be a race condition to create
601 // the lock. This is why InitLogging should be called from the main
602 // thread at the beginning of execution.
603 LoggingLock::Init(LOCK_LOG_FILE, NULL);
initial.commitd7cae122008-07-26 21:49:38604 // write to log file
605 if (logging_destination != LOG_NONE &&
[email protected]b3c572a2010-08-31 21:48:58606 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
607 LoggingLock logging_lock;
608 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28609#if defined(OS_WIN)
[email protected]b3c572a2010-08-31 21:48:58610 SetFilePointer(log_file, 0, 0, SEEK_END);
611 DWORD num_written;
612 WriteFile(log_file,
613 static_cast<const void*>(str_newline.c_str()),
614 static_cast<DWORD>(str_newline.length()),
615 &num_written,
616 NULL);
[email protected]f6abeba2008-08-08 13:27:28617#else
[email protected]b3c572a2010-08-31 21:48:58618 fprintf(log_file, "%s", str_newline.c_str());
619 fflush(log_file);
[email protected]f6abeba2008-08-08 13:27:28620#endif
initial.commitd7cae122008-07-26 21:49:38621 }
622 }
623
624 if (severity_ == LOG_FATAL) {
625 // display a message or break into the debugger on a fatal error
[email protected]1ffe08c12008-08-13 11:15:11626 if (DebugUtil::BeingDebugged()) {
627 DebugUtil::BreakDebugger();
628 } else {
initial.commitd7cae122008-07-26 21:49:38629 if (log_assert_handler) {
630 // make a copy of the string for the handler out of paranoia
631 log_assert_handler(std::string(stream_.str()));
632 } else {
[email protected]4d5901272008-11-06 00:33:50633 // Don't use the string with the newline, get a fresh version to send to
634 // the debug message process. We also don't display assertions to the
635 // user in release mode. The enduser can't do anything with this
636 // information, and displaying message boxes when the application is
637 // hosed can cause additional problems.
638#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22639 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50640#endif
initial.commitd7cae122008-07-26 21:49:38641 // Crash the process to generate a dump.
[email protected]1ffe08c12008-08-13 11:15:11642 DebugUtil::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38643 }
644 }
[email protected]fb62a532009-02-12 01:19:05645 } else if (severity_ == LOG_ERROR_REPORT) {
646 // We are here only if the user runs with --enable-dcheck in release mode.
647 if (log_report_handler) {
648 log_report_handler(std::string(stream_.str()));
649 } else {
[email protected]d81baca42010-03-01 13:10:22650 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05651 }
initial.commitd7cae122008-07-26 21:49:38652 }
653}
654
[email protected]d8617a62009-10-09 23:52:20655#if defined(OS_WIN)
656// This has already been defined in the header, but defining it again as DWORD
657// ensures that the type used in the header is equivalent to DWORD. If not,
658// the redefinition is a compile error.
659typedef DWORD SystemErrorCode;
660#endif
661
662SystemErrorCode GetLastSystemErrorCode() {
663#if defined(OS_WIN)
664 return ::GetLastError();
665#elif defined(OS_POSIX)
666 return errno;
667#else
668#error Not implemented
669#endif
670}
671
672#if defined(OS_WIN)
673Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
674 int line,
675 LogSeverity severity,
676 SystemErrorCode err,
677 const char* module)
678 : err_(err),
679 module_(module),
680 log_message_(file, line, severity) {
681}
682
683Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
684 int line,
685 LogSeverity severity,
686 SystemErrorCode err)
687 : err_(err),
688 module_(NULL),
689 log_message_(file, line, severity) {
690}
691
692Win32ErrorLogMessage::~Win32ErrorLogMessage() {
693 const int error_message_buffer_size = 256;
694 char msgbuf[error_message_buffer_size];
695 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
696 HMODULE hmod;
697 if (module_) {
698 hmod = GetModuleHandleA(module_);
699 if (hmod) {
700 flags |= FORMAT_MESSAGE_FROM_HMODULE;
701 } else {
702 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
703 // so it will not call GetModuleHandle, so recursive errors are
704 // impossible.
705 DPLOG(WARNING) << "Couldn't open module " << module_
706 << " for error message query";
707 }
708 } else {
709 hmod = NULL;
710 }
711 DWORD len = FormatMessageA(flags,
712 hmod,
713 err_,
714 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
715 msgbuf,
716 sizeof(msgbuf) / sizeof(msgbuf[0]),
717 NULL);
718 if (len) {
719 while ((len > 0) &&
720 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
721 msgbuf[--len] = 0;
722 }
723 stream() << ": " << msgbuf;
724 } else {
725 stream() << ": Error " << GetLastError() << " while retrieving error "
726 << err_;
727 }
728}
729#elif defined(OS_POSIX)
730ErrnoLogMessage::ErrnoLogMessage(const char* file,
731 int line,
732 LogSeverity severity,
733 SystemErrorCode err)
734 : err_(err),
735 log_message_(file, line, severity) {
736}
737
738ErrnoLogMessage::~ErrnoLogMessage() {
739 stream() << ": " << safe_strerror(err_);
740}
741#endif // OS_WIN
742
initial.commitd7cae122008-07-26 21:49:38743void CloseLogFile() {
[email protected]b3c572a2010-08-31 21:48:58744 LoggingLock logging_lock;
745
initial.commitd7cae122008-07-26 21:49:38746 if (!log_file)
747 return;
748
[email protected]f6abeba2008-08-08 13:27:28749 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38750 log_file = NULL;
751}
752
[email protected]e36ddc82009-12-08 04:22:50753void RawLog(int level, const char* message) {
754 if (level >= min_log_level) {
755 size_t bytes_written = 0;
756 const size_t message_len = strlen(message);
757 int rv;
758 while (bytes_written < message_len) {
759 rv = HANDLE_EINTR(
760 write(STDERR_FILENO, message + bytes_written,
761 message_len - bytes_written));
762 if (rv < 0) {
763 // Give up, nothing we can do now.
764 break;
765 }
766 bytes_written += rv;
767 }
768
769 if (message_len > 0 && message[message_len - 1] != '\n') {
770 do {
771 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
772 if (rv < 0) {
773 // Give up, nothing we can do now.
774 break;
775 }
776 } while (rv != 1);
777 }
778 }
779
780 if (level == LOG_FATAL)
781 DebugUtil::BreakDebugger();
782}
783
[email protected]96fd0032009-04-24 00:13:08784} // namespace logging
initial.commitd7cae122008-07-26 21:49:38785
786std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20787 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38788}