Ignore empty SMS from empty number
[chromium-blink-merge.git] / base / logging.cc
blob8db57400d3ce3d5d4711c044302e5e38be6b5c7b
1 // Copyright (c) 2012 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/time.h> // timespec doesn't seem to be in <time.h>
23 #else
24 #include <sys/syscall.h>
25 #endif
26 #include <time.h>
27 #endif
29 #if defined(OS_POSIX)
30 #include <errno.h>
31 #include <pthread.h>
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <string.h>
35 #include <unistd.h>
36 #define MAX_PATH PATH_MAX
37 typedef FILE* FileHandle;
38 typedef pthread_mutex_t* MutexHandle;
39 #endif
41 #include <algorithm>
42 #include <cstring>
43 #include <ctime>
44 #include <iomanip>
45 #include <ostream>
47 #include "base/base_switches.h"
48 #include "base/command_line.h"
49 #include "base/debug/debugger.h"
50 #include "base/debug/stack_trace.h"
51 #include "base/eintr_wrapper.h"
52 #include "base/string_piece.h"
53 #include "base/synchronization/lock_impl.h"
54 #include "base/threading/platform_thread.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;
69 namespace {
71 VlogInfo* g_vlog_info = NULL;
72 VlogInfo* g_vlog_info_prev = NULL;
74 const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
75 "INFO", "WARNING", "ERROR", "ERROR_REPORT", "FATAL" };
77 int min_log_level = 0;
79 // The default set here for logging_destination will only be used if
80 // InitLogging is not called. On Windows, use a file next to the exe;
81 // on POSIX platforms, where it may not even be possible to locate the
82 // executable on disk, use stderr.
83 #if defined(OS_WIN)
84 LoggingDestination logging_destination = LOG_ONLY_TO_FILE;
85 #elif defined(OS_POSIX)
86 LoggingDestination logging_destination = LOG_ONLY_TO_SYSTEM_DEBUG_LOG;
87 #endif
89 // For LOG_ERROR and above, always print to stderr.
90 const int kAlwaysPrintErrorLevel = LOG_ERROR;
92 // Which log file to use? This is initialized by InitLogging or
93 // will be lazily initialized to the default value when it is
94 // first needed.
95 #if defined(OS_WIN)
96 typedef std::wstring PathString;
97 #else
98 typedef std::string PathString;
99 #endif
100 PathString* log_file_name = NULL;
102 // this file is lazily opened and the handle may be NULL
103 FileHandle log_file = NULL;
105 // what should be prepended to each message?
106 bool log_process_id = false;
107 bool log_thread_id = false;
108 bool log_timestamp = true;
109 bool log_tickcount = false;
111 // Should we pop up fatal debug messages in a dialog?
112 bool show_error_dialogs = false;
114 // An assert handler override specified by the client to be called instead of
115 // the debug message dialog and process termination.
116 LogAssertHandlerFunction log_assert_handler = NULL;
117 // An report handler override specified by the client to be called instead of
118 // the debug message dialog.
119 LogReportHandlerFunction log_report_handler = NULL;
120 // A log message handler that gets notified of every log message we process.
121 LogMessageHandlerFunction log_message_handler = NULL;
123 // Helper functions to wrap platform differences.
125 int32 CurrentProcessId() {
126 #if defined(OS_WIN)
127 return GetCurrentProcessId();
128 #elif defined(OS_POSIX)
129 return getpid();
130 #endif
133 uint64 TickCount() {
134 #if defined(OS_WIN)
135 return GetTickCount();
136 #elif defined(OS_MACOSX)
137 return mach_absolute_time();
138 #elif defined(OS_NACL)
139 // NaCl sadly does not have _POSIX_TIMERS enabled in sys/features.h
140 // So we have to use clock() for now.
141 return clock();
142 #elif defined(OS_POSIX)
143 struct timespec ts;
144 clock_gettime(CLOCK_MONOTONIC, &ts);
146 uint64 absolute_micro =
147 static_cast<int64>(ts.tv_sec) * 1000000 +
148 static_cast<int64>(ts.tv_nsec) / 1000;
150 return absolute_micro;
151 #endif
154 void CloseFile(FileHandle log) {
155 #if defined(OS_WIN)
156 CloseHandle(log);
157 #else
158 fclose(log);
159 #endif
162 void DeleteFilePath(const PathString& log_name) {
163 #if defined(OS_WIN)
164 DeleteFile(log_name.c_str());
165 #else
166 unlink(log_name.c_str());
167 #endif
170 PathString GetDefaultLogFile() {
171 #if defined(OS_WIN)
172 // On Windows we use the same path as the exe.
173 wchar_t module_name[MAX_PATH];
174 GetModuleFileName(NULL, module_name, MAX_PATH);
176 PathString log_file = module_name;
177 PathString::size_type last_backslash =
178 log_file.rfind('\\', log_file.size());
179 if (last_backslash != PathString::npos)
180 log_file.erase(last_backslash + 1);
181 log_file += L"debug.log";
182 return log_file;
183 #elif defined(OS_POSIX)
184 // On other platforms we just use the current directory.
185 return PathString("debug.log");
186 #endif
189 // This class acts as a wrapper for locking the logging files.
190 // LoggingLock::Init() should be called from the main thread before any logging
191 // is done. Then whenever logging, be sure to have a local LoggingLock
192 // instance on the stack. This will ensure that the lock is unlocked upon
193 // exiting the frame.
194 // LoggingLocks can not be nested.
195 class LoggingLock {
196 public:
197 LoggingLock() {
198 LockLogging();
201 ~LoggingLock() {
202 UnlockLogging();
205 static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
206 if (initialized)
207 return;
208 lock_log_file = lock_log;
209 if (lock_log_file == LOCK_LOG_FILE) {
210 #if defined(OS_WIN)
211 if (!log_mutex) {
212 std::wstring safe_name;
213 if (new_log_file)
214 safe_name = new_log_file;
215 else
216 safe_name = GetDefaultLogFile();
217 // \ is not a legal character in mutex names so we replace \ with /
218 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
219 std::wstring t(L"Global\\");
220 t.append(safe_name);
221 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());
223 if (log_mutex == NULL) {
224 #if DEBUG
225 // Keep the error code for debugging
226 int error = GetLastError(); // NOLINT
227 base::debug::BreakDebugger();
228 #endif
229 // Return nicely without putting initialized to true.
230 return;
233 #endif
234 } else {
235 log_lock = new base::internal::LockImpl();
237 initialized = true;
240 private:
241 static void LockLogging() {
242 if (lock_log_file == LOCK_LOG_FILE) {
243 #if defined(OS_WIN)
244 ::WaitForSingleObject(log_mutex, INFINITE);
245 // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
246 // abort the process here. UI tests might be crashy sometimes,
247 // and aborting the test binary only makes the problem worse.
248 // We also don't use LOG macros because that might lead to an infinite
249 // loop. For more info see http://crbug.com/18028.
250 #elif defined(OS_POSIX)
251 pthread_mutex_lock(&log_mutex);
252 #endif
253 } else {
254 // use the lock
255 log_lock->Lock();
259 static void UnlockLogging() {
260 if (lock_log_file == LOCK_LOG_FILE) {
261 #if defined(OS_WIN)
262 ReleaseMutex(log_mutex);
263 #elif defined(OS_POSIX)
264 pthread_mutex_unlock(&log_mutex);
265 #endif
266 } else {
267 log_lock->Unlock();
271 // The lock is used if log file locking is false. It helps us avoid problems
272 // with multiple threads writing to the log file at the same time. Use
273 // LockImpl directly instead of using Lock, because Lock makes logging calls.
274 static base::internal::LockImpl* log_lock;
276 // When we don't use a lock, we are using a global mutex. We need to do this
277 // because LockFileEx is not thread safe.
278 #if defined(OS_WIN)
279 static MutexHandle log_mutex;
280 #elif defined(OS_POSIX)
281 static pthread_mutex_t log_mutex;
282 #endif
284 static bool initialized;
285 static LogLockingState lock_log_file;
288 // static
289 bool LoggingLock::initialized = false;
290 // static
291 base::internal::LockImpl* LoggingLock::log_lock = NULL;
292 // static
293 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
295 #if defined(OS_WIN)
296 // static
297 MutexHandle LoggingLock::log_mutex = NULL;
298 #elif defined(OS_POSIX)
299 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
300 #endif
302 // Called by logging functions to ensure that debug_file is initialized
303 // and can be used for writing. Returns false if the file could not be
304 // initialized. debug_file will be NULL in this case.
305 bool InitializeLogFileHandle() {
306 if (log_file)
307 return true;
309 if (!log_file_name) {
310 // Nobody has called InitLogging to specify a debug log file, so here we
311 // initialize the log file name to a default.
312 log_file_name = new PathString(GetDefaultLogFile());
315 if (logging_destination == LOG_ONLY_TO_FILE ||
316 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
317 #if defined(OS_WIN)
318 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
319 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
320 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
321 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
322 // try the current directory
323 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
324 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
325 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
326 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
327 log_file = NULL;
328 return false;
331 SetFilePointer(log_file, 0, 0, FILE_END);
332 #elif defined(OS_POSIX)
333 log_file = fopen(log_file_name->c_str(), "a");
334 if (log_file == NULL)
335 return false;
336 #endif
339 return true;
342 } // namespace
345 bool BaseInitLoggingImpl(const PathChar* new_log_file,
346 LoggingDestination logging_dest,
347 LogLockingState lock_log,
348 OldFileDeletionState delete_old,
349 DcheckState dcheck_state) {
350 g_dcheck_state = dcheck_state;
351 // TODO(bbudge) Hook this up to NaCl logging.
352 #if !defined(OS_NACL)
353 CommandLine* command_line = CommandLine::ForCurrentProcess();
354 // Don't bother initializing g_vlog_info unless we use one of the
355 // vlog switches.
356 if (command_line->HasSwitch(switches::kV) ||
357 command_line->HasSwitch(switches::kVModule)) {
358 // NOTE: If g_vlog_info has already been initialized, it might be in use
359 // by another thread. Don't delete the old VLogInfo, just create a second
360 // one. We keep track of both to avoid memory leak warnings.
361 CHECK(!g_vlog_info_prev);
362 g_vlog_info_prev = g_vlog_info;
364 g_vlog_info =
365 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
366 command_line->GetSwitchValueASCII(switches::kVModule),
367 &min_log_level);
370 LoggingLock::Init(lock_log, new_log_file);
372 LoggingLock logging_lock;
374 if (log_file) {
375 // calling InitLogging twice or after some log call has already opened the
376 // default log file will re-initialize to the new options
377 CloseFile(log_file);
378 log_file = NULL;
381 logging_destination = logging_dest;
383 // ignore file options if logging is disabled or only to system
384 if (logging_destination == LOG_NONE ||
385 logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG)
386 return true;
388 if (!log_file_name)
389 log_file_name = new PathString();
390 *log_file_name = new_log_file;
391 if (delete_old == DELETE_OLD_LOG_FILE)
392 DeleteFilePath(*log_file_name);
394 return InitializeLogFileHandle();
395 #else
396 return true;
397 #endif // !defined(OS_NACL)
400 void SetMinLogLevel(int level) {
401 min_log_level = std::min(LOG_ERROR_REPORT, level);
404 int GetMinLogLevel() {
405 return min_log_level;
408 int GetVlogVerbosity() {
409 return std::max(-1, LOG_INFO - GetMinLogLevel());
412 int GetVlogLevelHelper(const char* file, size_t N) {
413 DCHECK_GT(N, 0U);
414 // Note: g_vlog_info may change on a different thread during startup
415 // (but will always be valid or NULL).
416 VlogInfo* vlog_info = g_vlog_info;
417 return vlog_info ?
418 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
419 GetVlogVerbosity();
422 void SetLogItems(bool enable_process_id, bool enable_thread_id,
423 bool enable_timestamp, bool enable_tickcount) {
424 log_process_id = enable_process_id;
425 log_thread_id = enable_thread_id;
426 log_timestamp = enable_timestamp;
427 log_tickcount = enable_tickcount;
430 void SetShowErrorDialogs(bool enable_dialogs) {
431 show_error_dialogs = enable_dialogs;
434 void SetLogAssertHandler(LogAssertHandlerFunction handler) {
435 log_assert_handler = handler;
438 void SetLogReportHandler(LogReportHandlerFunction handler) {
439 log_report_handler = handler;
442 void SetLogMessageHandler(LogMessageHandlerFunction handler) {
443 log_message_handler = handler;
446 LogMessageHandlerFunction GetLogMessageHandler() {
447 return log_message_handler;
450 // MSVC doesn't like complex extern templates and DLLs.
451 #if !defined(COMPILER_MSVC)
452 // Explicit instantiations for commonly used comparisons.
453 template std::string* MakeCheckOpString<int, int>(
454 const int&, const int&, const char* names);
455 template std::string* MakeCheckOpString<unsigned long, unsigned long>(
456 const unsigned long&, const unsigned long&, const char* names);
457 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
458 const unsigned long&, const unsigned int&, const char* names);
459 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
460 const unsigned int&, const unsigned long&, const char* names);
461 template std::string* MakeCheckOpString<std::string, std::string>(
462 const std::string&, const std::string&, const char* name);
463 #endif
465 // Displays a message box to the user with the error message in it.
466 // Used for fatal messages, where we close the app simultaneously.
467 // This is for developers only; we don't use this in circumstances
468 // (like release builds) where users could see it, since users don't
469 // understand these messages anyway.
470 void DisplayDebugMessageInDialog(const std::string& str) {
471 if (str.empty())
472 return;
474 if (!show_error_dialogs)
475 return;
477 #if defined(OS_WIN)
478 // For Windows programs, it's possible that the message loop is
479 // messed up on a fatal error, and creating a MessageBox will cause
480 // that message loop to be run. Instead, we try to spawn another
481 // process that displays its command line. We look for "Debug
482 // Message.exe" in the same directory as the application. If it
483 // exists, we use it, otherwise, we use a regular message box.
484 wchar_t prog_name[MAX_PATH];
485 GetModuleFileNameW(NULL, prog_name, MAX_PATH);
486 wchar_t* backslash = wcsrchr(prog_name, '\\');
487 if (backslash)
488 backslash[1] = 0;
489 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
491 std::wstring cmdline = UTF8ToWide(str);
492 if (cmdline.empty())
493 return;
495 STARTUPINFO startup_info;
496 memset(&startup_info, 0, sizeof(startup_info));
497 startup_info.cb = sizeof(startup_info);
499 PROCESS_INFORMATION process_info;
500 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
501 NULL, &startup_info, &process_info)) {
502 WaitForSingleObject(process_info.hProcess, INFINITE);
503 CloseHandle(process_info.hThread);
504 CloseHandle(process_info.hProcess);
505 } else {
506 // debug process broken, let's just do a message box
507 MessageBoxW(NULL, &cmdline[0], L"Fatal error",
508 MB_OK | MB_ICONHAND | MB_TOPMOST);
510 #else
511 // We intentionally don't implement a dialog on other platforms.
512 // You can just look at stderr.
513 #endif
516 #if defined(OS_WIN)
517 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
520 LogMessage::SaveLastError::~SaveLastError() {
521 ::SetLastError(last_error_);
523 #endif // defined(OS_WIN)
525 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
526 int ctr)
527 : severity_(severity), file_(file), line_(line) {
528 Init(file, line);
531 LogMessage::LogMessage(const char* file, int line)
532 : severity_(LOG_INFO), file_(file), line_(line) {
533 Init(file, line);
536 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
537 : severity_(severity), file_(file), line_(line) {
538 Init(file, line);
541 LogMessage::LogMessage(const char* file, int line, std::string* result)
542 : severity_(LOG_FATAL), file_(file), line_(line) {
543 Init(file, line);
544 stream_ << "Check failed: " << *result;
545 delete result;
548 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
549 std::string* result)
550 : severity_(severity), file_(file), line_(line) {
551 Init(file, line);
552 stream_ << "Check failed: " << *result;
553 delete result;
556 LogMessage::~LogMessage() {
557 // TODO(port): enable stacktrace generation on LOG_FATAL once backtrace are
558 // working in Android.
559 #if !defined(NDEBUG) && !defined(OS_ANDROID) && !defined(OS_NACL)
560 if (severity_ == LOG_FATAL) {
561 // Include a stack trace on a fatal.
562 base::debug::StackTrace trace;
563 stream_ << std::endl; // Newline to separate from log message.
564 trace.OutputToStream(&stream_);
566 #endif
567 stream_ << std::endl;
568 std::string str_newline(stream_.str());
570 // Give any log message handler first dibs on the message.
571 if (log_message_handler && log_message_handler(severity_, file_, line_,
572 message_start_, str_newline)) {
573 // The handler took care of it, no further processing.
574 return;
577 if (logging_destination == LOG_ONLY_TO_SYSTEM_DEBUG_LOG ||
578 logging_destination == LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG) {
579 #if defined(OS_WIN)
580 OutputDebugStringA(str_newline.c_str());
581 #elif defined(OS_ANDROID)
582 android_LogPriority priority = ANDROID_LOG_UNKNOWN;
583 switch (severity_) {
584 case LOG_INFO:
585 priority = ANDROID_LOG_INFO;
586 break;
587 case LOG_WARNING:
588 priority = ANDROID_LOG_WARN;
589 break;
590 case LOG_ERROR:
591 case LOG_ERROR_REPORT:
592 priority = ANDROID_LOG_ERROR;
593 break;
594 case LOG_FATAL:
595 priority = ANDROID_LOG_FATAL;
596 break;
598 __android_log_write(priority, "chromium", str_newline.c_str());
599 #endif
600 fprintf(stderr, "%s", str_newline.c_str());
601 fflush(stderr);
602 } else if (severity_ >= kAlwaysPrintErrorLevel) {
603 // When we're only outputting to a log file, above a certain log level, we
604 // should still output to stderr so that we can better detect and diagnose
605 // problems with unit tests, especially on the buildbots.
606 fprintf(stderr, "%s", str_newline.c_str());
607 fflush(stderr);
610 // We can have multiple threads and/or processes, so try to prevent them
611 // from clobbering each other's writes.
612 // If the client app did not call InitLogging, and the lock has not
613 // been created do it now. We do this on demand, but if two threads try
614 // to do this at the same time, there will be a race condition to create
615 // the lock. This is why InitLogging should be called from the main
616 // thread at the beginning of execution.
617 LoggingLock::Init(LOCK_LOG_FILE, NULL);
618 // write to log file
619 if (logging_destination != LOG_NONE &&
620 logging_destination != LOG_ONLY_TO_SYSTEM_DEBUG_LOG) {
621 LoggingLock logging_lock;
622 if (InitializeLogFileHandle()) {
623 #if defined(OS_WIN)
624 SetFilePointer(log_file, 0, 0, SEEK_END);
625 DWORD num_written;
626 WriteFile(log_file,
627 static_cast<const void*>(str_newline.c_str()),
628 static_cast<DWORD>(str_newline.length()),
629 &num_written,
630 NULL);
631 #else
632 fprintf(log_file, "%s", str_newline.c_str());
633 fflush(log_file);
634 #endif
638 if (severity_ == LOG_FATAL) {
639 // display a message or break into the debugger on a fatal error
640 if (base::debug::BeingDebugged()) {
641 base::debug::BreakDebugger();
642 } else {
643 if (log_assert_handler) {
644 // make a copy of the string for the handler out of paranoia
645 log_assert_handler(std::string(stream_.str()));
646 } else {
647 // Don't use the string with the newline, get a fresh version to send to
648 // the debug message process. We also don't display assertions to the
649 // user in release mode. The enduser can't do anything with this
650 // information, and displaying message boxes when the application is
651 // hosed can cause additional problems.
652 #ifndef NDEBUG
653 DisplayDebugMessageInDialog(stream_.str());
654 #endif
655 // Crash the process to generate a dump.
656 base::debug::BreakDebugger();
659 } else if (severity_ == LOG_ERROR_REPORT) {
660 // We are here only if the user runs with --enable-dcheck in release mode.
661 if (log_report_handler) {
662 log_report_handler(std::string(stream_.str()));
663 } else {
664 DisplayDebugMessageInDialog(stream_.str());
669 // writes the common header info to the stream
670 void LogMessage::Init(const char* file, int line) {
671 base::StringPiece filename(file);
672 size_t last_slash_pos = filename.find_last_of("\\/");
673 if (last_slash_pos != base::StringPiece::npos)
674 filename.remove_prefix(last_slash_pos + 1);
676 // TODO(darin): It might be nice if the columns were fixed width.
678 stream_ << '[';
679 if (log_process_id)
680 stream_ << CurrentProcessId() << ':';
681 if (log_thread_id)
682 stream_ << base::PlatformThread::CurrentId() << ':';
683 if (log_timestamp) {
684 time_t t = time(NULL);
685 struct tm local_time = {0};
686 #if _MSC_VER >= 1400
687 localtime_s(&local_time, &t);
688 #else
689 localtime_r(&t, &local_time);
690 #endif
691 struct tm* tm_time = &local_time;
692 stream_ << std::setfill('0')
693 << std::setw(2) << 1 + tm_time->tm_mon
694 << std::setw(2) << tm_time->tm_mday
695 << '/'
696 << std::setw(2) << tm_time->tm_hour
697 << std::setw(2) << tm_time->tm_min
698 << std::setw(2) << tm_time->tm_sec
699 << ':';
701 if (log_tickcount)
702 stream_ << TickCount() << ':';
703 if (severity_ >= 0)
704 stream_ << log_severity_names[severity_];
705 else
706 stream_ << "VERBOSE" << -severity_;
708 stream_ << ":" << filename << "(" << line << ")] ";
710 message_start_ = stream_.tellp();
713 #if defined(OS_WIN)
714 // This has already been defined in the header, but defining it again as DWORD
715 // ensures that the type used in the header is equivalent to DWORD. If not,
716 // the redefinition is a compile error.
717 typedef DWORD SystemErrorCode;
718 #endif
720 SystemErrorCode GetLastSystemErrorCode() {
721 #if defined(OS_WIN)
722 return ::GetLastError();
723 #elif defined(OS_POSIX)
724 return errno;
725 #else
726 #error Not implemented
727 #endif
730 #if defined(OS_WIN)
731 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
732 int line,
733 LogSeverity severity,
734 SystemErrorCode err,
735 const char* module)
736 : err_(err),
737 module_(module),
738 log_message_(file, line, severity) {
741 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
742 int line,
743 LogSeverity severity,
744 SystemErrorCode err)
745 : err_(err),
746 module_(NULL),
747 log_message_(file, line, severity) {
750 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
751 const int error_message_buffer_size = 256;
752 char msgbuf[error_message_buffer_size];
753 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
754 HMODULE hmod;
755 if (module_) {
756 hmod = GetModuleHandleA(module_);
757 if (hmod) {
758 flags |= FORMAT_MESSAGE_FROM_HMODULE;
759 } else {
760 // This makes a nested Win32ErrorLogMessage. It will have module_ of NULL
761 // so it will not call GetModuleHandle, so recursive errors are
762 // impossible.
763 DPLOG(WARNING) << "Couldn't open module " << module_
764 << " for error message query";
766 } else {
767 hmod = NULL;
769 DWORD len = FormatMessageA(flags,
770 hmod,
771 err_,
773 msgbuf,
774 sizeof(msgbuf) / sizeof(msgbuf[0]),
775 NULL);
776 if (len) {
777 while ((len > 0) &&
778 isspace(static_cast<unsigned char>(msgbuf[len - 1]))) {
779 msgbuf[--len] = 0;
781 stream() << ": " << msgbuf;
782 } else {
783 stream() << ": Error " << GetLastError() << " while retrieving error "
784 << err_;
787 #elif defined(OS_POSIX)
788 ErrnoLogMessage::ErrnoLogMessage(const char* file,
789 int line,
790 LogSeverity severity,
791 SystemErrorCode err)
792 : err_(err),
793 log_message_(file, line, severity) {
796 ErrnoLogMessage::~ErrnoLogMessage() {
797 stream() << ": " << safe_strerror(err_);
799 #endif // OS_WIN
801 void CloseLogFile() {
802 LoggingLock logging_lock;
804 if (!log_file)
805 return;
807 CloseFile(log_file);
808 log_file = NULL;
811 void RawLog(int level, const char* message) {
812 if (level >= min_log_level) {
813 size_t bytes_written = 0;
814 const size_t message_len = strlen(message);
815 int rv;
816 while (bytes_written < message_len) {
817 rv = HANDLE_EINTR(
818 write(STDERR_FILENO, message + bytes_written,
819 message_len - bytes_written));
820 if (rv < 0) {
821 // Give up, nothing we can do now.
822 break;
824 bytes_written += rv;
827 if (message_len > 0 && message[message_len - 1] != '\n') {
828 do {
829 rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
830 if (rv < 0) {
831 // Give up, nothing we can do now.
832 break;
834 } while (rv != 1);
838 if (level == LOG_FATAL)
839 base::debug::BreakDebugger();
842 // This was defined at the beginning of this file.
843 #undef write
845 } // namespace logging
847 std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
848 return out << WideToUTF8(std::wstring(wstr));