logging.cc 45.5 KB
Newer Older
gejun's avatar
gejun committed
1
// Copyright (c) 2012 Baidu, Inc.
gejun's avatar
gejun committed
2 3 4 5 6 7 8 9 10 11 12 13 14
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

gejun's avatar
gejun committed
15 16 17
// Author: Ge,Jun (gejun@baidu.com)
// Date: 2012-10-08 23:53:50

18
#include "butil/logging.h"
gejun's avatar
gejun committed
19

20 21
#if !BRPC_WITH_GLOG

gejun's avatar
gejun committed
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
#if defined(OS_WIN)
#include <io.h>
#include <windows.h>
typedef HANDLE FileHandle;
typedef HANDLE MutexHandle;
// Windows warns on using write().  It prefers _write().
#define write(fd, buf, count) _write(fd, buf, static_cast<unsigned int>(count))
// Windows doesn't define STDERR_FILENO.  Define it here.
#define STDERR_FILENO 2
#elif defined(OS_MACOSX)
#include <mach/mach.h>
#include <mach/mach_time.h>
#include <mach-o/dyld.h>
#elif defined(OS_POSIX)
#if defined(OS_NACL) || defined(OS_LINUX)
#include <sys/time.h> // timespec doesn't seem to be in <time.h>
#else
#include <sys/syscall.h>
#endif
#include <time.h>
#endif
#if defined(OS_POSIX)
#include <errno.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define MAX_PATH PATH_MAX
typedef FILE* FileHandle;
typedef pthread_mutex_t* MutexHandle;
#endif

#include <algorithm>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <ostream>
#include <string>

62 63 64 65 66 67 68 69 70 71
#include "butil/file_util.h"
#include "butil/debug/alias.h"
#include "butil/debug/debugger.h"
#include "butil/debug/stack_trace.h"
#include "butil/posix/eintr_wrapper.h"
#include "butil/strings/string_util.h"
#include "butil/strings/stringprintf.h"
#include "butil/strings/utf_string_conversions.h"
#include "butil/synchronization/lock.h"
#include "butil/threading/platform_thread.h"
gejun's avatar
gejun committed
72
#if defined(OS_POSIX)
73 74
#include "butil/errno.h"
#include "butil/fd_guard.h"
gejun's avatar
gejun committed
75 76 77 78 79 80 81 82 83 84 85 86 87 88
#endif
#if defined(OS_LINUX)
#include <fcntl.h>
#endif

#if defined(OS_ANDROID)
#include <android/log.h>
#endif

#include <map>
#include <vector>
#include <deque>
#include <limits>
#include <gflags/gflags.h>
89 90 91 92 93 94 95 96
#include "butil/atomicops.h"
#include "butil/thread_local.h"
#include "butil/scoped_lock.h"                        // BAIDU_SCOPED_LOCK
#include "butil/string_splitter.h"
#include "butil/time.h"
#include "butil/containers/doubly_buffered_data.h"
#include "butil/memory/singleton.h"
#include "butil/endpoint.h"
gejun's avatar
gejun committed
97
#ifdef BAIDU_INTERNAL
98
#include "butil/comlog_sink.h"
gejun's avatar
gejun committed
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
#endif

extern "C" {
uint64_t BAIDU_WEAK bthread_self();
typedef struct {
    uint32_t index;    // index in KeyTable
    uint32_t version;  // ABA avoidance
} bthread_key_t;
int BAIDU_WEAK bthread_key_create(bthread_key_t* key,
                                  void (*destructor)(void* data));
int BAIDU_WEAK bthread_setspecific(bthread_key_t key, void* data);
void* BAIDU_WEAK bthread_getspecific(bthread_key_t key);
}

namespace logging {

DEFINE_bool(crash_on_fatal_log, false,
            "Crash process when a FATAL log is printed");
DEFINE_bool(print_stack_on_check, true,
            "Print the stack trace when a CHECK was failed");

120 121 122
DEFINE_int32(v, 0, "Show all VLOG(m) messages for m <= this."
             " Overridable by --vmodule.");
DEFINE_string(vmodule, "", "per-module verbose level."
gejun's avatar
gejun committed
123 124 125
              " Argument is a comma-separated list of MODULE_NAME=LOG_LEVEL."
              " MODULE_NAME is a glob pattern, matched against the filename base"
              " (that is, name ignoring .cpp/.h)."
126
              " LOG_LEVEL overrides any value given by --v.");
gejun's avatar
gejun committed
127 128 129

DEFINE_bool(log_process_id, false, "Log process id");

130
DEFINE_int32(minloglevel, 0, "Any log at or above this level will be "
gejun's avatar
gejun committed
131 132 133
             "displayed. Anything below this level will be silently ignored. "
             "0=INFO 1=NOTICE 2=WARNING 3=ERROR 4=FATAL");

gejun's avatar
gejun committed
134
DEFINE_bool(log_hostname, false, "Add host after pid in each log so"
gejun's avatar
gejun committed
135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
            " that we know where logs came from when using aggregation tools"
            " like ELK.");

DEFINE_bool(log_year, false, "Log year in datetime part in each log");

namespace {

LoggingDestination logging_destination = LOG_DEFAULT;

// For BLOG_ERROR and above, always print to stderr.
const int kAlwaysPrintErrorLevel = BLOG_ERROR;

// Which log file to use? This is initialized by InitLogging or
// will be lazily initialized to the default value when it is
// first needed.
#if defined(OS_WIN)
typedef std::wstring PathString;
#else
typedef std::string PathString;
#endif
PathString* log_file_name = NULL;

// this file is lazily opened and the handle may be NULL
FileHandle log_file = NULL;

// Should we pop up fatal debug messages in a dialog?
bool show_error_dialogs = false;

// An assert handler override specified by the client to be called instead of
// the debug message dialog and process termination.
LogAssertHandler log_assert_handler = NULL;

// Helper functions to wrap platform differences.

int32_t CurrentProcessId() {
#if defined(OS_WIN)
    return GetCurrentProcessId();
#elif defined(OS_POSIX)
    return getpid();
#endif
}

void DeleteFilePath(const PathString& log_name) {
#if defined(OS_WIN)
    DeleteFile(log_name.c_str());
#elif defined (OS_NACL)
    // Do nothing; unlink() isn't supported on NaCl.
#else
    unlink(log_name.c_str());
#endif
}

#if defined(OS_LINUX)
static PathString GetProcessName() {
189
    butil::fd_guard fd(open("/proc/self/cmdline", O_RDONLY));
gejun's avatar
gejun committed
190 191 192 193 194 195 196 197 198 199 200
    if (fd < 0) {
        return "unknown";
    }
    char buf[512];
    const ssize_t len = read(fd, buf, sizeof(buf) - 1);
    if (len <= 0) {
        return "unknown";
    }
    buf[len] = '\0';
    // Not string(buf, len) because we needs to buf to be truncated at first \0.
    // Under gdb, the first part of cmdline may include path.
201
    return butil::FilePath(std::string(buf)).BaseName().value();
gejun's avatar
gejun committed
202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
}
#endif

PathString GetDefaultLogFile() {
#if defined(OS_WIN)
    // On Windows we use the same path as the exe.
    wchar_t module_name[MAX_PATH];
    GetModuleFileName(NULL, module_name, MAX_PATH);

    PathString log_file = module_name;
    PathString::size_type last_backslash =
        log_file.rfind('\\', log_file.size());
    if (last_backslash != PathString::npos)
        log_file.erase(last_backslash + 1);
    log_file += L"debug.log";
    return log_file;
#elif defined(OS_LINUX)
    return GetProcessName() + ".log";
#elif defined(OS_POSIX)    
    // On other platforms we just use the current directory.
    return PathString("debug.log");
#endif
}

// This class acts as a wrapper for locking the logging files.
// LoggingLock::Init() should be called from the main thread before any logging
// is done. Then whenever logging, be sure to have a local LoggingLock
// instance on the stack. This will ensure that the lock is unlocked upon
// exiting the frame.
// LoggingLocks can not be nested.
class LoggingLock {
public:
    LoggingLock() {
        LockLogging();
    }

    ~LoggingLock() {
        UnlockLogging();
    }

    static void Init(LogLockingState lock_log, const PathChar* new_log_file) {
        if (initialized)
            return;
        lock_log_file = lock_log;
        if (lock_log_file == LOCK_LOG_FILE) {
#if defined(OS_WIN)
            if (!log_mutex) {
                std::wstring safe_name;
                if (new_log_file)
                    safe_name = new_log_file;
                else
                    safe_name = GetDefaultLogFile();
                // \ is not a legal character in mutex names so we replace \ with /
                std::replace(safe_name.begin(), safe_name.end(), '\\', '/');
                std::wstring t(L"Global\\");
                t.append(safe_name);
                log_mutex = ::CreateMutex(NULL, FALSE, t.c_str());

                if (log_mutex == NULL) {
#if DEBUG
                    // Keep the error code for debugging
                    int error = GetLastError();  // NOLINT
264
                    butil::debug::BreakDebugger();
gejun's avatar
gejun committed
265 266 267 268 269 270 271
#endif
                    // Return nicely without putting initialized to true.
                    return;
                }
            }
#endif
        } else {
272
            log_lock = new butil::Mutex;
gejun's avatar
gejun committed
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
        }
        initialized = true;
    }

private:
    static void LockLogging() {
        if (lock_log_file == LOCK_LOG_FILE) {
#if defined(OS_WIN)
            ::WaitForSingleObject(log_mutex, INFINITE);
            // WaitForSingleObject could have returned WAIT_ABANDONED. We don't
            // abort the process here. UI tests might be crashy sometimes,
            // and aborting the test binary only makes the problem worse.
            // We also don't use LOG macros because that might lead to an infinite
            // loop. For more info see http://crbug.com/18028.
#elif defined(OS_POSIX)
            pthread_mutex_lock(&log_mutex);
#endif
        } else {
            // use the lock
            log_lock->lock();
        }
    }

    static void UnlockLogging() {
        if (lock_log_file == LOCK_LOG_FILE) {
#if defined(OS_WIN)
            ReleaseMutex(log_mutex);
#elif defined(OS_POSIX)
            pthread_mutex_unlock(&log_mutex);
#endif
        } else {
            log_lock->unlock();
        }
    }

    // The lock is used if log file locking is false. It helps us avoid problems
    // with multiple threads writing to the log file at the same time.
310
    static butil::Mutex* log_lock;
gejun's avatar
gejun committed
311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326

    // When we don't use a lock, we are using a global mutex. We need to do this
    // because LockFileEx is not thread safe.
#if defined(OS_WIN)
    static MutexHandle log_mutex;
#elif defined(OS_POSIX)
    static pthread_mutex_t log_mutex;
#endif

    static bool initialized;
    static LogLockingState lock_log_file;
};

// static
bool LoggingLock::initialized = false;
// static
327
butil::Mutex* LoggingLock::log_lock = NULL;
gejun's avatar
gejun committed
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
// static
LogLockingState LoggingLock::lock_log_file = LOCK_LOG_FILE;

#if defined(OS_WIN)
// static
MutexHandle LoggingLock::log_mutex = NULL;
#elif defined(OS_POSIX)
pthread_mutex_t LoggingLock::log_mutex = PTHREAD_MUTEX_INITIALIZER;
#endif

// Called by logging functions to ensure that debug_file is initialized
// and can be used for writing. Returns false if the file could not be
// initialized. debug_file will be NULL in this case.
bool InitializeLogFileHandle() {
    if (log_file)
        return true;

    if (!log_file_name) {
        // Nobody has called InitLogging to specify a debug log file, so here we
        // initialize the log file name to a default.
        log_file_name = new PathString(GetDefaultLogFile());
    }

    if ((logging_destination & LOG_TO_FILE) != 0) {
#if defined(OS_WIN)
        log_file = CreateFile(log_file_name->c_str(), GENERIC_WRITE,
                              FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                              OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
        if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
            // try the current directory
            log_file = CreateFile(L".\\debug.log", GENERIC_WRITE,
                                  FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
                                  OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
            if (log_file == INVALID_HANDLE_VALUE || log_file == NULL) {
                log_file = NULL;
                return false;
            }
        }
        SetFilePointer(log_file, 0, 0, FILE_END);
#elif defined(OS_POSIX)
        log_file = fopen(log_file_name->c_str(), "a");
        if (log_file == NULL) {
            fprintf(stderr, "Fail to fopen %s", log_file_name->c_str());
            return false;
        }
#endif
    }

    return true;
}

void CloseFile(FileHandle log) {
#if defined(OS_WIN)
    CloseHandle(log);
#else
    fclose(log);
#endif
}

void CloseLogFileUnlocked() {
    if (!log_file)
        return;

    CloseFile(log_file);
    log_file = NULL;
}

}  // namespace

LoggingSettings::LoggingSettings()
    : logging_dest(LOG_DEFAULT),
      log_file(NULL),
      lock_log(LOCK_LOG_FILE),
      delete_old(APPEND_TO_OLD_LOG_FILE) {}

bool BaseInitLoggingImpl(const LoggingSettings& settings) {
#if defined(OS_NACL)
    // Can log only to the system debug log.
    CHECK_EQ(settings.logging_dest & ~LOG_TO_SYSTEM_DEBUG_LOG, 0);
#endif

    logging_destination = settings.logging_dest;

    // ignore file options unless logging to file is set.
    if ((logging_destination & LOG_TO_FILE) == 0)
        return true;

    LoggingLock::Init(settings.lock_log, settings.log_file);
    LoggingLock logging_lock;

    // Calling InitLogging twice or after some log call has already opened the
    // default log file will re-initialize to the new options.
    CloseLogFileUnlocked();

    if (!log_file_name)
        log_file_name = new PathString();
    if (settings.log_file) {
        *log_file_name = settings.log_file;
    } else {
        *log_file_name = GetDefaultLogFile();
    }
    if (settings.delete_old == DELETE_OLD_LOG_FILE)
        DeleteFilePath(*log_file_name);

    return InitializeLogFileHandle();
}

void SetMinLogLevel(int level) {
436
    FLAGS_minloglevel = std::min(BLOG_FATAL, level);
gejun's avatar
gejun committed
437 438 439
}

int GetMinLogLevel() {
440
    return FLAGS_minloglevel;
gejun's avatar
gejun committed
441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
}

void SetShowErrorDialogs(bool enable_dialogs) {
    show_error_dialogs = enable_dialogs;
}

void SetLogAssertHandler(LogAssertHandler handler) {
    log_assert_handler = handler;
}

const char* const log_severity_names[LOG_NUM_SEVERITIES] = {
    "INFO", "NOTICE", "WARNING", "ERROR", "FATAL" };

inline void log_severity_name(std::ostream& os, int severity) {
    if (severity < 0) {
        // Add extra space to separate from following datetime.
        os << 'V' << -severity << ' ';
    } else if (severity < LOG_NUM_SEVERITIES) {
        os << log_severity_names[severity][0];
    } else {
        os << 'U';
    }
}

void print_log_prefix(std::ostream& os,
                      int severity, const char* file, int line) {
    log_severity_name(os, severity);
#if defined(OS_LINUX)
    timeval tv;
    gettimeofday(&tv, NULL);
    time_t t = tv.tv_sec;
#else
    time_t t = time(NULL);
#endif
    struct tm local_tm = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, NULL};
#if _MSC_VER >= 1400
    localtime_s(&local_tm, &t);
#else
    localtime_r(&t, &local_tm);
#endif
    const char prev_fill = os.fill('0');
    if (FLAGS_log_year) {
        os << std::setw(4) << local_tm.tm_year + 1900;
    }
    os << std::setw(2) << local_tm.tm_mon + 1
       << std::setw(2) << local_tm.tm_mday << ' '
       << std::setw(2) << local_tm.tm_hour << ':'
       << std::setw(2) << local_tm.tm_min << ':'
       << std::setw(2) << local_tm.tm_sec;
#if defined(OS_LINUX)
    os << '.' << std::setw(6) << tv.tv_usec;
#endif
    if (FLAGS_log_process_id) {
        os << ' ' << std::setfill(' ') << std::setw(5) << CurrentProcessId();
    }
    os << ' ' << std::setfill(' ') << std::setw(5)
497
       << butil::PlatformThread::CurrentId() << std::setfill('0');
gejun's avatar
gejun committed
498
    if (FLAGS_log_hostname) {
499
        butil::StringPiece hostname(butil::my_hostname());
gejun's avatar
gejun committed
500 501 502 503 504 505 506 507 508 509
        if (hostname.ends_with(".baidu.com")) { // make it shorter
            hostname.remove_suffix(10);
        }
        os << ' ' << hostname;
    }
    os << ' ' << file << ':' << line << "] ";
    os.fill(prev_fill);
}

// A log message handler that gets notified of every log message we process.
510
class DoublyBufferedLogSink : public butil::DoublyBufferedData<LogSink*> {
gejun's avatar
gejun committed
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582
public:
    DoublyBufferedLogSink() {}
    static DoublyBufferedLogSink* GetInstance();
private:
friend struct DefaultSingletonTraits<DoublyBufferedLogSink>;
    DISALLOW_COPY_AND_ASSIGN(DoublyBufferedLogSink);
};

DoublyBufferedLogSink* DoublyBufferedLogSink::GetInstance() {
    return Singleton<DoublyBufferedLogSink,
                     LeakySingletonTraits<DoublyBufferedLogSink> >::get();
}

struct SetLogSinkFn {
    LogSink* new_sink;
    LogSink* old_sink;

    bool operator()(LogSink*& ptr) {
        old_sink = ptr;
        ptr = new_sink;
        return true;
    }
};

LogSink* SetLogSink(LogSink* sink) {
    SetLogSinkFn fn = { sink, NULL };
    CHECK(DoublyBufferedLogSink::GetInstance()->Modify(fn));
    return fn.old_sink;
}

// MSVC doesn't like complex extern templates and DLLs.
#if !defined(COMPILER_MSVC)
// Explicit instantiations for commonly used comparisons.
template std::string* MakeCheckOpString<int, int>(
    const int&, const int&, const char* names);
template std::string* MakeCheckOpString<unsigned long, unsigned long>(
    const unsigned long&, const unsigned long&, const char* names);
template std::string* MakeCheckOpString<unsigned long, unsigned int>(
    const unsigned long&, const unsigned int&, const char* names);
template std::string* MakeCheckOpString<unsigned int, unsigned long>(
    const unsigned int&, const unsigned long&, const char* names);
template std::string* MakeCheckOpString<std::string, std::string>(
    const std::string&, const std::string&, const char* name);
#endif

#if !defined(NDEBUG)
// Displays a message box to the user with the error message in it.
// Used for fatal messages, where we close the app simultaneously.
// This is for developers only; we don't use this in circumstances
// (like release builds) where users could see it, since users don't
// understand these messages anyway.
void DisplayDebugMessageInDialog(const std::string& str) {
    if (str.empty())
        return;

    if (!show_error_dialogs)
        return;

#if defined(OS_WIN)
    // For Windows programs, it's possible that the message loop is
    // messed up on a fatal error, and creating a MessageBox will cause
    // that message loop to be run. Instead, we try to spawn another
    // process that displays its command line. We look for "Debug
    // Message.exe" in the same directory as the application. If it
    // exists, we use it, otherwise, we use a regular message box.
    wchar_t prog_name[MAX_PATH];
    GetModuleFileNameW(NULL, prog_name, MAX_PATH);
    wchar_t* backslash = wcsrchr(prog_name, '\\');
    if (backslash)
        backslash[1] = 0;
    wcscat_s(prog_name, MAX_PATH, L"debug_message.exe");

583
    std::wstring cmdline = butil::UTF8ToWide(str);
gejun's avatar
gejun committed
584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
    if (cmdline.empty())
        return;

    STARTUPINFO startup_info;
    memset(&startup_info, 0, sizeof(startup_info));
    startup_info.cb = sizeof(startup_info);

    PROCESS_INFORMATION process_info;
    if (CreateProcessW(prog_name, &cmdline[0], NULL, NULL, false, 0, NULL,
                       NULL, &startup_info, &process_info)) {
        WaitForSingleObject(process_info.hProcess, INFINITE);
        CloseHandle(process_info.hThread);
        CloseHandle(process_info.hProcess);
    } else {
        // debug process broken, let's just do a message box
        MessageBoxW(NULL, &cmdline[0], L"Fatal error",
                    MB_OK | MB_ICONHAND | MB_TOPMOST);
    }
#else
    // We intentionally don't implement a dialog on other platforms.
    // You can just look at stderr.
#endif
}
#endif  // !defined(NDEBUG)


bool StringSink::OnLogMessage(int severity, const char* file, int line, 
611
                              const butil::StringPiece& content) {
gejun's avatar
gejun committed
612 613 614 615
    std::ostringstream prefix_os;
    print_log_prefix(prefix_os, severity, file, line);
    const std::string prefix = prefix_os.str();
    {
616
        butil::AutoLock lock_guard(_lock);
gejun's avatar
gejun committed
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
        reserve(size() + prefix.size() + content.size());
        append(prefix);
        append(content.data(), content.size());
    }
    return true;
}

CharArrayStreamBuf::~CharArrayStreamBuf() {
    free(_data);
}

int CharArrayStreamBuf::overflow(int ch) {
    if (ch == std::streambuf::traits_type::eof()) {
        return ch;
    }
    size_t new_size = std::max(_size * 3 / 2, (size_t)64);
    char* new_data = (char*)malloc(new_size);
    if (BAIDU_UNLIKELY(new_data == NULL)) {
        setp(NULL, NULL);
        return std::streambuf::traits_type::eof();
    }
    memcpy(new_data, _data, _size);
    free(_data);
    _data = new_data;
    const size_t old_size = _size;
    _size = new_size;
    setp(_data, _data + new_size);
    pbump(old_size);
    // if size == 1, this function will call overflow again.
    return sputc(ch);
}

int CharArrayStreamBuf::sync() {
    // data are already there.
    return 0;
}

void CharArrayStreamBuf::reset() {
    setp(_data, _data + _size);
}

LogStream& LogStream::SetPosition(const PathChar* file, int line,
                                  LogSeverity severity) {
    _file = file;
    _line = line;
    _severity = severity;
    return *this;
}

#if defined(__GNUC__)
static bthread_key_t stream_bkey;
static pthread_key_t stream_pkey;
static pthread_once_t create_stream_key_once = PTHREAD_ONCE_INIT;
inline bool is_bthread_linked() { return bthread_key_create != NULL; }
static void destroy_tls_streams(void* data) {
    if (data == NULL) {
        return;
    }
    LogStream** a = (LogStream**)data;
    for (int i = 0; i <= LOG_NUM_SEVERITIES; ++i) {
        delete a[i];
    }
    delete[] a;
}
static void create_stream_key_or_die() {
    if (is_bthread_linked()) {
        int rc = bthread_key_create(&stream_bkey, destroy_tls_streams);
        if (rc) {
            fprintf(stderr, "Fail to bthread_key_create");
            exit(1);
        }
    } else {
        int rc = pthread_key_create(&stream_pkey, destroy_tls_streams);
        if (rc) {
            fprintf(stderr, "Fail to pthread_key_create");
            exit(1);
        }
    }
}
static LogStream** get_tls_stream_array() {
    pthread_once(&create_stream_key_once, create_stream_key_or_die);
    if (is_bthread_linked()) {
        return (LogStream**)bthread_getspecific(stream_bkey);
    } else {
        return (LogStream**)pthread_getspecific(stream_pkey);
    }
}

static LogStream** get_or_new_tls_stream_array() {
    LogStream** a = get_tls_stream_array();
    if (a == NULL) {
        a = new LogStream*[LOG_NUM_SEVERITIES + 1];
        memset(a, 0, sizeof(LogStream*) * (LOG_NUM_SEVERITIES + 1));
        if (is_bthread_linked()) {
            bthread_setspecific(stream_bkey, a);
        } else {
            pthread_setspecific(stream_pkey, a);
        }
    }
    return a;
}

inline LogStream* CreateLogStream(const PathChar* file, int line,
                                  LogSeverity severity) {
    int slot = 0;
    if (severity >= 0) {
        DCHECK_LT(severity, LOG_NUM_SEVERITIES);
        slot = severity + 1;
    } // else vlog
    LogStream** stream_array = get_or_new_tls_stream_array();
    LogStream* stream = stream_array[slot];
    if (stream == NULL) {
        stream = new LogStream;
        stream_array[slot] = stream;
    }
    if (stream->empty()) {
        stream->SetPosition(file, line, severity);
    }
    return stream;
}

inline void DestroyLogStream(LogStream* stream) {
    if (stream != NULL) {
        stream->Flush();
    }
}

#else

inline LogStream* CreateLogStream(const PathChar* file, int line,
                                  LogSeverity severity) {
    LogStream* stream = new LogStream;
    stream->SetPosition(file, line, severity);
    return stream;
}

inline void DestroyLogStream(LogStream* stream) {
    delete stream;
}

#endif  // __GNUC__

class DefaultLogSink : public LogSink {
public:
    static DefaultLogSink* GetInstance() {
        return Singleton<DefaultLogSink,
                         LeakySingletonTraits<DefaultLogSink> >::get();
    }

    bool OnLogMessage(int severity, const char* file, int line,
767
                      const butil::StringPiece& content) {
gejun's avatar
gejun committed
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
        // There's a copy here to concatenate prefix and content. Since
        // DefaultLogSink is hardly used right now, the copy is irrelevant.
        // A LogSink focused on performance should also be able to handle
        // non-continuous inputs which is a must to maximize performance.
        std::ostringstream os;
        print_log_prefix(os, severity, file, line);
        os.write(content.data(), content.size());
        os << '\n';
        std::string log = os.str();
        
        if ((logging_destination & LOG_TO_SYSTEM_DEBUG_LOG) != 0) {
            fwrite(log.data(), log.size(), 1, stderr);
            fflush(stderr);
        } else if (severity >= kAlwaysPrintErrorLevel) {
            // When we're only outputting to a log file, above a certain log level, we
            // should still output to stderr so that we can better detect and diagnose
            // problems with unit tests, especially on the buildbots.
            fwrite(log.data(), log.size(), 1, stderr);
            fflush(stderr);
        }

        // write to log file
        if ((logging_destination & LOG_TO_FILE) != 0) {
            // We can have multiple threads and/or processes, so try to prevent them
            // from clobbering each other's writes.
            // If the client app did not call InitLogging, and the lock has not
            // been created do it now. We do this on demand, but if two threads try
            // to do this at the same time, there will be a race condition to create
            // the lock. This is why InitLogging should be called from the main
            // thread at the beginning of execution.
            LoggingLock::Init(LOCK_LOG_FILE, NULL);
            LoggingLock logging_lock;
            if (InitializeLogFileHandle()) {
#if defined(OS_WIN)
                SetFilePointer(log_file, 0, 0, SEEK_END);
                DWORD num_written;
                WriteFile(log_file,
                          static_cast<const void*>(log.data()),
                          static_cast<DWORD>(log.size()),
                          &num_written,
                          NULL);
#else
                fwrite(log.data(), log.size(), 1, log_file);
                fflush(log_file);
#endif
            }
        }
        return true;
    }
private:
    DefaultLogSink() {}
    ~DefaultLogSink() {}
friend struct DefaultSingletonTraits<DefaultLogSink>;
};

void LogStream::FlushWithoutReset() {
    if (empty()) {
        // Nothing to flush.
        return;
    }

#if !defined(OS_NACL) && !defined(__UCLIBC__)
    if (FLAGS_print_stack_on_check && _is_check && _severity == BLOG_FATAL) {
        // Include a stack trace on a fatal.
832
        butil::debug::StackTrace trace;
gejun's avatar
gejun committed
833 834 835 836 837 838 839
        size_t count = 0;
        const void* const* addrs = trace.Addresses(&count);

        *this << std::endl;  // Newline to separate from log message.
        if (count > 3) {
            // Remove top 3 frames which are useless to users.
            // #2 may be ~LogStream
840
            //   #0 0x00000059ccae butil::debug::StackTrace::StackTrace()
gejun's avatar
gejun committed
841 842
            //   #1 0x0000005947c7 logging::LogStream::FlushWithoutReset()
            //   #2 0x000000594b88 logging::LogMessage::~LogMessage()
843
            butil::debug::StackTrace trace_stripped(addrs + 3, count - 3);
gejun's avatar
gejun committed
844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891
            trace_stripped.OutputToStream(this);
        } else {
            trace.OutputToStream(this);
        }
    }
#endif
    // End the data with zero because sink is likely to assume this.
    *this << std::ends;
    // Move back one step because we don't want to count the zero.
    pbump(-1); 

    // Give any logsink first dibs on the message.
#ifdef BAIDU_INTERNAL
    // If the logsink fails and it's not comlog, try comlog. stderr on last try.
    bool tried_comlog = false;
#endif
    bool tried_default = false;
    {
        DoublyBufferedLogSink::ScopedPtr ptr;
        if (DoublyBufferedLogSink::GetInstance()->Read(&ptr) == 0 &&
            (*ptr) != NULL) {
            if ((*ptr)->OnLogMessage(_severity, _file, _line, content())) {
                goto FINISH_LOGGING;
            }
#ifdef BAIDU_INTERNAL
            tried_comlog = (*ptr == ComlogSink::GetInstance());
#endif
            tried_default = (*ptr == DefaultLogSink::GetInstance());
        }
    }

#ifdef BAIDU_INTERNAL
    if (!tried_comlog) {
        if (ComlogSink::GetInstance()->OnLogMessage(
                _severity, _file, _line, content())) {
            goto FINISH_LOGGING;
        }
    }
#endif
    if (!tried_default) {
        DefaultLogSink::GetInstance()->OnLogMessage(
            _severity, _file, _line, content());
    }

FINISH_LOGGING:
    if (FLAGS_crash_on_fatal_log && _severity == BLOG_FATAL) {
        // Ensure the first characters of the string are on the stack so they
        // are contained in minidumps for diagnostic purposes.
892
        butil::StringPiece str = content();
gejun's avatar
gejun committed
893 894
        char str_stack[1024];
        str.copy(str_stack, arraysize(str_stack));
895
        butil::debug::Alias(str_stack);
gejun's avatar
gejun committed
896 897 898 899 900 901 902 903 904 905 906 907 908 909

        if (log_assert_handler) {
            // Make a copy of the string for the handler out of paranoia.
            log_assert_handler(str.as_string());
        } else {
            // Don't use the string with the newline, get a fresh version to send to
            // the debug message process. We also don't display assertions to the
            // user in release mode. The enduser can't do anything with this
            // information, and displaying message boxes when the application is
            // hosed can cause additional problems.
#ifndef NDEBUG
            DisplayDebugMessageInDialog(str.as_string());
#endif
            // Crash the process to generate a dump.
910
            butil::debug::BreakDebugger();
gejun's avatar
gejun committed
911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963
        }
    }
}

LogMessage::LogMessage(const char* file, int line, LogSeverity severity) {
    _stream = CreateLogStream(file, line, severity);
}

LogMessage::LogMessage(const char* file, int line, std::string* result) {
    _stream = CreateLogStream(file, line, BLOG_FATAL);
    *_stream << "Check failed: " << *result;
    delete result;
}

LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
                       std::string* result) {
    _stream = CreateLogStream(file, line, severity);
    *_stream << "Check failed: " << *result;
    delete result;
}

LogMessage::~LogMessage() {
    DestroyLogStream(_stream);
}

#if defined(OS_WIN)
// This has already been defined in the header, but defining it again as DWORD
// ensures that the type used in the header is equivalent to DWORD. If not,
// the redefinition is a compile error.
typedef DWORD SystemErrorCode;
#endif

SystemErrorCode GetLastSystemErrorCode() {
#if defined(OS_WIN)
    return ::GetLastError();
#elif defined(OS_POSIX)
    return errno;
#else
#error Not implemented
#endif
}

void SetLastSystemErrorCode(SystemErrorCode err) {
#if defined(OS_WIN)
    ::SetLastError(err);
#elif defined(OS_POSIX)
    errno = err;
#else
#error Not implemented
#endif
}

#if defined(OS_WIN)
964
BUTIL_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
gejun's avatar
gejun committed
965 966 967 968 969 970 971
    const int error_message_buffer_size = 256;
    char msgbuf[error_message_buffer_size];
    DWORD flags = FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS;
    DWORD len = FormatMessageA(flags, NULL, error_code, 0, msgbuf,
                               arraysize(msgbuf), NULL);
    if (len) {
        // Messages returned by system end with line breaks.
972 973
        return butil::CollapseWhitespaceASCII(msgbuf, true) +
            butil::StringPrintf(" (0x%X)", error_code);
gejun's avatar
gejun committed
974
    }
975
    return butil::StringPrintf("Error (0x%X) while retrieving error. (0x%X)",
gejun's avatar
gejun committed
976 977 978
                              GetLastError(), error_code);
}
#elif defined(OS_POSIX)
979
BUTIL_EXPORT std::string SystemErrorCodeToString(SystemErrorCode error_code) {
gejun's avatar
gejun committed
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
    return berror(error_code);
}
#else
#error Not implemented
#endif


#if defined(OS_WIN)
Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
                                           int line,
                                           LogSeverity severity,
                                           SystemErrorCode err)
    : err_(err),
      log_message_(file, line, severity) {
}

Win32ErrorLogMessage::~Win32ErrorLogMessage() {
    stream() << ": " << SystemErrorCodeToString(err_);
    // We're about to crash (CHECK). Put |err_| on the stack (by placing it in a
    // field) and use Alias in hopes that it makes it into crash dumps.
    DWORD last_error = err_;
1001
    butil::debug::Alias(&last_error);
gejun's avatar
gejun committed
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
}
#elif defined(OS_POSIX)
ErrnoLogMessage::ErrnoLogMessage(const char* file,
                                 int line,
                                 LogSeverity severity,
                                 SystemErrorCode err)
    : err_(err),
      log_message_(file, line, severity) {
}

ErrnoLogMessage::~ErrnoLogMessage() {
    stream() << ": " << SystemErrorCodeToString(err_);
}
#endif  // OS_WIN

void CloseLogFile() {
    LoggingLock logging_lock;
    CloseLogFileUnlocked();
}

void RawLog(int level, const char* message) {
1023
    if (level >= FLAGS_minloglevel) {
gejun's avatar
gejun committed
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049
        size_t bytes_written = 0;
        const size_t message_len = strlen(message);
        int rv;
        while (bytes_written < message_len) {
            rv = HANDLE_EINTR(
                write(STDERR_FILENO, message + bytes_written,
                      message_len - bytes_written));
            if (rv < 0) {
                // Give up, nothing we can do now.
                break;
            }
            bytes_written += rv;
        }

        if (message_len > 0 && message[message_len - 1] != '\n') {
            do {
                rv = HANDLE_EINTR(write(STDERR_FILENO, "\n", 1));
                if (rv < 0) {
                    // Give up, nothing we can do now.
                    break;
                }
            } while (rv != 1);
        }
    }

    if (FLAGS_crash_on_fatal_log && level == BLOG_FATAL)
1050
        butil::debug::BreakDebugger();
gejun's avatar
gejun committed
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084
}

// This was defined at the beginning of this file.
#undef write

#if defined(OS_WIN)
std::wstring GetLogFileFullPath() {
    if (log_file_name)
        return *log_file_name;
    return std::wstring();
}
#endif


// ----------- VLOG stuff -----------------
struct VLogSite;
struct VModuleList;

extern const int VLOG_UNINITIALIZED = std::numeric_limits<int>::max();

static pthread_mutex_t vlog_site_list_mutex = PTHREAD_MUTEX_INITIALIZER;
static VLogSite* vlog_site_list = NULL;
static VModuleList* vmodule_list = NULL;

static pthread_mutex_t reset_vmodule_and_v_mutex = PTHREAD_MUTEX_INITIALIZER;

static const int64_t DELAY_DELETION_SEC = 10;
static std::deque<std::pair<VModuleList*, int64_t> >*
deleting_vmodule_list = NULL;

struct VLogSite {
    VLogSite(const char* filename, int required_v, int line_no)
        : _next(0), _v(0), _required_v(required_v), _line_no(line_no) {
        // Remove dirname/extname.
1085
        butil::StringPiece s(filename);
gejun's avatar
gejun committed
1086
        size_t pos = s.find_last_of("./");
1087
        if (pos != butil::StringPiece::npos) {
gejun's avatar
gejun committed
1088 1089 1090 1091
            if (s[pos] == '.') {
                s.remove_suffix(s.size() - pos);
                _full_module.assign(s.data(), s.size());
                size_t pos2 = s.find_last_of('/');
1092
                if (pos2 != butil::StringPiece::npos) {
gejun's avatar
gejun committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110
                    s.remove_prefix(pos2 + 1);
                }
            } else {
                _full_module.assign(s.data(), s.size());
                s.remove_prefix(pos + 1);
            }
        } // else keep _full_module empty when it equals _module
        _module.assign(s.data(), s.size());
        std::transform(_module.begin(), _module.end(),
                       _module.begin(), ::tolower);
        if (!_full_module.empty()) {
            std::transform(_full_module.begin(), _full_module.end(),
                           _full_module.begin(), ::tolower);
        }
    }

    // The consume/release fence makes the iteration outside lock see
    // newly added VLogSite correctly.
1111
    VLogSite* next() { return (VLogSite*)butil::subtle::Acquire_Load(&_next); }
gejun's avatar
gejun committed
1112
    const VLogSite* next() const
1113
    { return (VLogSite*)butil::subtle::Acquire_Load(&_next); }
gejun's avatar
gejun committed
1114
    void set_next(VLogSite* next)
1115
    { butil::subtle::Release_Store(&_next, (butil::subtle::AtomicWord)next); }
gejun's avatar
gejun committed
1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127

    int v() const { return _v; }
    int& v() { return _v; }

    int required_v() const { return  _required_v; }
    int line_no() const { return _line_no; }

    const std::string& module() const { return _module; }
    const std::string& full_module() const { return _full_module; }
    
private:
    // Next site in the list. NULL means no next.
1128
    butil::subtle::AtomicWord _next;
gejun's avatar
gejun committed
1129

1130
    // --vmodule > --v
gejun's avatar
gejun committed
1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187
    int _v;
    
    // vlog is on iff _v >= _required_v
    int _required_v;

    // line nubmer of the vlog.
    int _line_no;
    
    // Lowered, dirname & extname removed.
    std::string _module;
    // Lowered, extname removed. Empty when it equals to _module.
    std::string _full_module;
};

// Written by Jack Handy
// <A href="mailto:jakkhandy@hotmail.com">jakkhandy@hotmail.com</A>
bool wildcmp(const char* wild, const char* str) {
    const char* cp = NULL;
    const char* mp = NULL;

    while (*str && *wild != '*') {
        if (*wild != *str && *wild != '?') {
            return false;
        }
        ++wild;
        ++str;
    }

    while (*str) {
        if (*wild == '*') {
            if (!*++wild) {
                return true;
            }
            mp = wild;
            cp = str+1;
        } else if (*wild == *str || *wild == '?') {
            ++wild;
            ++str;
        } else {
            wild = mp;
            str = cp++;
        }
    }

    while (*wild == '*') {
        ++wild;
    }
    return !*wild;
}

struct VModuleList {
    VModuleList() {}

    int init(const char* vmodules) {
        _exact_names.clear();
        _wild_names.clear();
                           
1188
        for (butil::StringSplitter sp(vmodules, ','); sp; ++sp) {
gejun's avatar
gejun committed
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
            int verbose_level = std::numeric_limits<int>::max();
            size_t off = 0;
            for (; off < sp.length() && sp.field()[off] != '='; ++off) {}
            if (off + 1 < sp.length()) {
                verbose_level = strtol(sp.field() + off + 1, NULL, 10);
                
            }
            const char* name_begin = sp.field();
            const char* name_end = sp.field() + off - 1;
            for (; isspace(*name_begin) && name_begin < sp.field() + off;
                 ++name_begin) {}
            for (; isspace(*name_end) && name_end >= sp.field(); --name_end) {}
            
            if (name_begin > name_end) {  // only has spaces
                continue;
            }
            std::string name(name_begin, name_end - name_begin + 1);
            std::transform(name.begin(), name.end(), name.begin(), ::tolower);
            if (name.find_first_of("*?") == std::string::npos) {
                _exact_names[name] = verbose_level;
            } else {
                _wild_names.push_back(std::make_pair(name, verbose_level));
            }
        }
        // Reverse _wild_names so that latter wild cards override former ones.
        if (!_wild_names.empty()) {
            std::reverse(_wild_names.begin(), _wild_names.end());
        }
        return 0;
    }

    bool find_verbose_level(const std::string& module,
                            const std::string& full_module, int* v) const {
        if (!_exact_names.empty()) {
            std::map<std::string, int>::const_iterator
                it = _exact_names.find(module);
            if (it != _exact_names.end()) {
                *v = it->second;
                return true;
            }
            if (!full_module.empty()) {
                it = _exact_names.find(full_module);
                if (it != _exact_names.end()) {
                    *v = it->second;
                    return true;
                }
            }
        }

        for (size_t i = 0; i < _wild_names.size(); ++i) {
            if (wildcmp(_wild_names[i].first.c_str(), module.c_str())) {
                *v = _wild_names[i].second;
                return true;
            }
            if (!full_module.empty() &&
                wildcmp(_wild_names[i].first.c_str(), full_module.c_str())) {
                *v = _wild_names[i].second;
                return true;
            }
        }
        return false;
    }

    void print(std::ostream& os) const {
        os << "exact:";
        for (std::map<std::string, int>::const_iterator
                 it = _exact_names.begin(); it != _exact_names.end(); ++it) {
            os << ' ' << it->first << '=' << it->second;
        }
        os << ", wild:";
        for (size_t i = 0; i < _wild_names.size(); ++i) {
            os << ' ' << _wild_names[i].first << '=' << _wild_names[i].second;
        }
    }

private:
    std::map<std::string, int> _exact_names;
    std::vector<std::pair<std::string, int> > _wild_names;
};

// [ The idea ] 
// Each callsite creates a VLogSite and inserts the site into singly-linked
// vlog_site_list. To keep the critical area small, we use optimistic
// locking : Assign local site w/o locking, then insert the site into
// global list w/ locking, if local_module_list != global_vmodule_list or
1274
// local_default_v != FLAGS_v, repeat the assigment.
gejun's avatar
gejun committed
1275 1276 1277 1278
// An important property of vlog_site_list is that: It does not remove sites.
// When we need to iterate the list, we don't have to hold the lock. What we
// do is to get the head of the list inside lock and iterate the list w/o
// lock. If new sites is inserted during the iteration, it should see and
1279
// use the updated vmodule_list and FLAGS_v, nothing will be missed.
gejun's avatar
gejun committed
1280 1281 1282 1283 1284 1285 1286 1287 1288

static int vlog_site_list_add(VLogSite* site,
                              VModuleList** expected_module_list,
                              int* expected_default_v) {
    BAIDU_SCOPED_LOCK(vlog_site_list_mutex);
    if (vmodule_list != *expected_module_list) {
        *expected_module_list = vmodule_list;
        return -1;
    }
1289 1290
    if (*expected_default_v != FLAGS_v) {
        *expected_default_v = FLAGS_v;
gejun's avatar
gejun committed
1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
        return -1;
    }
    site->set_next(vlog_site_list);
    vlog_site_list = site;
    return 0;
}

bool add_vlog_site(const int** v, const char* filename, int line_no,
                   int required_v) {
    VLogSite* site = new (std::nothrow) VLogSite(filename, required_v, line_no);
    if (site == NULL) {
        return false;
    }
    VModuleList* module_list = vmodule_list;
1305
    int default_v = FLAGS_v;
gejun's avatar
gejun committed
1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332
    do {
        site->v() = default_v;
        if (module_list) {
            module_list->find_verbose_level(
                site->module(), site->full_module(), &site->v());
        }
    } while (vlog_site_list_add(site, &module_list, &default_v) != 0);
    *v = &site->v();
    return site->v() >= required_v;
}

void print_vlog_sites(VLogSitePrinter* printer) {
    VLogSite* head = NULL;
    {
        BAIDU_SCOPED_LOCK(vlog_site_list_mutex);
        head = vlog_site_list;
    }
    VLogSitePrinter::Site site;
    for (const VLogSite* p = head; p; p = p->next()) {
        site.current_verbose_level = p->v();
        site.required_verbose_level = p->required_v();
        site.line_no = p->line_no();
        site.full_module = p->full_module();
        printer->print(site);
    }
}

1333 1334
// [Thread-safe] Reset FLAGS_vmodule.
static int on_reset_vmodule(const char* vmodule) {
gejun's avatar
gejun committed
1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358
    // resetting must be serialized.
    BAIDU_SCOPED_LOCK(reset_vmodule_and_v_mutex);
    
    VModuleList* module_list = new (std::nothrow) VModuleList;
    if (NULL == module_list) {
        LOG(FATAL) << "Fail to new VModuleList";
        return -1;
    }
    if (module_list->init(vmodule) != 0) {
        delete module_list;
        LOG(FATAL) << "Fail to init VModuleList";
        return -1;
    }
    
    VModuleList* old_module_list = NULL;
    VLogSite* old_vlog_site_list = NULL;
    {
        {
            BAIDU_SCOPED_LOCK(vlog_site_list_mutex);
            old_module_list = vmodule_list;
            vmodule_list = module_list;
            old_vlog_site_list = vlog_site_list;
        }
        for (VLogSite* p = old_vlog_site_list; p; p = p->next()) {
1359
            p->v() = FLAGS_v;
gejun's avatar
gejun committed
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372
            module_list->find_verbose_level(
                p->module(), p->full_module(), &p->v());
        }
    }
    
    if (old_module_list) {
        //delay the deletion.
        if (NULL == deleting_vmodule_list) {
            deleting_vmodule_list =
                new std::deque<std::pair<VModuleList*, int64_t> >;
        }
        deleting_vmodule_list->push_back(
            std::make_pair(old_module_list,
1373
                           butil::gettimeofday_us() + DELAY_DELETION_SEC * 1000000L));
gejun's avatar
gejun committed
1374
        while (!deleting_vmodule_list->empty() &&
1375
               deleting_vmodule_list->front().second <= butil::gettimeofday_us()) {
gejun's avatar
gejun committed
1376 1377 1378 1379 1380 1381 1382 1383
            delete deleting_vmodule_list->front().first;
            deleting_vmodule_list->pop_front();
        }
    }
    return 0;
}

static bool validate_vmodule(const char*, const std::string& vmodule) {
1384
    return on_reset_vmodule(vmodule.c_str()) == 0;
gejun's avatar
gejun committed
1385 1386
}

1387
const bool ALLOW_UNUSED validate_vmodule_dummy = GFLAGS_NS::RegisterFlagValidator(
1388
    &FLAGS_vmodule, &validate_vmodule);
gejun's avatar
gejun committed
1389

1390
// [Thread-safe] Reset FLAGS_v.
gejun's avatar
gejun committed
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
static void on_reset_verbose(int default_v) {
    VModuleList* cur_module_list = NULL;
    VLogSite* cur_vlog_site_list = NULL;
    {
        // resetting must be serialized.
        BAIDU_SCOPED_LOCK(reset_vmodule_and_v_mutex);
        {
            BAIDU_SCOPED_LOCK(vlog_site_list_mutex);
            cur_module_list = vmodule_list;
            cur_vlog_site_list = vlog_site_list;
        }
        for (VLogSite* p = cur_vlog_site_list; p; p = p->next()) {
            p->v() = default_v;
            if (cur_module_list) {
                cur_module_list->find_verbose_level(
                    p->module(), p->full_module(), &p->v());
            }
        }
    }
}

static bool validate_v(const char*, int32_t v) {
    on_reset_verbose(v);
    return true;
}

1417
const bool ALLOW_UNUSED validate_v_dummy = GFLAGS_NS::RegisterFlagValidator(
1418
    &FLAGS_v, &validate_v);
gejun's avatar
gejun committed
1419 1420 1421 1422 1423 1424

static bool PassValidate(const char*, bool) {
    return true;
}

const bool ALLOW_UNUSED validate_crash_on_fatal_log =
1425
    GFLAGS_NS::RegisterFlagValidator(&FLAGS_crash_on_fatal_log, PassValidate);
gejun's avatar
gejun committed
1426 1427

const bool ALLOW_UNUSED validate_print_stack_on_check =
1428
    GFLAGS_NS::RegisterFlagValidator(&FLAGS_print_stack_on_check, PassValidate);
gejun's avatar
gejun committed
1429 1430 1431 1432 1433

static bool NonNegativeInteger(const char*, int32_t v) {
    return v >= 0;
}

1434
const bool ALLOW_UNUSED validate_min_log_level = GFLAGS_NS::RegisterFlagValidator(
1435
    &FLAGS_minloglevel, NonNegativeInteger);
gejun's avatar
gejun committed
1436 1437 1438 1439

}  // namespace logging

std::ostream& operator<<(std::ostream& out, const wchar_t* wstr) {
1440
    return out << butil::WideToUTF8(std::wstring(wstr));
gejun's avatar
gejun committed
1441
}
1442 1443

#endif  // BRPC_WITH_GLOG