Advertisement

How To Use Google Logging Library (glog)

阅读量:

(as of Fri Jan 25 2013)

Introduction

The Google glog library offers application-level logging functionality. It provides logging APIs based on C++-style streams and includes various helper macros. By sending messages through the LOG() mechanism, you can record a message, such as

复制代码

The Google glog module provides a set of macros designed to streamline common logging tasks. Users can log messages according to their severity levels; they can also adjust logging behavior from the command line; log operations based on conditional statements; halt execution if expected conditions aren't met; define custom verbose logging levels; and perform additional operations. The documentation details the functionality provided by Google's glog module. Please note that this document focuses on highlighting key functionalities while omitting less commonly used features of the library. If you're interested in exploring less commonly used features or specific configurations within Google's glog implementation, please refer to header files located under src/glog.

Severity Level

You can choose among different levels of severity, ranked from least severe to most severe: INFO, WARNING, ERROR, and FATAL. When a FATAL message is logged, it terminates the program after being recorded. It's important to note that any message sent with a specific severity level will also be included in all lower-level log files. For instance, logging a message at the FATAL level will result in it being recorded in the FATAL, ERROR, WARNING, and all subsequent lower-severity files.

The DFATAL severity records a Fatal error when in debug mode, specifically when there exists no NDEBUG macro. It prevents the program from being halted during production by automatically reducing the severity level to ERROR.

除非另有说明,默认情况下,glog会将日志记录到文件名"/tmp/<程序名称>/<主机名>/<用户名>.log.<严重程度等级>.<日期>-<时间>.<进程ID>"(例如: "/tmp/hello_world.example.com.hamaji.log.INFO.20080709-222411.10474")。默认情况下,glog会将严重程度等级为ERRORFATAL的日志记录到标准错误(stderr)以及存储在磁盘上的日志文件中。

Setting Flags

Several flags influence glog's output behavior. If the Google gflags library is installed on your machine, the configure script (see the INSTALL file in the package for detail of this script) will automatically detect and use it, allowing you to pass flags on the command line. For example, if you want to turn the flag --logtostderr on, you can start your application with the following command line:

复制代码

Unless the Google gflags library is not installed, you can configure flags by setting them within environment variables, by prefixing each flag name with "GLOG_", for example.

复制代码

The following flags are most commonly used:

logtostderr ( bool, default= false) Log messages to stderr rather than logfiles.
Note: you can set binary flags to true when you specify 1, true, or yes (case insensitive). Also, you can set binary flags to false when you specify 0, false, or no (again, case insensitive).

SEVERITY_THRESHOLD (integer type with a default value of 2)

该参数用于指定最小日志级别,默认值为0(对应'INFO'级别)。它必须是一个整数类型变量。
允许记录的信息量达到或超过该级别。
此外,信息、警告、错误和严重级别对应的数值分别为0、1、2和3。

log_dir ( string, default="") If provided, logfiles are stored within this directory rather than the default logging directory.

指定一个整数参数(默认值为0)以控制输出日志的详细程度。该参数用于输出所有小于或等于当前设置值的所有V日志记录,并可通过命令行参数--vmodule对其进行覆盖设置。详细信息请参考关于详细日志配置一节。

vmodule 参数(字符串类型,默认值为空)指定每个模块的详细级别设置。该参数必须包含一个逗号分隔的列表,在每个列表项中使用 "<模块名>=<日志级别>" 的形式来指定各个模块的日志级别。<模块名>是按通配符匹配文件名的方式(例如:"gfs*" 表示所有以 "gfs" 开头的文件夹中的模块),而 <日志级别> 会覆盖--v选项指定的值。有关详细信息,请参阅 关于详细日志配置的部分。

There are several additional flags declared in logging.cc. To search for the 'DEFINE_' macro, examine the original source code to identify all available macros.

You can also adjust program flags through global variables FLAGS_*. Upon updating FLAGS_*, most configurations begin to function promptly. Exceptions typically involve destination-related flags, such as setting FLAGS_log_dir prior to invoking google::InitGoogleLogging. Here's an illustrative example:

复制代码

Conditional / Occasional Logging

Sometimes, you may prefer to log a message only when certain conditions are met. It is possible for you to utilize these macros in order to achieve conditional logging.

复制代码

Only the "Got lots of cookies" notification is logged when the variable num_cookies reaches 10 or more. When a line of code runs repeatedly, it can be beneficial to monitor logs at specific intervals. This approach to logging proves especially helpful in Informational messages.

复制代码

The above line generates log message instances when it has been executed on the first, eleventh, twenty-first,... occasions. Note that a special google::COUNTER value is utilized to determine which instance of repetition occurs.

You can incorporate conditional statements and periodic logging using the following macro tool.

复制代码

Rather than sending a message each nth occurrence, it's possible to restrict transmission to only the first n instances.

复制代码

Generates logs at each execution up to 20 times. The google::COUNTER identifier is used for indicating which repetition occurs.

Debug Mode Support

Specifically designed for 'debug mode', these logging macros function solely within this context and are stripped out of the codebase entirely during non-debug compilation. These macros should be employed to prevent slowdowns in your production application due to (unnecessary) log records.

复制代码

CHECK Macros

Adopting this approach ensures that potential issues are identified promptly. The CHECK macro enables abrupt termination of execution when a condition isn't met, akin to how the assert macro functions within standard C libraries.

If a condition fails to meet, the application will terminate abnormally. Unlike assert, this check isn't governed by the NDEBUG macro; hence, it will execute irrespective of the compilation mode. Therefore, in the subsequent example provided, "fp->Write(x)" will inevitably be executed.

复制代码

There exist multiple utility macros designed for equality and inequality evaluations: CHECK_EQ, CHECK_NE, CHECK_LE, CHECK_LT, CHECK_GE, and CHECK_GT. These macros assess two values and issue a severe error message incorporating both values if the evaluation does not yield the expected outcome. The required values must support an insertion operator into an output stream.

You may append to the error message like so:

复制代码

We are extremely cautious in ensuring that each argument is evaluated precisely once, making certain that every argument is examined in detail. Additionally, we guarantee that anything which can legally be passed as a function argument complies with our policies. Notably, the arguments might include temporary expressions or placeholders designed to be resolved within the context of the current operation. For instance:

复制代码

The compiler throws an error when one of the arguments is a pointer and the other is NULL. To circumvent this issue, simply cast NULL to (static) cast type of desired pointer.

复制代码

Better yet, use the CHECK_NOTNULL macro:

复制代码

Because this macro returns the provided pointer location, it is especially valuable when used within the constructor initializer list.

复制代码

Note that you are prohibited from using this macro as a C++ stream due to its inherent limitations. It is important to utilize the CHECK_EQ function, as outlined earlier, in order to log a custom message prior to exiting the application.

When comparing C-style strings (of type char *) using a handy set of macros, these can perform both case-sensitive and case-insensitive comparisons. The version-specific macros handle comparisons in a case-insensitive manner. It is safe to pass NULL pointers when using this macro. These macros consider NULL and any non-null string not equal, but two NULL pointers will be considered equal by these macros.

Note that the two arguments may be temporary strings, each of which gets decomposed upon completion of the current full expression. For example, consider this call: CHECK_STREQ(Foo().c_str(), Bar().c_str()). Here, each function, such as Foo() and Bar(), returns a C++ std::string object.

The CHECK_DOUBLE_EQ macro verifies the equality between two floating-point values, allowing for a minimal tolerance level. CHECK_NEAR requires a third floating-point argument to define the acceptable error margin.

Verbose Logging

When pursuing challenging bugs, detailed error messages prove highly beneficial. However, in typical development scenarios, one might wish to disregard overly verbose logs. For such extensive logging purposes, glog offers the VLOG macro, enabling users to establish custom numeric log levels. The --v command-line parameter determines which verbose logs will be captured:

复制代码

With the VLOG command, reducing the level of verbosity results in messages being logged more frequently. For instance, when using --v=1, VLOG(1) will output messages, whereas VLOG(2) will not. This is contrary to the severity levels where INFO is assigned 0 and ERROR is 2. Setting --minloglevel to 1 ensures that WARNING and higher levels are logged. Although both the VLOG macro and --v flag allow specifying any integer values, their common usage typically involves small positive integers. For example, invoking VLOG(0) would require setting --v=-1 or lower to suppress logging. This is generally less useful since default configurations usually avoid verbose logging. The VLOG macros consistently log at the INFO level whenever they do produce output.

详细日志可以通过命令行分别控制到每个模块:

复制代码

will:

  • a. Log VLOG(2)并输出来自mapreduce目录下{h,cc}文件中的信息。
    • b. Log VLOG(1)并输出来自file目录下{h,cc}文件中的信息。
    • c. Log VLOG(3)并输出以'gfs'开头的文件夹中的信息。
    • d. Log VLOG(0)并输出其他位置的信息。

This wildcard functionality, as depicted in (c), incorporates both the * and ? operators. The * operator matches zero or more characters, while the ? operator matches a single character. Additionally, you should review the section on command-line flags at http://google-glog.googlecode.com/svn/trunk/doc/glog.html#flags.

There's also a $VLOG_IS_ON(n)$ criterion for the verbose level. This macro evaluates to true when the value of $--v$ is equal to or greater than $n$. It can be defined as follows:

复制代码

Differentiation levels for conditions, referred to as VLOG_IF, VLOG_EVERY_N, and VLOG_IF_EVERY_N, operate similarly to LOG_IF, LOG_EVERY_N, and LOF_IF_EVERY, but they utilize a granularity-based approach instead of relying on severity levels.

复制代码

Failure Signal Handler

The library offers a user-friendly signal handler that upon crash will dump useful information for specific signals like SIGSEGV. This handler can be activated via google::InstallFailureSignalHandler(). The subsequent illustration demonstrates outputs from the signal handler.

复制代码

By default, the signal handler outputs failure dumps to standard error. The destination for failure dumps can be customized using InstallFailureWriter().

Miscellaneous Notes

Performance of Messages

glog provides these conditionals (CHECK, LOG_IF, VLOG, etc.), which are well-crafted and ensure that the right-hand-side expressions aren't executed when conditions fail. It's important to note that performing this check won't compromise your application's performance.

复制代码

User-defined Failure Function

Messages at the FATAL severity level or an unsatisfied CHECK condition will result in program termination. By using this function, you can modify the termination behavior. The terminating process is governed by the installation of InstallFailureFunction.

复制代码

By default, glog aims to output stack traces and results in a program exit code of 1. Stack traces are generated exclusively when the application is executed on an architecture that supports stack tracing (as of September 2008, this feature applies to x86 and x86_64 systems).

Raw Logging

The header file <glog/raw_logging.h> is designed to provide thread-safe logging without requiring allocation of memory or acquisition of locks. Therefore, the macros defined in this header file are available to support low-level memory allocation and synchronization operations. Please refer to src/glog/raw_logging.h.in for further details.

Google Style perror()

The functions PLOG(), PLOG_IF(), and PCHECK() exhibit identical behavior to their LOG* and CHECK equivalents, in addition to appending a description of the current state of errno to each of their output messages. For instance, these functions are designed in such a way as well as providing detailed error information, they also ensure robustness in handling system states.

复制代码

This check fails with the following error message.

复制代码

Syslog

The SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macro definitions are accessible in this context. These can be utilized not only for regular logging operations but also for additional syslog destinations. It’s important to note that configuring syslog for remote usage can have significant performance implications. Users should ensure a thorough understanding of the potential consequences of leveraging syslog before employing these macro definitions. Generally, it’s advisable to employ these macros sparingly unless absolutely necessary.

Strip Logging Messages

Log messages incorporating strings may result in an increase in binary size and pose a privacy concern. It is therefore advisable to configure glog to strip all strings with severity below a specified threshold utilizing the GOOGLE_STRIP_LOG macro.

If your application has code like this:

复制代码

The compiler system is programmed to eliminate log messages with severity levels below a given integer threshold. Because VLOG records data at a certain level (specifically INFO, which corresponds to a numeric value of 0), enabling GOOGLE_STRIP_LOG to be set to 1 or higher will eliminate all logs tied to VLOG instances and INFO statement records.

Notes for Windows users

Google's glog defines a severity level named ERROR, which is also declared in the windows.h header file. By enabling the GLOG_NO_ABBREVIATED_SEVERITIES macro before including the logging.h header, you can prevent the definition of INFO, WARNING, ERROR, and FATAL log levels. Despite this configuration, you retain access to iostream-like logging capabilities.

复制代码

However, you are prohibited from using INFO, WARNING, ERROR, and FATAL in glog/logging.h.

复制代码

Unless you require the ERROR macro defined in the Windows.h header file, there are several alternative workaround solutions that can be employed, though these solutions may not always function correctly.

  • Define a macro named WIN32_LEAN_AND_MEAN, optionally alongside NOGDI, prior to incorporating the Windows.h header file.
  • Undefine the macro ERROR post incorporating the Windows.h header file.

Refer to this issue for further details.

全部评论 (0)

还没有任何评论哟~