Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(164)

Side by Side Diff: base/logging.cc

Issue 1134153003: Cleanup base/logging.cc a bit. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 5 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « no previous file | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/logging.h" 5 #include "base/logging.h"
6 6
7 #if defined(OS_WIN) 7 #if defined(OS_WIN)
8 #include <io.h> 8 #include <io.h>
9 #include <windows.h> 9 #include <windows.h>
10 typedef HANDLE FileHandle; 10 typedef HANDLE FileHandle;
(...skipping 52 matching lines...) Expand 10 before | Expand all | Expand 10 after
63 #endif 63 #endif
64 64
65 #if defined(OS_ANDROID) 65 #if defined(OS_ANDROID)
66 #include <android/log.h> 66 #include <android/log.h>
67 #endif 67 #endif
68 68
69 namespace logging { 69 namespace logging {
70 70
71 namespace { 71 namespace {
72 72
73 VlogInfo* g_vlog_info = NULL; 73 VlogInfo* g_vlog_info = nullptr;
74 VlogInfo* g_vlog_info_prev = NULL; 74 VlogInfo* g_vlog_info_prev = nullptr;
75 75
76 const char* const log_severity_names[LOG_NUM_SEVERITIES] = { 76 const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
77 "INFO", "WARNING", "ERROR", "FATAL" }; 77 "INFO", "WARNING", "ERROR", "FATAL" };
78 78
79 const char* log_severity_name(int severity) { 79 const char* log_severity_name(int severity) {
80 if (severity >= 0 && severity < LOG_NUM_SEVERITIES) 80 if (severity >= 0 && severity < LOG_NUM_SEVERITIES)
81 return log_severity_names[severity]; 81 return log_severity_names[severity];
82 return "UNKNOWN"; 82 return "UNKNOWN";
83 } 83 }
84 84
85 int min_log_level = 0; 85 int g_min_log_level = 0;
86 86
87 LoggingDestination logging_destination = LOG_DEFAULT; 87 LoggingDestination g_logging_destination = LOG_DEFAULT;
88 88
89 // For LOG_ERROR and above, always print to stderr. 89 // For LOG_ERROR and above, always print to stderr.
90 const int kAlwaysPrintErrorLevel = LOG_ERROR; 90 const int kAlwaysPrintErrorLevel = LOG_ERROR;
91 91
92 // Which log file to use? This is initialized by InitLogging or 92 // Which log file to use? This is initialized by InitLogging or
93 // will be lazily initialized to the default value when it is 93 // will be lazily initialized to the default value when it is
94 // first needed. 94 // first needed.
95 #if defined(OS_WIN) 95 #if defined(OS_WIN)
96 typedef std::wstring PathString; 96 typedef std::wstring PathString;
97 #else 97 #else
98 typedef std::string PathString; 98 typedef std::string PathString;
99 #endif 99 #endif
100 PathString* log_file_name = NULL; 100 PathString* g_log_file_name = nullptr;
101 101
102 // this file is lazily opened and the handle may be NULL 102 // This file is lazily opened and the handle may be nullptr
103 FileHandle log_file = NULL; 103 FileHandle g_log_file = nullptr;
104 104
105 // what should be prepended to each message? 105 // What should be prepended to each message?
106 bool log_process_id = false; 106 bool g_log_process_id = false;
107 bool log_thread_id = false; 107 bool g_log_thread_id = false;
108 bool log_timestamp = true; 108 bool g_log_timestamp = true;
109 bool log_tickcount = false; 109 bool g_log_tickcount = false;
110 110
111 // Should we pop up fatal debug messages in a dialog? 111 // Should we pop up fatal debug messages in a dialog?
112 bool show_error_dialogs = false; 112 bool show_error_dialogs = false;
113 113
114 // An assert handler override specified by the client to be called instead of 114 // An assert handler override specified by the client to be called instead of
115 // the debug message dialog and process termination. 115 // the debug message dialog and process termination.
116 LogAssertHandlerFunction log_assert_handler = NULL; 116 LogAssertHandlerFunction log_assert_handler = nullptr;
117 // A log message handler that gets notified of every log message we process. 117 // A log message handler that gets notified of every log message we process.
118 LogMessageHandlerFunction log_message_handler = NULL; 118 LogMessageHandlerFunction log_message_handler = nullptr;
119 119
120 // Helper functions to wrap platform differences. 120 // Helper functions to wrap platform differences.
121 121
122 int32 CurrentProcessId() { 122 int32 CurrentProcessId() {
123 #if defined(OS_WIN) 123 #if defined(OS_WIN)
124 return GetCurrentProcessId(); 124 return GetCurrentProcessId();
125 #elif defined(OS_POSIX) 125 #elif defined(OS_POSIX)
126 return getpid(); 126 return getpid();
127 #endif 127 #endif
128 } 128 }
(...skipping 26 matching lines...) Expand all
155 // Do nothing; unlink() isn't supported on NaCl. 155 // Do nothing; unlink() isn't supported on NaCl.
156 #else 156 #else
157 unlink(log_name.c_str()); 157 unlink(log_name.c_str());
158 #endif 158 #endif
159 } 159 }
160 160
161 PathString GetDefaultLogFile() { 161 PathString GetDefaultLogFile() {
162 #if defined(OS_WIN) 162 #if defined(OS_WIN)
163 // On Windows we use the same path as the exe. 163 // On Windows we use the same path as the exe.
164 wchar_t module_name[MAX_PATH]; 164 wchar_t module_name[MAX_PATH];
165 GetModuleFileName(NULL, module_name, MAX_PATH); 165 GetModuleFileName(nullptr, module_name, MAX_PATH);
166 166
167 PathString log_name = module_name; 167 PathString log_name = module_name;
168 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size()); 168 PathString::size_type last_backslash = log_name.rfind('\\', log_name.size());
169 if (last_backslash != PathString::npos) 169 if (last_backslash != PathString::npos)
170 log_name.erase(last_backslash + 1); 170 log_name.erase(last_backslash + 1);
171 log_name += L"debug.log"; 171 log_name += L"debug.log";
172 return log_name; 172 return log_name;
173 #elif defined(OS_POSIX) 173 #elif defined(OS_POSIX)
174 // On other platforms we just use the current directory. 174 // On other platforms we just use the current directory.
175 return PathString("debug.log"); 175 return PathString("debug.log");
(...skipping 25 matching lines...) Expand all
201 if (!log_mutex) { 201 if (!log_mutex) {
202 std::wstring safe_name; 202 std::wstring safe_name;
203 if (new_log_file) 203 if (new_log_file)
204 safe_name = new_log_file; 204 safe_name = new_log_file;
205 else 205 else
206 safe_name = GetDefaultLogFile(); 206 safe_name = GetDefaultLogFile();
207 // \ is not a legal character in mutex names so we replace \ with / 207 // \ is not a legal character in mutex names so we replace \ with /
208 std::replace(safe_name.begin(), safe_name.end(), '\\', '/'); 208 std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
209 std::wstring t(L"Global\\"); 209 std::wstring t(L"Global\\");
210 t.append(safe_name); 210 t.append(safe_name);
211 log_mutex = ::CreateMutex(NULL, FALSE, t.c_str()); 211 log_mutex = ::CreateMutex(nullptr, FALSE, t.c_str());
212 212
213 if (log_mutex == NULL) { 213 if (log_mutex == nullptr) {
214 #if DEBUG 214 #if DEBUG
215 // Keep the error code for debugging 215 // Keep the error code for debugging
216 int error = GetLastError(); // NOLINT 216 int error = GetLastError(); // NOLINT
217 base::debug::BreakDebugger(); 217 base::debug::BreakDebugger();
218 #endif 218 #endif
219 // Return nicely without putting initialized to true. 219 // Return nicely without putting initialized to true.
220 return; 220 return;
221 } 221 }
222 } 222 }
223 #endif 223 #endif
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
271 static pthread_mutex_t log_mutex; 271 static pthread_mutex_t log_mutex;
272 #endif 272 #endif
273 273
274 static bool initialized; 274 static bool initialized;
275 static LogLockingState lock_log_file; 275 static LogLockingState lock_log_file;
276 }; 276 };
277 277
278 // static 278 // static
279 bool LoggingLock::initialized = false; 279 bool LoggingLock::initialized = false;
280 // static 280 // static
281 base::internal::LockImpl* LoggingLock::log_lock = NULL; 281 base::internal::LockImpl* LoggingLock::log_lock = nullptr;
282 // static 282 // static
283 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE; 283 LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;
284 284
285 #if defined(OS_WIN) 285 #if defined(OS_WIN)
286 // static 286 // static
287 MutexHandle LoggingLock::log_mutex = NULL; 287 MutexHandle LoggingLock::log_mutex = nullptr;
288 #elif defined(OS_POSIX) 288 #elif defined(OS_POSIX)
289 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER; 289 pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
290 #endif 290 #endif
291 291
292 // Called by logging functions to ensure that debug_file is initialized 292 // Called by logging functions to ensure that |g_log_file| is initialized
293 // and can be used for writing. Returns false if the file could not be 293 // and can be used for writing. Returns false if the file could not be
294 // initialized. debug_file will be NULL in this case. 294 // initialized. |g_log_file| will be nullptr in this case.
295 bool InitializeLogFileHandle() { 295 bool InitializeLogFileHandle() {
296 if (log_file) 296 if (g_log_file)
297 return true; 297 return true;
298 298
299 if (!log_file_name) { 299 if (!g_log_file_name) {
300 // Nobody has called InitLogging to specify a debug log file, so here we 300 // Nobody has called InitLogging to specify a debug log file, so here we
301 // initialize the log file name to a default. 301 // initialize the log file name to a default.
302 log_file_name = new PathString(GetDefaultLogFile()); 302 g_log_file_name = new PathString(GetDefaultLogFile());
303 } 303 }
304 304
305 if ((logging_destination & LOG_TO_FILE) != 0) { 305 if ((g_logging_destination & LOG_TO_FILE) != 0) {
306 #if defined(OS_WIN) 306 #if defined(OS_WIN)
307 log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE, 307 g_log_file = CreateFile(g_log_file_name->c_str(), GENERIC_WRITE,
308 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 308 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
309 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 309 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
310 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) { 310 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
311 // try the current directory 311 // try the current directory
312 log_file = CreateFile(L".\\debug.log", GENERIC_WRITE, 312 g_log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
313 FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 313 FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
314 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); 314 OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr);
315 if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) { 315 if (g_log_file == INVALID_HANDLE_VALUE || g_log_file == nullptr) {
316 log_file = NULL; 316 g_log_file = nullptr;
317 return false; 317 return false;
318 } 318 }
319 } 319 }
320 SetFilePointer(log_file, 0, 0, FILE_END); 320 SetFilePointer(g_log_file, 0, 0, FILE_END);
321 #elif defined(OS_POSIX) 321 #elif defined(OS_POSIX)
322 log_file = fopen(log_file_name->c_str(), "a"); 322 g_log_file = fopen(g_log_file_name->c_str(), "a");
323 if (log_file == NULL) 323 if (g_log_file == nullptr)
324 return false; 324 return false;
325 #endif 325 #endif
326 } 326 }
327 327
328 return true; 328 return true;
329 } 329 }
330 330
331 void CloseFile(FileHandle log) { 331 void CloseFile(FileHandle log) {
332 #if defined(OS_WIN) 332 #if defined(OS_WIN)
333 CloseHandle(log); 333 CloseHandle(log);
334 #else 334 #else
335 fclose(log); 335 fclose(log);
336 #endif 336 #endif
337 } 337 }
338 338
339 void CloseLogFileUnlocked() { 339 void CloseLogFileUnlocked() {
340 if (!log_file) 340 if (!g_log_file)
341 return; 341 return;
342 342
343 CloseFile(log_file); 343 CloseFile(g_log_file);
344 log_file = NULL; 344 g_log_file = nullptr;
345 } 345 }
346 346
347 } // namespace 347 } // namespace
348 348
349 LoggingSettings::LoggingSettings() 349 LoggingSettings::LoggingSettings()
350 : logging_dest(LOG_DEFAULT), 350 : logging_dest(LOG_DEFAULT),
351 log_file(NULL), 351 log_file(nullptr),
352 lock_log(LOCK_LOG_FILE), 352 lock_log(LOCK_LOG_FILE),
353 delete_old(APPEND_TO_OLD_LOG_FILE) {} 353 delete_old(APPEND_TO_OLD_LOG_FILE) {}
354 354
355 bool BaseInitLoggingImpl(const LoggingSettings& settings) { 355 bool BaseInitLoggingImpl(const LoggingSettings& settings) {
356 #if defined(OS_NACL) 356 #if defined(OS_NACL)
357 // Can log only to the system debug log. 357 // Can log only to the system debug log.
358 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0); 358 CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
359 #endif 359 #endif
360 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess(); 360 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
361 // Don't bother initializing g_vlog_info unless we use one of the 361 // Don't bother initializing |g_vlog_info| unless we use one of the
362 // vlog switches. 362 // vlog switches.
363 if (command_line->HasSwitch(switches::kV) || 363 if (command_line->HasSwitch(switches::kV) ||
364 command_line->HasSwitch(switches::kVModule)) { 364 command_line->HasSwitch(switches::kVModule)) {
365 // NOTE: If g_vlog_info has already been initialized, it might be in use 365 // NOTE: If |g_vlog_info| has already been initialized, it might be in use
366 // by another thread. Don't delete the old VLogInfo, just create a second 366 // by another thread. Don't delete the old VLogInfo, just create a second
367 // one. We keep track of both to avoid memory leak warnings. 367 // one. We keep track of both to avoid memory leak warnings.
368 CHECK(!g_vlog_info_prev); 368 CHECK(!g_vlog_info_prev);
369 g_vlog_info_prev = g_vlog_info; 369 g_vlog_info_prev = g_vlog_info;
370 370
371 g_vlog_info = 371 g_vlog_info =
372 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV), 372 new VlogInfo(command_line->GetSwitchValueASCII(switches::kV),
373 command_line->GetSwitchValueASCII(switches::kVModule), 373 command_line->GetSwitchValueASCII(switches::kVModule),
374 &min_log_level); 374 &g_min_log_level);
375 } 375 }
376 376
377 logging_destination = settings.logging_dest; 377 g_logging_destination = settings.logging_dest;
378 378
379 // ignore file options unless logging to file is set. 379 // ignore file options unless logging to file is set.
380 if ((logging_destination & LOG_TO_FILE) == 0) 380 if ((g_logging_destination & LOG_TO_FILE) == 0)
381 return true; 381 return true;
382 382
383 LoggingLock::Init(settings.lock_log, settings.log_file); 383 LoggingLock::Init(settings.lock_log, settings.log_file);
384 LoggingLock logging_lock; 384 LoggingLock logging_lock;
385 385
386 // Calling InitLogging twice or after some log call has already opened the 386 // Calling InitLogging twice or after some log call has already opened the
387 // default log file will re-initialize to the new options. 387 // default log file will re-initialize to the new options.
388 CloseLogFileUnlocked(); 388 CloseLogFileUnlocked();
389 389
390 if (!log_file_name) 390 if (!g_log_file_name)
391 log_file_name = new PathString(); 391 g_log_file_name = new PathString();
392 *log_file_name = settings.log_file; 392 *g_log_file_name = settings.log_file;
393 if (settings.delete_old == DELETE_OLD_LOG_FILE) 393 if (settings.delete_old == DELETE_OLD_LOG_FILE)
394 DeleteFilePath(*log_file_name); 394 DeleteFilePath(*g_log_file_name);
395 395
396 return InitializeLogFileHandle(); 396 return InitializeLogFileHandle();
397 } 397 }
398 398
399 void SetMinLogLevel(int level) { 399 void SetMinLogLevel(int level) {
400 min_log_level = std::min(LOG_FATAL, level); 400 g_min_log_level = std::min(LOG_FATAL, level);
401 } 401 }
402 402
403 int GetMinLogLevel() { 403 int GetMinLogLevel() {
404 return min_log_level; 404 return g_min_log_level;
405 } 405 }
406 406
407 int GetVlogVerbosity() { 407 int GetVlogVerbosity() {
408 return std::max(-1, LOG_INFO - GetMinLogLevel()); 408 return std::max(-1, LOG_INFO - GetMinLogLevel());
409 } 409 }
410 410
411 int GetVlogLevelHelper(const char* file, size_t N) { 411 int GetVlogLevelHelper(const char* file, size_t N) {
412 DCHECK_GT(N, 0U); 412 DCHECK_GT(N, 0U);
413 // Note: g_vlog_info may change on a different thread during startup 413 // Note: |g_vlog_info| may change on a different thread during startup
414 // (but will always be valid or NULL). 414 // (but will always be valid or nullptr).
415 VlogInfo* vlog_info = g_vlog_info; 415 VlogInfo* vlog_info = g_vlog_info;
416 return vlog_info ? 416 return vlog_info ?
417 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) : 417 vlog_info->GetVlogLevel(base::StringPiece(file, N - 1)) :
418 GetVlogVerbosity(); 418 GetVlogVerbosity();
419 } 419 }
420 420
421 void SetLogItems(bool enable_process_id, bool enable_thread_id, 421 void SetLogItems(bool enable_process_id, bool enable_thread_id,
422 bool enable_timestamp, bool enable_tickcount) { 422 bool enable_timestamp, bool enable_tickcount) {
423 log_process_id = enable_process_id; 423 g_log_process_id = enable_process_id;
424 log_thread_id = enable_thread_id; 424 g_log_thread_id = enable_thread_id;
425 log_timestamp = enable_timestamp; 425 g_log_timestamp = enable_timestamp;
426 log_tickcount = enable_tickcount; 426 g_log_tickcount = enable_tickcount;
427 } 427 }
428 428
429 void SetShowErrorDialogs(bool enable_dialogs) { 429 void SetShowErrorDialogs(bool enable_dialogs) {
430 show_error_dialogs = enable_dialogs; 430 show_error_dialogs = enable_dialogs;
431 } 431 }
432 432
433 void SetLogAssertHandler(LogAssertHandlerFunction handler) { 433 void SetLogAssertHandler(LogAssertHandlerFunction handler) {
434 log_assert_handler = handler; 434 log_assert_handler = handler;
435 } 435 }
436 436
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
468 return; 468 return;
469 469
470 #if defined(OS_WIN) 470 #if defined(OS_WIN)
471 // For Windows programs, it's possible that the message loop is 471 // For Windows programs, it's possible that the message loop is
472 // messed up on a fatal error, and creating a MessageBox will cause 472 // messed up on a fatal error, and creating a MessageBox will cause
473 // that message loop to be run. Instead, we try to spawn another 473 // that message loop to be run. Instead, we try to spawn another
474 // process that displays its command line. We look for "Debug 474 // process that displays its command line. We look for "Debug
475 // Message.exe" in the same directory as the application. If it 475 // Message.exe" in the same directory as the application. If it
476 // exists, we use it, otherwise, we use a regular message box. 476 // exists, we use it, otherwise, we use a regular message box.
477 wchar_t prog_name[MAX_PATH]; 477 wchar_t prog_name[MAX_PATH];
478 GetModuleFileNameW(NULL, prog_name, MAX_PATH); 478 GetModuleFileNameW(nullptr, prog_name, MAX_PATH);
479 wchar_t* backslash = wcsrchr(prog_name, '\\'); 479 wchar_t* backslash = wcsrchr(prog_name, '\\');
480 if (backslash) 480 if (backslash)
481 backslash[1] = 0; 481 backslash[1] = 0;
482 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe"); 482 wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");
483 483
484 std::wstring cmdline = base::UTF8ToWide(str); 484 std::wstring cmdline = base::UTF8ToWide(str);
485 if (cmdline.empty()) 485 if (cmdline.empty())
486 return; 486 return;
487 487
488 STARTUPINFO startup_info; 488 STARTUPINFO startup_info;
489 memset(&startup_info, 0, sizeof(startup_info)); 489 memset(&startup_info, 0, sizeof(startup_info));
490 startup_info.cb = sizeof(startup_info); 490 startup_info.cb = sizeof(startup_info);
491 491
492 PROCESS_INFORMATION process_info; 492 PROCESS_INFORMATION process_info;
493 if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL, 493 if (CreateProcessW(prog_name, &cmdline[0], nullptr, nullptr, false, 0,
494 NULL, &startup_info, &process_info)) { 494 nullptr, nullptr, &startup_info, &process_info)) {
495 WaitForSingleObject(process_info.hProcess, INFINITE); 495 WaitForSingleObject(process_info.hProcess, INFINITE);
496 CloseHandle(process_info.hThread); 496 CloseHandle(process_info.hThread);
497 CloseHandle(process_info.hProcess); 497 CloseHandle(process_info.hProcess);
498 } else { 498 } else {
499 // debug process broken, let's just do a message box 499 // debug process broken, let's just do a message box
500 MessageBoxW(NULL, &cmdline[0], L"Fatal error", 500 MessageBoxW(nullptr, &cmdline[0], L"Fatal error",
501 MB_OK | MB_ICONHAND | MB_TOPMOST); 501 MB_OK | MB_ICONHAND | MB_TOPMOST);
502 } 502 }
503 #else 503 #else
504 // We intentionally don't implement a dialog on other platforms. 504 // We intentionally don't implement a dialog on other platforms.
505 // You can just look at stderr. 505 // You can just look at stderr.
506 #endif 506 #endif // defined(OS_WIN)
507 } 507 }
508 #endif // !defined(NDEBUG) 508 #endif // !defined(NDEBUG)
509 509
510 #if defined(OS_WIN) 510 #if defined(OS_WIN)
511 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) { 511 LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
512 } 512 }
513 513
514 LogMessage::SaveLastError::~SaveLastError() { 514 LogMessage::SaveLastError::~SaveLastError() {
515 ::SetLastError(last_error_); 515 ::SetLastError(last_error_);
516 } 516 }
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
549 std::string str_newline(stream_.str()); 549 std::string str_newline(stream_.str());
550 550
551 // Give any log message handler first dibs on the message. 551 // Give any log message handler first dibs on the message.
552 if (log_message_handler && 552 if (log_message_handler &&
553 log_message_handler(severity_, file_, line_, 553 log_message_handler(severity_, file_, line_,
554 message_start_, str_newline)) { 554 message_start_, str_newline)) {
555 // The handler took care of it, no further processing. 555 // The handler took care of it, no further processing.
556 return; 556 return;
557 } 557 }
558 558
559 if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) { 559 if ((g_logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
560 #if defined(OS_WIN) 560 #if defined(OS_WIN)
561 OutputDebugStringA(str_newline.c_str()); 561 OutputDebugStringA(str_newline.c_str());
562 #elif defined(OS_ANDROID) 562 #elif defined(OS_ANDROID)
563 android_LogPriority priority = 563 android_LogPriority priority =
564 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN; 564 (severity_ < 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
565 switch (severity_) { 565 switch (severity_) {
566 case LOG_INFO: 566 case LOG_INFO:
567 priority = ANDROID_LOG_INFO; 567 priority = ANDROID_LOG_INFO;
568 break; 568 break;
569 case LOG_WARNING: 569 case LOG_WARNING:
(...skipping 12 matching lines...) Expand all
582 fflush(stderr); 582 fflush(stderr);
583 } else if (severity_ >= kAlwaysPrintErrorLevel) { 583 } else if (severity_ >= kAlwaysPrintErrorLevel) {
584 // When we're only outputting to a log file, above a certain log level, we 584 // When we're only outputting to a log file, above a certain log level, we
585 // should still output to stderr so that we can better detect and diagnose 585 // should still output to stderr so that we can better detect and diagnose
586 // problems with unit tests, especially on the buildbots. 586 // problems with unit tests, especially on the buildbots.
587 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr)); 587 ignore_result(fwrite(str_newline.data(), str_newline.size(), 1, stderr));
588 fflush(stderr); 588 fflush(stderr);
589 } 589 }
590 590
591 // write to log file 591 // write to log file
592 if ((logging_destination & LOG_TO_FILE) != 0) { 592 if ((g_logging_destination & LOG_TO_FILE) != 0) {
593 // We can have multiple threads and/or processes, so try to prevent them 593 // We can have multiple threads and/or processes, so try to prevent them
594 // from clobbering each other's writes. 594 // from clobbering each other's writes.
595 // If the client app did not call InitLogging, and the lock has not 595 // If the client app did not call InitLogging, and the lock has not
596 // been created do it now. We do this on demand, but if two threads try 596 // been created do it now. We do this on demand, but if two threads try
597 // to do this at the same time, there will be a race condition to create 597 // to do this at the same time, there will be a race condition to create
598 // the lock. This is why InitLogging should be called from the main 598 // the lock. This is why InitLogging should be called from the main
599 // thread at the beginning of execution. 599 // thread at the beginning of execution.
600 LoggingLock::Init(LOCK_LOG_FILE, NULL); 600 LoggingLock::Init(LOCK_LOG_FILE, nullptr);
601 LoggingLock logging_lock; 601 LoggingLock logging_lock;
602 if (InitializeLogFileHandle()) { 602 if (InitializeLogFileHandle()) {
603 #if defined(OS_WIN) 603 #if defined(OS_WIN)
604 SetFilePointer(log_file, 0, 0, SEEK_END); 604 SetFilePointer(g_log_file, 0, 0, SEEK_END);
605 DWORD num_written; 605 DWORD num_written;
606 WriteFile(log_file, 606 WriteFile(g_log_file,
607 static_cast<const void*>(str_newline.c_str()), 607 static_cast<const void*>(str_newline.c_str()),
608 static_cast<DWORD>(str_newline.length()), 608 static_cast<DWORD>(str_newline.length()),
609 &num_written, 609 &num_written,
610 NULL); 610 nullptr);
611 #else 611 #else
612 ignore_result(fwrite( 612 ignore_result(fwrite(
613 str_newline.data(), str_newline.size(), 1, log_file)); 613 str_newline.data(), str_newline.size(), 1, g_log_file));
614 fflush(log_file); 614 fflush(g_log_file);
615 #endif 615 #endif
616 } 616 }
617 } 617 }
618 618
619 if (severity_ == LOG_FATAL) { 619 if (severity_ == LOG_FATAL) {
620 // Ensure the first characters of the string are on the stack so they 620 // Ensure the first characters of the string are on the stack so they
621 // are contained in minidumps for diagnostic purposes. 621 // are contained in minidumps for diagnostic purposes.
622 char str_stack[1024]; 622 char str_stack[1024];
623 str_newline.copy(str_stack, arraysize(str_stack)); 623 str_newline.copy(str_stack, arraysize(str_stack));
624 base::debug::Alias(str_stack); 624 base::debug::Alias(str_stack);
(...skipping 19 matching lines...) Expand all
644 // writes the common header info to the stream 644 // writes the common header info to the stream
645 void LogMessage::Init(const char* file, int line) { 645 void LogMessage::Init(const char* file, int line) {
646 base::StringPiece filename(file); 646 base::StringPiece filename(file);
647 size_t last_slash_pos = filename.find_last_of("\\/"); 647 size_t last_slash_pos = filename.find_last_of("\\/");
648 if (last_slash_pos != base::StringPiece::npos) 648 if (last_slash_pos != base::StringPiece::npos)
649 filename.remove_prefix(last_slash_pos + 1); 649 filename.remove_prefix(last_slash_pos + 1);
650 650
651 // TODO(darin): It might be nice if the columns were fixed width. 651 // TODO(darin): It might be nice if the columns were fixed width.
652 652
653 stream_ << '['; 653 stream_ << '[';
654 if (log_process_id) 654 if (g_log_process_id)
655 stream_ << CurrentProcessId() << ':'; 655 stream_ << CurrentProcessId() << ':';
656 if (log_thread_id) 656 if (g_log_thread_id)
657 stream_ << base::PlatformThread::CurrentId() << ':'; 657 stream_ << base::PlatformThread::CurrentId() << ':';
658 if (log_timestamp) { 658 if (g_log_timestamp) {
659 time_t t = time(NULL); 659 time_t t = time(nullptr);
660 struct tm local_time = {0}; 660 struct tm local_time = {0};
661 #ifdef _MSC_VER 661 #ifdef _MSC_VER
662 localtime_s(&local_time, &t); 662 localtime_s(&local_time, &t);
663 #else 663 #else
664 localtime_r(&t, &local_time); 664 localtime_r(&t, &local_time);
665 #endif 665 #endif
666 struct tm* tm_time = &local_time; 666 struct tm* tm_time = &local_time;
667 stream_ << std::setfill('0') 667 stream_ << std::setfill('0')
668 << std::setw(2) << 1 + tm_time->tm_mon 668 << std::setw(2) << 1 + tm_time->tm_mon
669 << std::setw(2) << tm_time->tm_mday 669 << std::setw(2) << tm_time->tm_mday
670 << '/' 670 << '/'
671 << std::setw(2) << tm_time->tm_hour 671 << std::setw(2) << tm_time->tm_hour
672 << std::setw(2) << tm_time->tm_min 672 << std::setw(2) << tm_time->tm_min
673 << std::setw(2) << tm_time->tm_sec 673 << std::setw(2) << tm_time->tm_sec
674 << ':'; 674 << ':';
675 } 675 }
676 if (log_tickcount) 676 if (g_log_tickcount)
677 stream_ << TickCount() << ':'; 677 stream_ << TickCount() << ':';
678 if (severity_ >= 0) 678 if (severity_ >= 0)
679 stream_ << log_severity_name(severity_); 679 stream_ << log_severity_name(severity_);
680 else 680 else
681 stream_ << "VERBOSE" << -severity_; 681 stream_ << "VERBOSE" << -severity_;
682 682
683 stream_ << ":" << filename << "(" << line << ")] "; 683 stream_ << ":" << filename << "(" << line << ")] ";
684 684
685 message_start_ = stream_.str().length(); 685 message_start_ = stream_.str().length();
686 } 686 }
(...skipping 13 matching lines...) Expand all
700 #else 700 #else
701 #error Not implemented 701 #error Not implemented
702 #endif 702 #endif
703 } 703 }
704 704
705 #if defined(OS_WIN) 705 #if defined(OS_WIN)
706 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) { 706 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
707 const int kErrorMessageBufferSize = 256; 707 const int kErrorMessageBufferSize = 256;
708 char msgbuf[kErrorMessageBufferSize]; 708 char msgbuf[kErrorMessageBufferSize];
709 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS; 709 DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
710 DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf, 710 DWORD len = FormatMessageA(flags, nullptr, error_code, 0, msgbuf,
711 arraysize(msgbuf), NULL); 711 arraysize(msgbuf), nullptr);
712 if (len) { 712 if (len) {
713 // Messages returned by system end with line breaks. 713 // Messages returned by system end with line breaks.
714 return base::CollapseWhitespaceASCII(msgbuf, true) + 714 return base::CollapseWhitespaceASCII(msgbuf, true) +
715 base::StringPrintf(" (0x%X)", error_code); 715 base::StringPrintf(" (0x%X)", error_code);
716 } 716 }
717 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)", 717 return base::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
718 GetLastError(), error_code); 718 GetLastError(), error_code);
719 } 719 }
720 #elif defined(OS_POSIX) 720 #elif defined(OS_POSIX)
721 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) { 721 BASE_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
722 return safe_strerror(error_code); 722 return safe_strerror(error_code);
723 } 723 }
724 #else 724 #else
725 #error Not implemented 725 #error Not implemented
726 #endif 726 #endif // defined(OS_WIN)
727 727
728 728
729 #if defined(OS_WIN) 729 #if defined(OS_WIN)
730 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file, 730 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
731 int line, 731 int line,
732 LogSeverity severity, 732 LogSeverity severity,
733 SystemErrorCode err) 733 SystemErrorCode err)
734 : err_(err), 734 : err_(err),
735 log_message_(file, line, severity) { 735 log_message_(file, line, severity) {
736 } 736 }
(...skipping 10 matching lines...) Expand all
747 int line, 747 int line,
748 LogSeverity severity, 748 LogSeverity severity,
749 SystemErrorCode err) 749 SystemErrorCode err)
750 : err_(err), 750 : err_(err),
751 log_message_(file, line, severity) { 751 log_message_(file, line, severity) {
752 } 752 }
753 753
754 ErrnoLogMessage::~ErrnoLogMessage() { 754 ErrnoLogMessage::~ErrnoLogMessage() {
755 stream() << ": " << SystemErrorCodeToString(err_); 755 stream() << ": " << SystemErrorCodeToString(err_);
756 } 756 }
757 #endif // OS_WIN 757 #endif // defined(OS_WIN)
758 758
759 void CloseLogFile() { 759 void CloseLogFile() {
760 LoggingLock logging_lock; 760 LoggingLock logging_lock;
761 CloseLogFileUnlocked(); 761 CloseLogFileUnlocked();
762 } 762 }
763 763
764 void RawLog(int level, const char* message) { 764 void RawLog(int level, const char* message) {
765 if (level >= min_log_level) { 765 if (level >= g_min_log_level) {
766 size_t bytes_written = 0; 766 size_t bytes_written = 0;
767 const size_t message_len = strlen(message); 767 const size_t message_len = strlen(message);
768 int rv; 768 int rv;
769 while (bytes_written < message_len) { 769 while (bytes_written < message_len) {
770 rv = HANDLE_EINTR( 770 rv = HANDLE_EINTR(
771 write(STDERR_FILENO, message + bytes_written, 771 write(STDERR_FILENO, message + bytes_written,
772 message_len - bytes_written)); 772 message_len - bytes_written));
773 if (rv < 0) { 773 if (rv < 0) {
774 // Give up, nothing we can do now. 774 // Give up, nothing we can do now.
775 break; 775 break;
(...skipping 14 matching lines...) Expand all
790 790
791 if (level == LOG_FATAL) 791 if (level == LOG_FATAL)
792 base::debug::BreakDebugger(); 792 base::debug::BreakDebugger();
793 } 793 }
794 794
795 // This was defined at the beginning of this file. 795 // This was defined at the beginning of this file.
796 #undef write 796 #undef write
797 797
798 #if defined(OS_WIN) 798 #if defined(OS_WIN)
799 std::wstring GetLogFileFullPath() { 799 std::wstring GetLogFileFullPath() {
800 if (log_file_name) 800 if (g_log_file_name)
801 return *log_file_name; 801 return *g_log_file_name;
802 return std::wstring(); 802 return std::wstring();
803 } 803 }
804 #endif 804 #endif
805 805
806 } // namespace logging 806 } // namespace logging
807 807
808 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) { 808 std::ostream& std::operator<<(std::ostream& out, const wchar_t* wstr) {
809 return out << base::WideToUTF8(wstr); 809 return out << base::WideToUTF8(wstr);
810 } 810 }
OLDNEW
« no previous file with comments | « no previous file | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698