blob: f0c6217cbdd823288855b27bd125e934b90fdd00 [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]99b7c57f2010-09-29 19:26:3654#include "base/vlog.h"
[email protected]52a261f2009-03-03 15:01:1255
initial.commitd7cae122008-07-26 21:49:3856namespace logging {
57
58bool g_enable_dcheck = false;
[email protected]99b7c57f2010-09-29 19:26:3659VlogInfo* g_vlog_info = NULL;
initial.commitd7cae122008-07-26 21:49:3860
61const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
[email protected]fb62a532009-02-12 01:19:0562 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
initial.commitd7cae122008-07-26 21:49:3863
64int min_log_level = 0;
[email protected]1d8c2702008-08-19 23:39:3265
66// The default set here for logging_destination will only be used if
67// InitLogging is not called. On Windows, use a file next to the exe;
68// on POSIX platforms, where it may not even be possible to locate the
69// executable on disk, use stderr.
[email protected]4c0040c2008-08-15 01:04:1170#if defined(OS_WIN)
[email protected]fe613522008-08-22 17:09:3471LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
[email protected]4c0040c2008-08-15 01:04:1172#elif defined(OS_POSIX)
[email protected]1d8c2702008-08-19 23:39:3273LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
[email protected]4c0040c2008-08-15 01:04:1174#endif
initial.commitd7cae122008-07-26 21:49:3875
[email protected]a33c9892008-08-25 20:10:3176// For LOG_ERROR and above, always print to stderr.
77const int kAlwaysPrintErrorLevel = LOG_ERROR;
78
[email protected]614e9fa2008-08-11 22:52:5979// Which log file to use? This is initialized by InitLogging or
initial.commitd7cae122008-07-26 21:49:3880// will be lazily initialized to the default value when it is
81// first needed.
[email protected]f6abeba2008-08-08 13:27:2882#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:5983typedef std::wstring PathString;
[email protected]f6abeba2008-08-08 13:27:2884#else
[email protected]614e9fa2008-08-11 22:52:5985typedef std::string PathString;
[email protected]f6abeba2008-08-08 13:27:2886#endif
[email protected]614e9fa2008-08-11 22:52:5987PathString* log_file_name = NULL;
initial.commitd7cae122008-07-26 21:49:3888
89// this file is lazily opened and the handle may be NULL
[email protected]f6abeba2008-08-08 13:27:2890FileHandle log_file = NULL;
initial.commitd7cae122008-07-26 21:49:3891
92// what should be prepended to each message?
93bool log_process_id = false;
94bool log_thread_id = false;
95bool log_timestamp = true;
96bool log_tickcount = false;
97
[email protected]81e0a852010-08-17 00:38:1298// Should we pop up fatal debug messages in a dialog?
99bool show_error_dialogs = false;
100
initial.commitd7cae122008-07-26 21:49:38101// An assert handler override specified by the client to be called instead of
[email protected]fb62a532009-02-12 01:19:05102// the debug message dialog and process termination.
initial.commitd7cae122008-07-26 21:49:38103LogAssertHandlerFunction log_assert_handler = NULL;
[email protected]fb62a532009-02-12 01:19:05104// An report handler override specified by the client to be called instead of
105// the debug message dialog.
106LogReportHandlerFunction log_report_handler = NULL;
[email protected]2b07b8412009-11-25 15:26:34107// A log message handler that gets notified of every log message we process.
108LogMessageHandlerFunction log_message_handler = NULL;
initial.commitd7cae122008-07-26 21:49:38109
[email protected]f6abeba2008-08-08 13:27:28110// Helper functions to wrap platform differences.
111
[email protected]f8588472008-11-05 23:17:24112int32 CurrentProcessId() {
113#if defined(OS_WIN)
114 return GetCurrentProcessId();
115#elif defined(OS_POSIX)
116 return getpid();
117#endif
118}
119
120int32 CurrentThreadId() {
121#if defined(OS_WIN)
122 return GetCurrentThreadId();
123#elif defined(OS_MACOSX)
124 return mach_thread_self();
[email protected]052f1b52008-11-06 21:43:07125#elif defined(OS_LINUX)
126 return syscall(__NR_gettid);
[email protected]e43eddf12009-12-29 00:32:52127#elif defined(OS_FREEBSD)
128 // TODO(BSD): find a better thread ID
129 return reinterpret_cast<int64>(pthread_self());
[email protected]f8588472008-11-05 23:17:24130#endif
131}
132
133uint64 TickCount() {
134#if defined(OS_WIN)
135 return GetTickCount();
136#elif defined(OS_MACOSX)
137 return mach_absolute_time();
[email protected]e43eddf12009-12-29 00:32:52138#elif defined(OS_POSIX)
[email protected]052f1b52008-11-06 21:43:07139 struct timespec ts;
140 clock_gettime(CLOCK_MONOTONIC, &ts);
141
142 uint64 absolute_micro =
143 static_cast<int64>(ts.tv_sec) * 1000000 +
144 static_cast<int64>(ts.tv_nsec) / 1000;
145
146 return absolute_micro;
[email protected]f8588472008-11-05 23:17:24147#endif
148}
149
[email protected]f6abeba2008-08-08 13:27:28150void CloseFile(FileHandle log) {
151#if defined(OS_WIN)
152 CloseHandle(log);
153#else
154 fclose(log);
155#endif
156}
157
[email protected]614e9fa2008-08-11 22:52:59158void DeleteFilePath(const PathString& log_name) {
[email protected]f6abeba2008-08-08 13:27:28159#if defined(OS_WIN)
[email protected]614e9fa2008-08-11 22:52:59160 DeleteFile(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28161#else
[email protected]614e9fa2008-08-11 22:52:59162 unlink(log_name.c_str());
[email protected]f6abeba2008-08-08 13:27:28163#endif
164}
initial.commitd7cae122008-07-26 21:49:38165
[email protected]5b84fe32010-09-14 22:24:55166void GetDefaultLogFile(PathString default_log_file) {
167#if defined(OS_WIN)
168 // On Windows we use the same path as the exe.
169 wchar_t module_name[MAX_PATH];
170 GetModuleFileName(NULL, module_name, MAX_PATH);
171 default_log_file = module_name;
172 std::wstring::size_type last_backslash =
173 default_log_file.rfind('\\', default_log_file.size());
174 if (last_backslash != std::wstring::npos)
175 default_log_file.erase(last_backslash + 1);
176 default_log_file += L"debug.log";
177#elif defined(OS_POSIX)
178 // On other platforms we just use the current directory.
179 default_log_file = "debug.log";
180#endif
181}
182
183// This class acts as a wrapper for locking the logging files.
184// LoggingLock::Init() should be called from the main thread before any logging
185// is done. Then whenever logging, be sure to have a local LoggingLock
186// instance on the stack. This will ensure that the lock is unlocked upon
187// exiting the frame.
188// LoggingLocks can not be nested.
189class LoggingLock {
190 public:
191 LoggingLock() {
192 LockLogging();
193 }
194
195 ~LoggingLock() {
196 UnlockLogging();
197 }
198
199 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
200 if (initialized)
201 return;
202 lock_log_file = lock_log;
203 if (lock_log_file == LOCK_LOG_FILE) {
204#if defined(OS_WIN)
205 if (!log_mutex) {
206 std::wstring safe_name;
207 if (new_log_file)
208 safe_name = new_log_file;
209 else
210 GetDefaultLogFile(safe_name);
211 // \ is not a legal character in mutex names so we replace \ with /
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]5b84fe32010-09-14 22:24:55296 log_file_name = new PathString();
297 GetDefaultLogFile(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38298 }
299
[email protected]1d8c2702008-08-19 23:39:32300 if (logging_destination == LOG_ONLY_TO_FILE ||
301 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
[email protected]614e9fa2008-08-11 22:52:59302#if defined(OS_WIN)
[email protected]1d8c2702008-08-19 23:39:32303 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
initial.commitd7cae122008-07-26 21:49:38304 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
305 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
306 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
[email protected]1d8c2702008-08-19 23:39:32307 // try the current directory
308 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
309 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
310 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
311 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
312 log_file = NULL;
313 return false;
314 }
initial.commitd7cae122008-07-26 21:49:38315 }
[email protected]1d8c2702008-08-19 23:39:32316 SetFilePointer(log_file, 0, 0, FILE_END);
[email protected]78c6dd62009-06-08 23:29:11317#elif defined(OS_POSIX)
318 log_file = fopen(log_file_name->c_str(), "a");
319 if (log_file == NULL)
320 return false;
[email protected]f6abeba2008-08-08 13:27:28321#endif
[email protected]1d8c2702008-08-19 23:39:32322 }
323
initial.commitd7cae122008-07-26 21:49:38324 return true;
325}
326
[email protected]ff3d0c32010-08-23 19:57:46327void BaseInitLoggingImpl(const PathChar* new_log_file,
328 LoggingDestination logging_dest,
329 LogLockingState lock_log,
330 OldFileDeletionState delete_old) {
[email protected]99b7c57f2010-09-29 19:26:36331 CommandLine* command_line = CommandLine::ForCurrentProcess();
[email protected]bb975362009-01-21 01:00:22332 g_enable_dcheck =
[email protected]99b7c57f2010-09-29 19:26:36333 command_line->HasSwitch(switches::kEnableDCHECK);
334 delete g_vlog_info;
335 g_vlog_info = NULL;
336 // Don't bother initializing g_vlog_info unless we use one of the
337 // vlog switches.
338 if (command_line->HasSwitch(switches::kV) ||
339 command_line->HasSwitch(switches::kVModule)) {
340 g_vlog_info =
341 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
342 command_line->GetSwitchValueASCII(switches::kVModule));
343 }
344
[email protected]5b84fe32010-09-14 22:24:55345 LoggingLock::Init(lock_log, new_log_file);
346
347 LoggingLock logging_lock;
initial.commitd7cae122008-07-26 21:49:38348
349 if (log_file) {
350 // calling InitLogging twice or after some log call has already opened the
351 // default log file will re-initialize to the new options
[email protected]f6abeba2008-08-08 13:27:28352 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38353 log_file = NULL;
354 }
355
initial.commitd7cae122008-07-26 21:49:38356 logging_destination = logging_dest;
357
358 // ignore file options if logging is disabled or only to system
359 if (logging_destination == LOG_NONE ||
360 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
361 return;
362
[email protected]614e9fa2008-08-11 22:52:59363 if (!log_file_name)
364 log_file_name = new PathString();
365 *log_file_name = new_log_file;
initial.commitd7cae122008-07-26 21:49:38366 if (delete_old == DELETE_OLD_LOG_FILE)
[email protected]614e9fa2008-08-11 22:52:59367 DeleteFilePath(*log_file_name);
initial.commitd7cae122008-07-26 21:49:38368
[email protected]cba21962010-08-31 22:35:55369 InitializeLogFileHandle();
[email protected]5b84fe32010-09-14 22:24:55370
initial.commitd7cae122008-07-26 21:49:38371}
372
373void SetMinLogLevel(int level) {
374 min_log_level = level;
375}
376
377int GetMinLogLevel() {
378 return min_log_level;
379}
380
[email protected]99b7c57f2010-09-29 19:26:36381int GetVlogLevelHelper(const char* file, size_t N) {
382 DCHECK_GT(N, 0U);
383 return g_vlog_info ?
384 g_vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
385 VlogInfo::kDefaultVlogLevel;
386}
387
initial.commitd7cae122008-07-26 21:49:38388void SetLogItems(bool enable_process_id, bool enable_thread_id,
389 bool enable_timestamp, bool enable_tickcount) {
390 log_process_id = enable_process_id;
391 log_thread_id = enable_thread_id;
392 log_timestamp = enable_timestamp;
393 log_tickcount = enable_tickcount;
394}
395
[email protected]81e0a852010-08-17 00:38:12396void SetShowErrorDialogs(bool enable_dialogs) {
397 show_error_dialogs = enable_dialogs;
398}
399
initial.commitd7cae122008-07-26 21:49:38400void SetLogAssertHandler(LogAssertHandlerFunction handler) {
401 log_assert_handler = handler;
402}
403
[email protected]fb62a532009-02-12 01:19:05404void SetLogReportHandler(LogReportHandlerFunction handler) {
405 log_report_handler = handler;
406}
407
[email protected]2b07b8412009-11-25 15:26:34408void SetLogMessageHandler(LogMessageHandlerFunction handler) {
409 log_message_handler = handler;
410}
411
[email protected]6d445d32010-09-30 19:10:03412// MSVC doesn't like complex extern templates and DLLs.
413#if !defined(COMPILER_MSVC)
414// Explicit instantiations for commonly used comparisons.
415template std::string* MakeCheckOpString<int, int>(
416 const int&, const int&, const char* names);
417template std::string* MakeCheckOpString<unsigned long, unsigned long>(
418 const unsigned long&, const unsigned long&, const char* names);
419template std::string* MakeCheckOpString<unsigned long, unsigned int>(
420 const unsigned long&, const unsigned int&, const char* names);
421template std::string* MakeCheckOpString<unsigned int, unsigned long>(
422 const unsigned int&, const unsigned long&, const char* names);
423template std::string* MakeCheckOpString<std::string, std::string>(
424 const std::string&, const std::string&, const char* name);
425#endif
[email protected]2b07b8412009-11-25 15:26:34426
[email protected]d81baca42010-03-01 13:10:22427// Displays a message box to the user with the error message in it.
428// Used for fatal messages, where we close the app simultaneously.
429void DisplayDebugMessageInDialog(const std::string& str) {
initial.commitd7cae122008-07-26 21:49:38430 if (str.empty())
431 return;
432
[email protected]81e0a852010-08-17 00:38:12433 if (!show_error_dialogs)
[email protected]846ed9c32010-07-29 20:33:44434 return;
435
[email protected]f6abeba2008-08-08 13:27:28436#if defined(OS_WIN)
[email protected]d81baca42010-03-01 13:10:22437 // For Windows programs, it's possible that the message loop is
438 // messed up on a fatal error, and creating a MessageBox will cause
439 // that message loop to be run. Instead, we try to spawn another
440 // process that displays its command line. We look for "Debug
441 // Message.exe" in the same directory as the application. If it
442 // exists, we use it, otherwise, we use a regular message box.
initial.commitd7cae122008-07-26 21:49:38443 wchar_t prog_name[MAX_PATH];
444 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
445 wchar_t* backslash = wcsrchr(prog_name, '\\');
446 if (backslash)
447 backslash[1] = 0;
448 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
449
[email protected]047a03f2009-10-07 02:10:20450 std::wstring cmdline = UTF8ToWide(str);
[email protected]3ca4214c12009-03-25 22:12:02451 if (cmdline.empty())
452 return;
initial.commitd7cae122008-07-26 21:49:38453
454 STARTUPINFO startup_info;
455 memset(&startup_info, 0, sizeof(startup_info));
456 startup_info.cb = sizeof(startup_info);
457
458 PROCESS_INFORMATION process_info;
[email protected]3ca4214c12009-03-25 22:12:02459 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
initial.commitd7cae122008-07-26 21:49:38460 NULL, &startup_info, &process_info)) {
461 WaitForSingleObject(process_info.hProcess, INFINITE);
462 CloseHandle(process_info.hThread);
463 CloseHandle(process_info.hProcess);
464 } else {
465 // debug process broken, let's just do a message box
[email protected]3ca4214c12009-03-25 22:12:02466 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
initial.commitd7cae122008-07-26 21:49:38467 MB_OK | MB_ICONHAND | MB_TOPMOST);
468 }
[email protected]81e0a852010-08-17 00:38:12469#elif defined(USE_X11) && !defined(OS_CHROMEOS)
[email protected]d81baca42010-03-01 13:10:22470 // Shell out to xmessage, which behaves like debug_message.exe, but is
471 // way more retro. We could use zenity/kdialog but then we're starting
472 // to get into needing to check the desktop env and this dialog should
473 // only be coming up in Very Bad situations.
474 std::vector<std::string> argv;
475 argv.push_back("xmessage");
476 argv.push_back(str);
477 base::LaunchApp(argv, base::file_handle_mapping_vector(), true /* wait */,
478 NULL);
[email protected]f6abeba2008-08-08 13:27:28479#else
[email protected]d81baca42010-03-01 13:10:22480 // http://code.google.com/p/chromium/issues/detail?id=37026
481 NOTIMPLEMENTED();
[email protected]f6abeba2008-08-08 13:27:28482#endif
initial.commitd7cae122008-07-26 21:49:38483}
484
[email protected]3f85caa2009-04-14 16:52:11485#if defined(OS_WIN)
486LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
487}
488
489LogMessage::SaveLastError::~SaveLastError() {
490 ::SetLastError(last_error_);
491}
492#endif // defined(OS_WIN)
493
initial.commitd7cae122008-07-26 21:49:38494LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
495 int ctr)
496 : severity_(severity) {
497 Init(file, line);
498}
499
500LogMessage::LogMessage(const char* file, int line, const CheckOpString& result)
501 : severity_(LOG_FATAL) {
502 Init(file, line);
503 stream_ << "Check failed: " << (*result.str_);
504}
505
[email protected]fb62a532009-02-12 01:19:05506LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
507 const CheckOpString& result)
508 : severity_(severity) {
509 Init(file, line);
510 stream_ << "Check failed: " << (*result.str_);
511}
512
initial.commitd7cae122008-07-26 21:49:38513LogMessage::LogMessage(const char* file, int line)
514 : severity_(LOG_INFO) {
515 Init(file, line);
516}
517
518LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
519 : severity_(severity) {
520 Init(file, line);
521}
522
523// writes the common header info to the stream
524void LogMessage::Init(const char* file, int line) {
525 // log only the filename
526 const char* last_slash = strrchr(file, '\\');
527 if (last_slash)
528 file = last_slash + 1;
529
530 // TODO(darin): It might be nice if the columns were fixed width.
531
532 stream_ << '[';
533 if (log_process_id)
[email protected]f8588472008-11-05 23:17:24534 stream_ << CurrentProcessId() << ':';
initial.commitd7cae122008-07-26 21:49:38535 if (log_thread_id)
[email protected]f8588472008-11-05 23:17:24536 stream_ << CurrentThreadId() << ':';
initial.commitd7cae122008-07-26 21:49:38537 if (log_timestamp) {
[email protected]defcd8f32009-05-13 00:03:43538 time_t t = time(NULL);
initial.commitd7cae122008-07-26 21:49:38539 struct tm local_time = {0};
[email protected]defcd8f32009-05-13 00:03:43540#if _MSC_VER >= 1400
initial.commitd7cae122008-07-26 21:49:38541 localtime_s(&local_time, &t);
initial.commitd7cae122008-07-26 21:49:38542#else
[email protected]defcd8f32009-05-13 00:03:43543 localtime_r(&t, &local_time);
initial.commitd7cae122008-07-26 21:49:38544#endif
[email protected]defcd8f32009-05-13 00:03:43545 struct tm* tm_time = &local_time;
initial.commitd7cae122008-07-26 21:49:38546 stream_ << std::setfill('0')
547 << std::setw(2) << 1 + tm_time->tm_mon
548 << std::setw(2) << tm_time->tm_mday
549 << '/'
550 << std::setw(2) << tm_time->tm_hour
551 << std::setw(2) << tm_time->tm_min
552 << std::setw(2) << tm_time->tm_sec
553 << ':';
554 }
555 if (log_tickcount)
[email protected]f8588472008-11-05 23:17:24556 stream_ << TickCount() << ':';
[email protected]52a261f2009-03-03 15:01:12557 stream_ << log_severity_names[severity_] << ":" << file <<
558 "(" << line << ")] ";
initial.commitd7cae122008-07-26 21:49:38559
560 message_start_ = stream_.tellp();
561}
562
563LogMessage::~LogMessage() {
564 // TODO(brettw) modify the macros so that nothing is executed when the log
565 // level is too high.
566 if (severity_ < min_log_level)
567 return;
568
[email protected]d1ccc35a2010-03-24 05:03:24569#ifndef NDEBUG
570 if (severity_ == LOG_FATAL) {
571 // Include a stack trace on a fatal.
572 StackTrace trace;
573 stream_ << std::endl; // Newline to separate from log message.
574 trace.OutputToStream(&stream_);
575 }
[email protected]1d8c2702008-08-19 23:39:32576#endif
[email protected]d1ccc35a2010-03-24 05:03:24577 stream_ << std::endl;
578 std::string str_newline(stream_.str());
579
[email protected]2b07b8412009-11-25 15:26:34580 // Give any log message handler first dibs on the message.
581 if (log_message_handler && log_message_handler(severity_, str_newline))
582 return;
initial.commitd7cae122008-07-26 21:49:38583
initial.commitd7cae122008-07-26 21:49:38584 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
[email protected]f6abeba2008-08-08 13:27:28585 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
586#if defined(OS_WIN)
initial.commitd7cae122008-07-26 21:49:38587 OutputDebugStringA(str_newline.c_str());
[email protected]107bc0f12008-08-26 17:48:18588#endif
[email protected]469006c2010-09-24 15:43:06589 fprintf(stderr, "%s", str_newline.c_str());
590 fflush(stderr);
[email protected]a33c9892008-08-25 20:10:31591 } else if (severity_ >= kAlwaysPrintErrorLevel) {
592 // When we're only outputting to a log file, above a certain log level, we
593 // should still output to stderr so that we can better detect and diagnose
594 // problems with unit tests, especially on the buildbots.
595 fprintf(stderr, "%s", str_newline.c_str());
[email protected]1ce41052009-12-02 00:34:02596 fflush(stderr);
[email protected]f6abeba2008-08-08 13:27:28597 }
[email protected]52a261f2009-03-03 15:01:12598
[email protected]5b84fe32010-09-14 22:24:55599 // We can have multiple threads and/or processes, so try to prevent them
600 // from clobbering each other's writes.
601 // If the client app did not call InitLogging, and the lock has not
602 // been created do it now. We do this on demand, but if two threads try
603 // to do this at the same time, there will be a race condition to create
604 // the lock. This is why InitLogging should be called from the main
605 // thread at the beginning of execution.
606 LoggingLock::Init(LOCK_LOG_FILE, NULL);
initial.commitd7cae122008-07-26 21:49:38607 // write to log file
608 if (logging_destination != LOG_NONE &&
[email protected]5b84fe32010-09-14 22:24:55609 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
610 LoggingLock logging_lock;
611 if (InitializeLogFileHandle()) {
[email protected]f6abeba2008-08-08 13:27:28612#if defined(OS_WIN)
[email protected]5b84fe32010-09-14 22:24:55613 SetFilePointer(log_file, 0, 0, SEEK_END);
614 DWORD num_written;
615 WriteFile(log_file,
616 static_cast<const void*>(str_newline.c_str()),
617 static_cast<DWORD>(str_newline.length()),
618 &num_written,
619 NULL);
[email protected]cba21962010-08-31 22:35:55620#else
[email protected]5b84fe32010-09-14 22:24:55621 fprintf(log_file, "%s", str_newline.c_str());
622 fflush(log_file);
[email protected]cba21962010-08-31 22:35:55623#endif
initial.commitd7cae122008-07-26 21:49:38624 }
625 }
626
627 if (severity_ == LOG_FATAL) {
628 // display a message or break into the debugger on a fatal error
[email protected]1ffe08c12008-08-13 11:15:11629 if (DebugUtil::BeingDebugged()) {
630 DebugUtil::BreakDebugger();
631 } else {
initial.commitd7cae122008-07-26 21:49:38632 if (log_assert_handler) {
633 // make a copy of the string for the handler out of paranoia
634 log_assert_handler(std::string(stream_.str()));
635 } else {
[email protected]4d5901272008-11-06 00:33:50636 // Don't use the string with the newline, get a fresh version to send to
637 // the debug message process. We also don't display assertions to the
638 // user in release mode. The enduser can't do anything with this
639 // information, and displaying message boxes when the application is
640 // hosed can cause additional problems.
641#ifndef NDEBUG
[email protected]d81baca42010-03-01 13:10:22642 DisplayDebugMessageInDialog(stream_.str());
[email protected]4d5901272008-11-06 00:33:50643#endif
initial.commitd7cae122008-07-26 21:49:38644 // Crash the process to generate a dump.
[email protected]1ffe08c12008-08-13 11:15:11645 DebugUtil::BreakDebugger();
initial.commitd7cae122008-07-26 21:49:38646 }
647 }
[email protected]fb62a532009-02-12 01:19:05648 } else if (severity_ == LOG_ERROR_REPORT) {
649 // We are here only if the user runs with --enable-dcheck in release mode.
650 if (log_report_handler) {
651 log_report_handler(std::string(stream_.str()));
652 } else {
[email protected]d81baca42010-03-01 13:10:22653 DisplayDebugMessageInDialog(stream_.str());
[email protected]fb62a532009-02-12 01:19:05654 }
initial.commitd7cae122008-07-26 21:49:38655 }
656}
657
[email protected]d8617a62009-10-09 23:52:20658#if defined(OS_WIN)
659// This has already been defined in the header, but defining it again as DWORD
660// ensures that the type used in the header is equivalent to DWORD. If not,
661// the redefinition is a compile error.
662typedef DWORD SystemErrorCode;
663#endif
664
665SystemErrorCode GetLastSystemErrorCode() {
666#if defined(OS_WIN)
667 return ::GetLastError();
668#elif defined(OS_POSIX)
669 return errno;
670#else
671#error Not implemented
672#endif
673}
674
675#if defined(OS_WIN)
676Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
677 int line,
678 LogSeverity severity,
679 SystemErrorCode err,
680 const char* module)
681 : err_(err),
682 module_(module),
683 log_message_(file, line, severity) {
684}
685
686Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
687 int line,
688 LogSeverity severity,
689 SystemErrorCode err)
690 : err_(err),
691 module_(NULL),
692 log_message_(file, line, severity) {
693}
694
695Win32ErrorLogMessage::~Win32ErrorLogMessage() {
696 const int error_message_buffer_size = 256;
697 char msgbuf[error_message_buffer_size];
698 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM;
699 HMODULE hmod;
700 if (module_) {
701 hmod = GetModuleHandleA(module_);
702 if (hmod) {
703 flags |= FORMAT_MESSAGE_FROM_HMODULE;
704 } else {
705 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
706 // so it will not call GetModuleHandle, so recursive errors are
707 // impossible.
708 DPLOG(WARNING) << "Couldn't open module " << module_
709 << " for error message query";
710 }
711 } else {
712 hmod = NULL;
713 }
714 DWORD len = FormatMessageA(flags,
715 hmod,
716 err_,
717 MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
718 msgbuf,
719 sizeof(msgbuf) / sizeof(msgbuf[0]),
720 NULL);
721 if (len) {
722 while ((len > 0) &&
723 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
724 msgbuf[--len] = 0;
725 }
726 stream() << ": " << msgbuf;
727 } else {
728 stream() << ": Error " << GetLastError() << " while retrieving error "
729 << err_;
730 }
731}
732#elif defined(OS_POSIX)
733ErrnoLogMessage::ErrnoLogMessage(const char* file,
734 int line,
735 LogSeverity severity,
736 SystemErrorCode err)
737 : err_(err),
738 log_message_(file, line, severity) {
739}
740
741ErrnoLogMessage::~ErrnoLogMessage() {
742 stream() << ": " << safe_strerror(err_);
743}
744#endif // OS_WIN
745
initial.commitd7cae122008-07-26 21:49:38746void CloseLogFile() {
[email protected]5b84fe32010-09-14 22:24:55747 LoggingLock logging_lock;
748
initial.commitd7cae122008-07-26 21:49:38749 if (!log_file)
750 return;
751
[email protected]f6abeba2008-08-08 13:27:28752 CloseFile(log_file);
initial.commitd7cae122008-07-26 21:49:38753 log_file = NULL;
754}
755
[email protected]e36ddc82009-12-08 04:22:50756void RawLog(int level, const char* message) {
757 if (level >= min_log_level) {
758 size_t bytes_written = 0;
759 const size_t message_len = strlen(message);
760 int rv;
761 while (bytes_written < message_len) {
762 rv = HANDLE_EINTR(
763 write(STDERR_FILENO, message + bytes_written,
764 message_len - bytes_written));
765 if (rv < 0) {
766 // Give up, nothing we can do now.
767 break;
768 }
769 bytes_written += rv;
770 }
771
772 if (message_len > 0 && message[message_len - 1] != '\n') {
773 do {
774 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
775 if (rv < 0) {
776 // Give up, nothing we can do now.
777 break;
778 }
779 } while (rv != 1);
780 }
781 }
782
783 if (level == LOG_FATAL)
784 DebugUtil::BreakDebugger();
785}
786
[email protected]96fd0032009-04-24 00:13:08787} // namespace logging
initial.commitd7cae122008-07-26 21:49:38788
789std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
[email protected]047a03f2009-10-07 02:10:20790 return out << WideToUTF8(std::wstring(wstr));
initial.commitd7cae122008-07-26 21:49:38791}