blob: 780da868af49a9e5dbdb414abcd3f00f081f3f0f [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]5b84fe32010-09-14 22:24:55167void GetDefaultLogFile(PathString default_log_file) {
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 default_log_file = module_name;
173 std::wstring::size_type last_backslash =
174 default_log_file.rfind('\\', default_log_file.size());
175 if (last_backslash != std::wstring::npos)
176 default_log_file.erase(last_backslash + 1);
177 default_log_file += L"debug.log";
178#elif defined(OS_POSIX)
179 // On other platforms we just use the current directory.
180 default_log_file = "debug.log";
181#endif
182}
183
184// This class acts as a wrapper for locking the logging files.
185// LoggingLock::Init() should be called from the main thread before any logging
186// is done. Then whenever logging, be sure to have a local LoggingLock
187// instance on the stack. This will ensure that the lock is unlocked upon
188// exiting the frame.
189// LoggingLocks can not be nested.
190class LoggingLock {
191 public:
192 LoggingLock() {
193 LockLogging();
194 }
195
196 ~LoggingLock() {
197 UnlockLogging();
198 }
199
200 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
201 if (initialized)
202 return;
203 lock_log_file = lock_log;
204 if (lock_log_file == LOCK_LOG_FILE) {
205#if defined(OS_WIN)
206 if (!log_mutex) {
207 std::wstring safe_name;
208 if (new_log_file)
209 safe_name = new_log_file;
210 else
211 GetDefaultLogFile(safe_name);
212 // \ is not a legal character in mutex names so we replace \ with /
213 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
214 std::wstring t(L"Global\\");
215 t.append(safe_name);
216 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
217 }
218#endif
219 } else {
220 log_lock = new LockImpl();
221 }
222 initialized = true;
223 }
224
225 private:
226 static void LockLogging() {
227 if (lock_log_file == LOCK_LOG_FILE) {
228#if defined(OS_WIN)
229 ::WaitForSingleObject(log_mutex, INFINITE);
230 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
231 // abort the process here. UI tests might be crashy sometimes,
232 // and aborting the test binary only makes the problem worse.
233 // We also don't use LOG macros because that might lead to an infinite
234 // loop. For more info see http://crbug.com/18028.
235#elif defined(OS_POSIX)
236 pthread_mutex_lock(&log_mutex);
237#endif
238 } else {
239 // use the lock
240 log_lock->Lock();
241 }
242 }
243
244 static void UnlockLogging() {
245 if (lock_log_file == LOCK_LOG_FILE) {
246#if defined(OS_WIN)
247 ReleaseMutex(log_mutex);
248#elif defined(OS_POSIX)
249 pthread_mutex_unlock(&log_mutex);
250#endif
251 } else {
252 log_lock->Unlock();
253 }
254 }
255
256 // The lock is used if log file locking is false. It helps us avoid problems
257 // with multiple threads writing to the log file at the same time. Use
258 // LockImpl directly instead of using Lock, because Lock makes logging calls.
259 static LockImpl* log_lock;
260
261 // When we don't use a lock, we are using a global mutex. We need to do this
262 // because LockFileEx is not thread safe.
263#if defined(OS_WIN)
264 static MutexHandle log_mutex;
265#elif defined(OS_POSIX)
266 static pthread_mutex_t log_mutex;
267#endif
268
269 static bool initialized;
270 static LogLockingState lock_log_file;
271};
272
273// static
274bool LoggingLock::initialized = false;
275// static
276LockImpl* LoggingLock::log_lock = NULL;
277// static
278LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
279
280#if defined(OS_WIN)
281// static
282MutexHandle LoggingLock::log_mutex = NULL;
283#elif defined(OS_POSIX)
284pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
285#endif
286
initial.commitd7cae122008-07-26 21:49:38287// Called by logging functions to ensure that debug_file is initialized
288// and can be used for writing. Returns false if the file could not be
289// initialized. debug_file will be NULL in this case.
290bool InitializeLogFileHandle() {
291 if (log_file)
292 return true;
293
[email protected]614e9fa2008-08-11 22:52:59294 if (!log_file_name) {
295 // Nobody has called InitLogging to specify a debug log file, so here we
296 // initialize the log file name to a default.
[email protected]5b84fe32010-09-14 22:24:55297 log_file_name = new PathString();
298 GetDefaultLogFile(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38299 }
300
[email protected]1d8c2702008-08-19 23:39:32301 if (logging_destination == LOG_ONLY_TO_FILE ||
302 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
[email protected]614e9fa2008-08-11 22:52:59303#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32304 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38305 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
306 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
307 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32308 // try the current directory
309 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
310 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
311 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
312 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
313 log_file = NULL;
314 return false;
315 }
initial.commitd7cae122008-07-26 21:49:38316 }
[email protected]1d8c2702008-08-19 23:39:32317 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11318#elif defined(OS_POSIX)
319 log_file = fopen(log_file_name->c_str(), "a");
320 if (log_file == NULL)
321 return false;
[email protected]f6abeba2008-08-08 13:27:28322#endif
[email protected]1d8c2702008-08-19 23:39:32323 }
324
initial.commitd7cae122008-07-26 21:49:38325 return true;
326}
327
[email protected]ff3d0c32010-08-23 19:57:46328void BaseInitLoggingImpl(const PathChar* new_log_file,
329 LoggingDestination logging_dest,
330 LogLockingState lock_log,
331 OldFileDeletionState delete_old) {
[email protected]bb975362009-01-21 01:00:22332 g_enable_dcheck =
333 CommandLine::ForCurrentProcess()->HasSwitch(switches::kEnableDCHECK);
[email protected]5b84fe32010-09-14 22:24:55334 LoggingLock::Init(lock_log, new_log_file);
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
[email protected]cba21962010-08-31 22:35:55358 InitializeLogFileHandle();
[email protected]5b84fe32010-09-14 22:24:55359
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]107bc0f12008-08-26 17:48:18572#endif
[email protected]469006c2010-09-24 15:43:06573 fprintf(stderr, "%s", str_newline.c_str());
574 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31575 } else if (severity_ >= kAlwaysPrintErrorLevel) {
576 // When we're only outputting to a log file, above a certain log level, we
577 // should still output to stderr so that we can better detect and diagnose
578 // problems with unit tests, especially on the buildbots.
579 fprintf(stderr, "%s", str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02580 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28581 }
[email protected]52a261f2009-03-03 15:01:12582
[email protected]5b84fe32010-09-14 22:24:55583 // We can have multiple threads and/or processes, so try to prevent them
584 // from clobbering each other's writes.
585 // If the client app did not call InitLogging, and the lock has not
586 // been created do it now. We do this on demand, but if two threads try
587 // to do this at the same time, there will be a race condition to create
588 // the lock. This is why InitLogging should be called from the main
589 // thread at the beginning of execution.
590 LoggingLock::Init(LOCK_LOG_FILE, NULL);
initial.commitd7cae122008-07-26 21:49:38591 // write to log file
592 if (logging_destination != LOG_NONE &&
[email protected]5b84fe32010-09-14 22:24:55593 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
594 LoggingLock logging_lock;
595 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28596#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55597 SetFilePointer(log_file, 0, 0, SEEK_END);
598 DWORD num_written;
599 WriteFile(log_file,
600 static_cast<const void*>(str_newline.c_str()),
601 static_cast<DWORD>(str_newline.length()),
602 &num_written,
603 NULL);
[email protected]cba21962010-08-31 22:35:55604#else
[email protected]5b84fe32010-09-14 22:24:55605 fprintf(log_file, "%s", str_newline.c_str());
606 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55607#endif
initial.commitd7cae122008-07-26 21:49:38608 }
609 }
610
611 if (severity_ == LOG_FATAL) {
612 // display a message or break into the debugger on a fatal error
[email protected]1ffe08c12008-08-13 11:15:11613 if (DebugUtil::BeingDebugged()) {
614 DebugUtil::BreakDebugger();
615 } else {
initial.commitd7cae122008-07-26 21:49:38616 if (log_assert_handler) {
617 // make a copy of the string for the handler out of paranoia
618 log_assert_handler(std::string(stream_.str()));
619 } else {
[email protected]4d5901272008-11-06 00:33:50620 // Don't use the string with the newline, get a fresh version to send to
621 // the debug message process. We also don't display assertions to the
622 // user in release mode. The enduser can't do anything with this
623 // information, and displaying message boxes when the application is
624 // hosed can cause additional problems.
625#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22626 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50627#endif
initial.commitd7cae122008-07-26 21:49:38628 // Crash the process to generate a dump.
[email protected]1ffe08c12008-08-13 11:15:11629 DebugUtil::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38630 }
631 }
[email protected]fb62a532009-02-12 01:19:05632 } else if (severity_ == LOG_ERROR_REPORT) {
633 // We are here only if the user runs with --enable-dcheck in release mode.
634 if (log_report_handler) {
635 log_report_handler(std::string(stream_.str()));
636 } else {
[email protected]d81baca42010-03-01 13:10:22637 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05638 }
initial.commitd7cae122008-07-26 21:49:38639 }
640}
641
[email protected]d8617a62009-10-09 23:52:20642#if defined(OS_WIN)
643// This has already been defined in the header, but defining it again as DWORD
644// ensures that the type used in the header is equivalent to DWORD. If not,
645// the redefinition is a compile error.
646typedef DWORD SystemErrorCode;
647#endif
648
649SystemErrorCode GetLastSystemErrorCode() {
650#if defined(OS_WIN)
651 return ::GetLastError();
652#elif defined(OS_POSIX)
653 return errno;
654#else
655#error Not implemented
656#endif
657}
658
659#if defined(OS_WIN)
660Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
661 int line,
662 LogSeverity severity,
663 SystemErrorCode err,
664 const char* module)
665 : err_(err),
666 module_(module),
667 log_message_(file, line, severity) {
668}
669
670Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
671 int line,
672 LogSeverity severity,
673 SystemErrorCode err)
674 : err_(err),
675 module_(NULL),
676 log_message_(file, line, severity) {
677}
678
679Win32ErrorLogMessage::~Win32ErrorLogMessage() {
680 const int error_message_buffer_size = 256;
681 char msgbuf[error_message_buffer_size];
682 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
683 HMODULE hmod;
684 if (module_) {
685 hmod = GetModuleHandleA(module_);
686 if (hmod) {
687 flags |= FORMAT_MESSAGE_FROM_HMODULE;
688 } else {
689 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
690 // so it will not call GetModuleHandle, so recursive errors are
691 // impossible.
692 DPLOG(WARNING) << "Couldn't open module " << module_
693 << " for error message query";
694 }
695 } else {
696 hmod = NULL;
697 }
698 DWORD len = FormatMessageA(flags,
699 hmod,
700 err_,
701 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
702 msgbuf,
703 sizeof(msgbuf) / sizeof(msgbuf[0]),
704 NULL);
705 if (len) {
706 while ((len > 0) &&
707 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
708 msgbuf[--len] = 0;
709 }
710 stream() << ": " << msgbuf;
711 } else {
712 stream() << ": Error " << GetLastError() << " while retrieving error "
713 << err_;
714 }
715}
716#elif defined(OS_POSIX)
717ErrnoLogMessage::ErrnoLogMessage(const char* file,
718 int line,
719 LogSeverity severity,
720 SystemErrorCode err)
721 : err_(err),
722 log_message_(file, line, severity) {
723}
724
725ErrnoLogMessage::~ErrnoLogMessage() {
726 stream() << ": " << safe_strerror(err_);
727}
728#endif // OS_WIN
729
initial.commitd7cae122008-07-26 21:49:38730void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55731 LoggingLock logging_lock;
732
initial.commitd7cae122008-07-26 21:49:38733 if (!log_file)
734 return;
735
[email protected]f6abeba2008-08-08 13:27:28736 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38737 log_file = NULL;
738}
739
[email protected]e36ddc82009-12-08 04:22:50740void RawLog(int level, const char* message) {
741 if (level >= min_log_level) {
742 size_t bytes_written = 0;
743 const size_t message_len = strlen(message);
744 int rv;
745 while (bytes_written < message_len) {
746 rv = HANDLE_EINTR(
747 write(STDERR_FILENO, message + bytes_written,
748 message_len - bytes_written));
749 if (rv < 0) {
750 // Give up, nothing we can do now.
751 break;
752 }
753 bytes_written += rv;
754 }
755
756 if (message_len > 0 && message[message_len - 1] != '\n') {
757 do {
758 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
759 if (rv < 0) {
760 // Give up, nothing we can do now.
761 break;
762 }
763 } while (rv != 1);
764 }
765 }
766
767 if (level == LOG_FATAL)
768 DebugUtil::BreakDebugger();
769}
770
[email protected]96fd0032009-04-24 00:13:08771} // namespace logging
initial.commitd7cae122008-07-26 21:49:38772
773std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20774 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38775}