WebKit merge 94748:94770
[chromium-blink-merge.git] / base / logging.cc
blob11ad9357d6afbf26050b5abbd35c0a1b2c70f4e7
1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/logging.h"
7 #if defined(OS_WIN)
8 #include <io.h>
9 #include <windows.h>
10 typedef HANDLE FileHandle;
11 typedef HANDLE MutexHandle;
12 // 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
16 #elif defined(OS_MACOSX)
17 #include <mach/mach.h>
18 #include <mach/mach_time.h>
19 #include <mach-o/dyld.h>
20 #elif defined(OS_POSIX)
21 #if defined(OS_NACL)
22 #include <sys/nacl_syscalls.h>
23 #include <sys/time.h> // timespec doesn't seem to be in <time.h>
24 #else
25 #include <sys/syscall.h>
26 #endif
27 #include <time.h>
28 #endif
30 #if defined(OS_POSIX)
31 #include <errno.h>
32 #include <pthread.h>
33 #include <stdlib.h>
34 #include <stdio.h>
35 #include <string.h>
36 #include <unistd.h>
37 #define MAX_PATH PATH_MAX
38 typedef FILE* FileHandle;
39 typedef pthread_mutex_t* MutexHandle;
40 #endif
42 #include <algorithm>
43 #include <cstring>
44 #include <ctime>
45 #include <iomanip>
46 #include <ostream>
48 #include "base/base_switches.h"
49 #include "base/command_line.h"
50 #include "base/debug/debugger.h"
51 #include "base/debug/stack_trace.h"
52 #include "base/eintr_wrapper.h"
53 #include "base/string_piece.h"
54 #include "base/synchronization/lock_impl.h"
55 #include "base/utf_string_conversions.h"
56 #include "base/vlog.h"
57 #if defined(OS_POSIX)
58 #include "base/safe_strerror_posix.h"
59 #endif
61 #if defined(OS_ANDROID)
62 #include <android/log.h>
63 #endif
65 namespace logging {
67 DcheckState g_dcheck_state = DISABLE_DCHECK_FOR_NON_OFFICIAL_RELEASE_BUILDS;
68 VlogInfo* g_vlog_info = NULL;
70 const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
71 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
73 int min_log_level = 0;
75 // The default set here for logging_destination will only be used if
76 // InitLogging is not called. On Windows, use a file next to the exe;
77 // on POSIX platforms, where it may not even be possible to locate the
78 // executable on disk, use stderr.
79 #if defined(OS_WIN)
80 LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
81 #elif defined(OS_POSIX)
82 LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
83 #endif
85 // For LOG_ERROR and above, always print to stderr.
86 const int kAlwaysPrintErrorLevel = LOG_ERROR;
88 // Which log file to use? This is initialized by InitLogging or
89 // will be lazily initialized to the default value when it is
90 // first needed.
91 #if defined(OS_WIN)
92 typedef std::wstring PathString;
93 #else
94 typedef std::string PathString;
95 #endif
96 PathString* log_file_name = NULL;
98 // this file is lazily opened and the handle may be NULL
99 FileHandle log_file = NULL;
101 // what should be prepended to each message?
102 bool log_process_id = false;
103 bool log_thread_id = false;
104 bool log_timestamp = true;
105 bool log_tickcount = false;
107 // Should we pop up fatal debug messages in a dialog?
108 bool show_error_dialogs = false;
110 // An assert handler override specified by the client to be called instead of
111 // the debug message dialog and process termination.
112 LogAssertHandlerFunction log_assert_handler = NULL;
113 // An report handler override specified by the client to be called instead of
114 // the debug message dialog.
115 LogReportHandlerFunction log_report_handler = NULL;
116 // A log message handler that gets notified of every log message we process.
117 LogMessageHandlerFunction log_message_handler = NULL;
119 // Helper functions to wrap platform differences.
121 int32 CurrentProcessId() {
122 #if defined(OS_WIN)
123 return GetCurrentProcessId();
124 #elif defined(OS_POSIX)
125 return getpid();
126 #endif
129 int32 CurrentThreadId() {
130 #if defined(OS_WIN)
131 return GetCurrentThreadId();
132 #elif defined(OS_MACOSX)
133 return mach_thread_self();
134 #elif defined(OS_LINUX)
135 return syscall(__NR_gettid);
136 #elif defined(OS_ANDROID)
137 return gettid();
138 #elif defined(OS_FREEBSD)
139 // TODO(BSD): find a better thread ID
140 return reinterpret_cast<int64>(pthread_self());
141 #elif defined(OS_NACL)
142 return pthread_self();
143 #endif
146 uint64 TickCount() {
147 #if defined(OS_WIN)
148 return GetTickCount();
149 #elif defined(OS_MACOSX)
150 return mach_absolute_time();
151 #elif defined(OS_NACL)
152 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
153 // So we have to use clock() for now.
154 return clock();
155 #elif defined(OS_POSIX)
156 struct timespec ts;
157 clock_gettime(CLOCK_MONOTONIC, &ts);
159 uint64 absolute_micro =
160 static_cast<int64>(ts.tv_sec) * 1000000 +
161 static_cast<int64>(ts.tv_nsec) / 1000;
163 return absolute_micro;
164 #endif
167 void CloseFile(FileHandle log) {
168 #if defined(OS_WIN)
169 CloseHandle(log);
170 #else
171 fclose(log);
172 #endif
175 void DeleteFilePath(const PathString& log_name) {
176 #if defined(OS_WIN)
177 DeleteFile(log_name.c_str());
178 #else
179 unlink(log_name.c_str());
180 #endif
183 PathString GetDefaultLogFile() {
184 #if defined(OS_WIN)
185 // On Windows we use the same path as the exe.
186 wchar_t module_name[MAX_PATH];
187 GetModuleFileName(NULL, module_name, MAX_PATH);
189 PathString log_file = module_name;
190 PathString::size_type last_backslash =
191 log_file.rfind('\\', log_file.size());
192 if (last_backslash != PathString::npos)
193 log_file.erase(last_backslash + 1);
194 log_file += L"debug.log";
195 return log_file;
196 #elif defined(OS_POSIX)
197 // On other platforms we just use the current directory.
198 return PathString("debug.log");
199 #endif
202 // This class acts as a wrapper for locking the logging files.
203 // LoggingLock::Init() should be called from the main thread before any logging
204 // is done. Then whenever logging, be sure to have a local LoggingLock
205 // instance on the stack. This will ensure that the lock is unlocked upon
206 // exiting the frame.
207 // LoggingLocks can not be nested.
208 class LoggingLock {
209 public:
210 LoggingLock() {
211 LockLogging();
214 ~LoggingLock() {
215 UnlockLogging();
218 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
219 if (initialized)
220 return;
221 lock_log_file = lock_log;
222 if (lock_log_file == LOCK_LOG_FILE) {
223 #if defined(OS_WIN)
224 if (!log_mutex) {
225 std::wstring safe_name;
226 if (new_log_file)
227 safe_name = new_log_file;
228 else
229 safe_name = GetDefaultLogFile();
230 // \ is not a legal character in mutex names so we replace \ with /
231 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
232 std::wstring t(L"Global\\");
233 t.append(safe_name);
234 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
236 if (log_mutex == NULL) {
237 #if DEBUG
238 // Keep the error code for debugging
239 int error = GetLastError(); // NOLINT
240 base::debug::BreakDebugger();
241 #endif
242 // Return nicely without putting initialized to true.
243 return;
246 #endif
247 } else {
248 log_lock = new base::internal::LockImpl();
250 initialized = true;
253 private:
254 static void LockLogging() {
255 if (lock_log_file == LOCK_LOG_FILE) {
256 #if defined(OS_WIN)
257 ::WaitForSingleObject(log_mutex, INFINITE);
258 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
259 // abort the process here. UI tests might be crashy sometimes,
260 // and aborting the test binary only makes the problem worse.
261 // We also don't use LOG macros because that might lead to an infinite
262 // loop. For more info see http://crbug.com/18028.
263 #elif defined(OS_POSIX)
264 pthread_mutex_lock(&log_mutex);
265 #endif
266 } else {
267 // use the lock
268 log_lock->Lock();
272 static void UnlockLogging() {
273 if (lock_log_file == LOCK_LOG_FILE) {
274 #if defined(OS_WIN)
275 ReleaseMutex(log_mutex);
276 #elif defined(OS_POSIX)
277 pthread_mutex_unlock(&log_mutex);
278 #endif
279 } else {
280 log_lock->Unlock();
284 // The lock is used if log file locking is false. It helps us avoid problems
285 // with multiple threads writing to the log file at the same time. Use
286 // LockImpl directly instead of using Lock, because Lock makes logging calls.
287 static base::internal::LockImpl* log_lock;
289 // When we don't use a lock, we are using a global mutex. We need to do this
290 // because LockFileEx is not thread safe.
291 #if defined(OS_WIN)
292 static MutexHandle log_mutex;
293 #elif defined(OS_POSIX)
294 static pthread_mutex_t log_mutex;
295 #endif
297 static bool initialized;
298 static LogLockingState lock_log_file;
301 // static
302 bool LoggingLock::initialized = false;
303 // static
304 base::internal::LockImpl* LoggingLock::log_lock = NULL;
305 // static
306 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
308 #if defined(OS_WIN)
309 // static
310 MutexHandle LoggingLock::log_mutex = NULL;
311 #elif defined(OS_POSIX)
312 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
313 #endif
315 // Called by logging functions to ensure that debug_file is initialized
316 // and can be used for writing. Returns false if the file could not be
317 // initialized. debug_file will be NULL in this case.
318 bool InitializeLogFileHandle() {
319 if (log_file)
320 return true;
322 if (!log_file_name) {
323 // Nobody has called InitLogging to specify a debug log file, so here we
324 // initialize the log file name to a default.
325 log_file_name = new PathString(GetDefaultLogFile());
328 if (logging_destination == LOG_ONLY_TO_FILE ||
329 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
330 #if defined(OS_WIN)
331 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
332 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
333 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
334 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
335 // try the current directory
336 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
337 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
338 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
339 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
340 log_file = NULL;
341 return false;
344 SetFilePointer(log_file, 0, 0, FILE_END);
345 #elif defined(OS_POSIX)
346 log_file = fopen(log_file_name->c_str(), "a");
347 if (log_file == NULL)
348 return false;
349 #endif
352 return true;
355 bool BaseInitLoggingImpl(const PathChar* new_log_file,
356 LoggingDestination logging_dest,
357 LogLockingState lock_log,
358 OldFileDeletionState delete_old,
359 DcheckState dcheck_state) {
360 CommandLine* command_line = CommandLine::ForCurrentProcess();
361 g_dcheck_state = dcheck_state;
362 delete g_vlog_info;
363 g_vlog_info = NULL;
364 // Don't bother initializing g_vlog_info unless we use one of the
365 // vlog switches.
366 if (command_line->HasSwitch(switches::kV) ||
367 command_line->HasSwitch(switches::kVModule)) {
368 g_vlog_info =
369 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
370 command_line->GetSwitchValueASCII(switches::kVModule),
371 &min_log_level);
374 LoggingLock::Init(lock_log, new_log_file);
376 LoggingLock logging_lock;
378 if (log_file) {
379 // calling InitLogging twice or after some log call has already opened the
380 // default log file will re-initialize to the new options
381 CloseFile(log_file);
382 log_file = NULL;
385 logging_destination = logging_dest;
387 // ignore file options if logging is disabled or only to system
388 if (logging_destination == LOG_NONE ||
389 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
390 return true;
392 if (!log_file_name)
393 log_file_name = new PathString();
394 *log_file_name = new_log_file;
395 if (delete_old == DELETE_OLD_LOG_FILE)
396 DeleteFilePath(*log_file_name);
398 return InitializeLogFileHandle();
401 void SetMinLogLevel(int level) {
402 min_log_level = std::min(LOG_ERROR_REPORT, level);
405 int GetMinLogLevel() {
406 return min_log_level;
409 int GetVlogVerbosity() {
410 return std::max(-1, LOG_INFO - GetMinLogLevel());
413 int GetVlogLevelHelper(const char* file, size_t N) {
414 DCHECK_GT(N, 0U);
415 return g_vlog_info ?
416 g_vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
417 GetVlogVerbosity();
420 void SetLogItems(bool enable_process_id, bool enable_thread_id,
421 bool enable_timestamp, bool enable_tickcount) {
422 log_process_id = enable_process_id;
423 log_thread_id = enable_thread_id;
424 log_timestamp = enable_timestamp;
425 log_tickcount = enable_tickcount;
428 void SetShowErrorDialogs(bool enable_dialogs) {
429 show_error_dialogs = enable_dialogs;
432 void SetLogAssertHandler(LogAssertHandlerFunction handler) {
433 log_assert_handler = handler;
436 void SetLogReportHandler(LogReportHandlerFunction handler) {
437 log_report_handler = handler;
440 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
441 log_message_handler = handler;
444 LogMessageHandlerFunction GetLogMessageHandler() {
445 return log_message_handler;
448 // MSVC doesn't like complex extern templates and DLLs.
449 #if !defined(COMPILER_MSVC)
450 // Explicit instantiations for commonly used comparisons.
451 template std::string* MakeCheckOpString<int, int>(
452 const int&, const int&, const char* names);
453 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
454 const unsigned long&, const unsigned long&, const char* names);
455 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
456 const unsigned long&, const unsigned int&, const char* names);
457 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
458 const unsigned int&, const unsigned long&, const char* names);
459 template std::string* MakeCheckOpString<std::string, std::string>(
460 const std::string&, const std::string&, const char* name);
461 #endif
463 // Displays a message box to the user with the error message in it.
464 // Used for fatal messages, where we close the app simultaneously.
465 // This is for developers only; we don't use this in circumstances
466 // (like release builds) where users could see it, since users don't
467 // understand these messages anyway.
468 void DisplayDebugMessageInDialog(const std::string& str) {
469 if (str.empty())
470 return;
472 if (!show_error_dialogs)
473 return;
475 #if defined(OS_WIN)
476 // For Windows programs, it's possible that the message loop is
477 // messed up on a fatal error, and creating a MessageBox will cause
478 // that message loop to be run. Instead, we try to spawn another
479 // process that displays its command line. We look for "Debug
480 // Message.exe" in the same directory as the application. If it
481 // exists, we use it, otherwise, we use a regular message box.
482 wchar_t prog_name[MAX_PATH];
483 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
484 wchar_t* backslash = wcsrchr(prog_name, '\\');
485 if (backslash)
486 backslash[1] = 0;
487 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
489 std::wstring cmdline = UTF8ToWide(str);
490 if (cmdline.empty())
491 return;
493 STARTUPINFO startup_info;
494 memset(&startup_info, 0, sizeof(startup_info));
495 startup_info.cb = sizeof(startup_info);
497 PROCESS_INFORMATION process_info;
498 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
499 NULL, &startup_info, &process_info)) {
500 WaitForSingleObject(process_info.hProcess, INFINITE);
501 CloseHandle(process_info.hThread);
502 CloseHandle(process_info.hProcess);
503 } else {
504 // debug process broken, let's just do a message box
505 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
506 MB_OK | MB_ICONHAND | MB_TOPMOST);
508 #else
509 // We intentionally don't implement a dialog on other platforms.
510 // You can just look at stderr.
511 #endif
514 #if defined(OS_WIN)
515 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
518 LogMessage::SaveLastError::~SaveLastError() {
519 ::SetLastError(last_error_);
521 #endif // defined(OS_WIN)
523 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
524 int ctr)
525 : severity_(severity), file_(file), line_(line) {
526 Init(file, line);
529 LogMessage::LogMessage(const char* file, int line)
530 : severity_(LOG_INFO), file_(file), line_(line) {
531 Init(file, line);
534 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
535 : severity_(severity), file_(file), line_(line) {
536 Init(file, line);
539 LogMessage::LogMessage(const char* file, int line, std::string* result)
540 : severity_(LOG_FATAL), file_(file), line_(line) {
541 Init(file, line);
542 stream_ << "Check failed: " << *result;
543 delete result;
546 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
547 std::string* result)
548 : severity_(severity), file_(file), line_(line) {
549 Init(file, line);
550 stream_ << "Check failed: " << *result;
551 delete result;
554 LogMessage::~LogMessage() {
555 // TODO(port): enable stacktrace generation on LOG_FATAL once backtrace are
556 // working in Android.
557 #if !defined(NDEBUG) && !defined(OS_ANDROID)
558 if (severity_ == LOG_FATAL) {
559 // Include a stack trace on a fatal.
560 base::debug::StackTrace trace;
561 stream_ << std::endl; // Newline to separate from log message.
562 trace.OutputToStream(&stream_);
564 #endif
565 stream_ << std::endl;
566 std::string str_newline(stream_.str());
568 // Give any log message handler first dibs on the message.
569 if (log_message_handler && log_message_handler(severity_, file_, line_,
570 message_start_, str_newline)) {
571 // The handler took care of it, no further processing.
572 return;
575 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
576 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
577 #if defined(OS_WIN)
578 OutputDebugStringA(str_newline.c_str());
579 #elif defined(OS_ANDROID)
580 android_LogPriority priority = ANDROID_LOG_UNKNOWN;
581 switch (severity_) {
582 case LOG_INFO:
583 priority = ANDROID_LOG_INFO;
584 break;
585 case LOG_WARNING:
586 priority = ANDROID_LOG_WARN;
587 break;
588 case LOG_ERROR:
589 case LOG_ERROR_REPORT:
590 priority = ANDROID_LOG_ERROR;
591 break;
592 case LOG_FATAL:
593 priority = ANDROID_LOG_FATAL;
594 break;
596 __android_log_write(priority, "chromium", str_newline.c_str());
597 #endif
598 fprintf(stderr, "%s", str_newline.c_str());
599 fflush(stderr);
600 } else if (severity_ >= kAlwaysPrintErrorLevel) {
601 // When we're only outputting to a log file, above a certain log level, we
602 // should still output to stderr so that we can better detect and diagnose
603 // problems with unit tests, especially on the buildbots.
604 fprintf(stderr, "%s", str_newline.c_str());
605 fflush(stderr);
608 // We can have multiple threads and/or processes, so try to prevent them
609 // from clobbering each other's writes.
610 // If the client app did not call InitLogging, and the lock has not
611 // been created do it now. We do this on demand, but if two threads try
612 // to do this at the same time, there will be a race condition to create
613 // the lock. This is why InitLogging should be called from the main
614 // thread at the beginning of execution.
615 LoggingLock::Init(LOCK_LOG_FILE, NULL);
616 // write to log file
617 if (logging_destination != LOG_NONE &&
618 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
619 LoggingLock logging_lock;
620 if (InitializeLogFileHandle()) {
621 #if defined(OS_WIN)
622 SetFilePointer(log_file, 0, 0, SEEK_END);
623 DWORD num_written;
624 WriteFile(log_file,
625 static_cast<const void*>(str_newline.c_str()),
626 static_cast<DWORD>(str_newline.length()),
627 &num_written,
628 NULL);
629 #else
630 fprintf(log_file, "%s", str_newline.c_str());
631 fflush(log_file);
632 #endif
636 if (severity_ == LOG_FATAL) {
637 // display a message or break into the debugger on a fatal error
638 if (base::debug::BeingDebugged()) {
639 base::debug::BreakDebugger();
640 } else {
641 if (log_assert_handler) {
642 // make a copy of the string for the handler out of paranoia
643 log_assert_handler(std::string(stream_.str()));
644 } else {
645 // Don't use the string with the newline, get a fresh version to send to
646 // the debug message process. We also don't display assertions to the
647 // user in release mode. The enduser can't do anything with this
648 // information, and displaying message boxes when the application is
649 // hosed can cause additional problems.
650 #ifndef NDEBUG
651 DisplayDebugMessageInDialog(stream_.str());
652 #endif
653 // Crash the process to generate a dump.
654 base::debug::BreakDebugger();
657 } else if (severity_ == LOG_ERROR_REPORT) {
658 // We are here only if the user runs with --enable-dcheck in release mode.
659 if (log_report_handler) {
660 log_report_handler(std::string(stream_.str()));
661 } else {
662 DisplayDebugMessageInDialog(stream_.str());
667 // writes the common header info to the stream
668 void LogMessage::Init(const char* file, int line) {
669 base::StringPiece filename(file);
670 size_t last_slash_pos = filename.find_last_of("\\/");
671 if (last_slash_pos != base::StringPiece::npos)
672 filename.remove_prefix(last_slash_pos + 1);
674 // TODO(darin): It might be nice if the columns were fixed width.
676 stream_ << '[';
677 if (log_process_id)
678 stream_ << CurrentProcessId() << ':';
679 if (log_thread_id)
680 stream_ << CurrentThreadId() << ':';
681 if (log_timestamp) {
682 time_t t = time(NULL);
683 struct tm local_time = {0};
684 #if _MSC_VER >= 1400
685 localtime_s(&local_time, &t);
686 #else
687 localtime_r(&t, &local_time);
688 #endif
689 struct tm* tm_time = &local_time;
690 stream_ << std::setfill('0')
691 << std::setw(2) << 1 + tm_time->tm_mon
692 << std::setw(2) << tm_time->tm_mday
693 << '/'
694 << std::setw(2) << tm_time->tm_hour
695 << std::setw(2) << tm_time->tm_min
696 << std::setw(2) << tm_time->tm_sec
697 << ':';
699 if (log_tickcount)
700 stream_ << TickCount() << ':';
701 if (severity_ >= 0)
702 stream_ << log_severity_names[severity_];
703 else
704 stream_ << "VERBOSE" << -severity_;
706 stream_ << ":" << filename << "(" << line << ")] ";
708 message_start_ = stream_.tellp();
711 #if defined(OS_WIN)
712 // This has already been defined in the header, but defining it again as DWORD
713 // ensures that the type used in the header is equivalent to DWORD. If not,
714 // the redefinition is a compile error.
715 typedef DWORD SystemErrorCode;
716 #endif
718 SystemErrorCode GetLastSystemErrorCode() {
719 #if defined(OS_WIN)
720 return ::GetLastError();
721 #elif defined(OS_POSIX)
722 return errno;
723 #else
724 #error Not implemented
725 #endif
728 #if defined(OS_WIN)
729 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
730 int line,
731 LogSeverity severity,
732 SystemErrorCode err,
733 const char* module)
734 : err_(err),
735 module_(module),
736 log_message_(file, line, severity) {
739 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
740 int line,
741 LogSeverity severity,
742 SystemErrorCode err)
743 : err_(err),
744 module_(NULL),
745 log_message_(file, line, severity) {
748 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
749 const int error_message_buffer_size = 256;
750 char msgbuf[error_message_buffer_size];
751 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
752 HMODULE hmod;
753 if (module_) {
754 hmod = GetModuleHandleA(module_);
755 if (hmod) {
756 flags |= FORMAT_MESSAGE_FROM_HMODULE;
757 } else {
758 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
759 // so it will not call GetModuleHandle, so recursive errors are
760 // impossible.
761 DPLOG(WARNING) << "Couldn't open module " << module_
762 << " for error message query";
764 } else {
765 hmod = NULL;
767 DWORD len = FormatMessageA(flags,
768 hmod,
769 err_,
771 msgbuf,
772 sizeof(msgbuf) / sizeof(msgbuf[0]),
773 NULL);
774 if (len) {
775 while ((len > 0) &&
776 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
777 msgbuf[--len] = 0;
779 stream() << ": " << msgbuf;
780 } else {
781 stream() << ": Error " << GetLastError() << " while retrieving error "
782 << err_;
785 #elif defined(OS_POSIX)
786 ErrnoLogMessage::ErrnoLogMessage(const char* file,
787 int line,
788 LogSeverity severity,
789 SystemErrorCode err)
790 : err_(err),
791 log_message_(file, line, severity) {
794 ErrnoLogMessage::~ErrnoLogMessage() {
795 stream() << ": " << safe_strerror(err_);
797 #endif // OS_WIN
799 void CloseLogFile() {
800 LoggingLock logging_lock;
802 if (!log_file)
803 return;
805 CloseFile(log_file);
806 log_file = NULL;
809 void RawLog(int level, const char* message) {
810 if (level >= min_log_level) {
811 size_t bytes_written = 0;
812 const size_t message_len = strlen(message);
813 int rv;
814 while (bytes_written < message_len) {
815 rv = HANDLE_EINTR(
816 write(STDERR_FILENO, message + bytes_written,
817 message_len - bytes_written));
818 if (rv < 0) {
819 // Give up, nothing we can do now.
820 break;
822 bytes_written += rv;
825 if (message_len > 0 && message[message_len - 1] != '\n') {
826 do {
827 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
828 if (rv < 0) {
829 // Give up, nothing we can do now.
830 break;
832 } while (rv != 1);
836 if (level == LOG_FATAL)
837 base::debug::BreakDebugger();
840 } // namespace logging
842 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
843 return out << WideToUTF8(std::wstring(wstr));
846 namespace base {
848 // This was defined at the beginnig of this file.
849 #undef write
851 std::ostream& operator<<(std::ostream& o, const StringPiece& piece) {
852 o.write(piece.data(), static_cast<std::streamsize>(piece.size()));
853 return o;
856 } // namespace base