如何使用Google日志库glog

本文来自于glog库的doc目录的glog.html

0.Extract

本文中比较重要的几段内容提取如下:

  • You can log messages by severity level, control logging behavior from the command line, log based on conditionals, abort the program when expected conditions are not met, introduce your own verbose logging levels, and more.(glog的特性)
  • If you want to find less common features, please check header files under src/glog(The best way is read source) directory.(最好的方法是看源码)
  • There are some other flags defined in logging.cc. Please grep the source code for "DEFINE_" to see a complete list of all flags.(想了解所有标志FLAGS_*,可以使用grep命令筛选logging.cc文件的'DEFINE_'关键字)

修改glog的标志的方法有以下三种:

  1. 若支持gflags,可使用命令行参数传入,也可以通过--flagfile指定参数文件;
  2. 若不支持gflags,可通过设置系统环境变量来实现,环境变量均以'GLOG_'开头(If the Google gflags library isn't installed, you set flags via environment variables, prefixing the flag name with "GLOG_");
  3. 不管是否支持gflags,你都可以在你的程序源码中直接修改对应的标志,所有的标志均以'FLAGS_*'开头(You can also modify flag values in your program by modifying global variables FLAGS_*)。

1.Introduction

Google glog is a library that implements application-level logging. This library provides logging APIs based on C++-style streams and various helper macros. You can log a message by simply streaming things to LOG(< a particular ++severity level++(Chapter 2) >), e.g.

#include <glog/logging.h>

int main(int argc, char* argv[])
{
    // Initialize Google's logging library.
    google::InitGoogleLogging(argv[0]);

    // ...
    LOG(INFO) << "Found " << num_cookies << " cookies";
}

Google glog defines a series of macros that simplify many common logging tasks. You can log messages by severity level, control logging behavior from the command line, log based on conditionals, abort the program when expected conditions are not met, introduce your own verbose logging levels, and more. This document describes the functionality supported by glog. Please note that this document doesn't describe all features in this library, but the most useful ones. If you want to find less common features, please check header files under src/glog(The best way is read source) directory.

2.Severity Level

You can specify one of the following severity levels (in increasing order of severity): INFO, WARNING, ERROR, and FATAL. Logging a FATAL message terminates the program (after the message is logged). Note that messages of a given severity are logged not only in the logfile for that severity, but also in all logfiles of lower severity. E.g., a message of severity FATAL will be logged to the logfiles of severity FATAL, ERROR, WARNING, and INFO.

The DFATAL severity logs a FATAL error in debug mode (i.e., there is no NDEBUG macro defined), but avoids halting the program in production by automatically reducing the severity to ERROR.

Unless otherwise specified, glog writes to the filename "/tmp/< program name >.< hostname >.< user name >.log.< severity level >.< date >.< time >.< pid >" (e.g., "/tmp/hello_world.example.com.hamaji.log.INFO.20080709-222411.10474"). By default, glog copies the log messages of severity level ERROR or FATAL to standard error (stderr) in addition to log files.

3.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:

./your_application --logtostderr=1

If the Google gflags library isn't installed, you set flags via environment variables, prefixing the flag name with "GLOG_", e.g.

GLOG_logtostderr=1 ./your_application

The following flags are most commonly used:

  • logtostderr (bool, default=false):Log messages to stderr instead of logfiles.

Note: you can set binary flags to true by specifying 1, true, or yes (case insensitive). Also, you can set binary flags to false by specifying 0, false, or no (again, case insensitive).

  • stderrthreshold (int, default=2, which is ERROR):Copy log messages at or above this level to stderr in addition to logfiles. The numbers of severity levels INFO, WARNING, ERROR, and FATAL are 0, 1, 2, and 3, respectively.

  • minloglevel (int, default=0, which is INFO):Log messages at or above this level. Again, the numbers of severity levels INFO, WARNING, ERROR, and FATAL are 0, 1, 2, and 3, respectively.

  • log_dir (string, default=""):If specified, logfiles are written into this directory instead of the default logging directory.

  • v (int, default=0):Show all VLOG(m) messages for m less or equal the value of this flag. Overridable by --vmodule. See the section about verbose logging(Chapter 7) for more detail.

  • vmodule (string, default=""):Per-module verbose level. The argument has to contain a comma-separated list of <module name>=<log level>. <module name> is a glob pattern (e.g., gfs* for all modules whose name starts with "gfs"), matched against the filename base (that is, name ignoring .cc/.h./-inl.h). <log level> overrides any value given by --v. See also the section about verbose logging(Chapter 7).

There are some other flags defined in logging.cc. Please grep the source code for "DEFINE_" to see a complete list of all flags.

You can also modify flag values in your program by modifying global variables FLAGS_* . Most settings start working immediately after you update FLAGS_* . The exceptions are the flags related to destination files. For example, you might want to set FLAGS_log_dir before calling google::InitGoogleLogging . Here is an example:

   LOG(INFO) << "file";
   // Most flags work immediately after updating values.
   FLAGS_logtostderr = 1;
   LOG(INFO) << "stderr";
   FLAGS_logtostderr = 0;
   // This won't change the log destination. If you want to set this
   // value, you should do this before google::InitGoogleLogging .
   FLAGS_log_dir = "/some/log/directory";
   LOG(INFO) << "the same file";

4.Conditional/Occasional Logging

Sometimes, you may only want to log a message under certain conditions. You can use the following macros to perform conditional logging:

LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";

The "Got lots of cookies" message is logged only when the variable num_cookies exceeds 10. If a line of code is executed many times, it may be useful to only log a message at certain intervals. This kind of logging is most useful for informational messages.

LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";

The above line outputs a log messages on the 1st, 11th, 21st, ... times it is executed. Note that the special google::COUNTER value is used to identify which repetition is happening.

You can combine conditional and occasional logging with the following macro.

LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
                                           << "th big cookie";

Instead of outputting a message every nth time, you can also limit the output to the first n occurrences:

LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";

Outputs log messages for the first 20 times it is executed. Again, the google::COUNTER identifier indicates which repetition is happening.

5.Debug Mode Support

Special "debug mode" logging macros only have an effect in debug mode and are compiled away to nothing for non-debug mode compiles. Use these macros to avoid slowing down your production application due to excessive logging.

   DLOG(INFO) << "Found cookies";
   DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
   DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";

6.CHECK Macros

It is a good practice to check expected conditions in your program frequently to detect errors as early as possible. The CHECK macro provides the ability to abort the application when a condition is not met, similar to the assert macro defined in the standard C library.

CHECK aborts the application if a condition is not true. Unlike assert, it is *not* controlled by NDEBUG, so the check will be executed regardless of compilation mode. Therefore, fp->Write(x) in the following example is always executed:

CHECK(fp->Write(x) == 4) << "Write failed!";

There are various helper macros for equality/inequality checks - CHECK_EQ, CHECK_NE, CHECK_LE, CHECK_LT, CHECK_GE, and CHECK_GT. They compare two values, and log a FATAL message including the two values when the result is not as expected. The values must have operator<<(ostream, ...) defined.

You may append to the error message like so:

CHECK_NE(1, 2) << ": The world must be ending!";

We are very careful to ensure that each argument is evaluated exactly once, and that anything which is legal to pass as a function argument is legal here. In particular, the arguments may be temporary expressions which will end up being destroyed at the end of the apparent statement, for example:

CHECK_EQ(string("abc")[1], 'b');

The compiler reports an error if one of the arguments is a pointer and the other is NULL. To work around this, simply static_cast NULL to the type of the desired pointer.

CHECK_EQ(some_ptr, static_cast<SomeType*>(NULL));

Better yet, use the CHECK_NOTNULL macro:

CHECK_NOTNULL(some_ptr);
some_ptr->DoSomething();

Since this macro returns the given pointer, this is very useful in constructor initializer lists.

   struct S {
     S(Something* ptr) : ptr_(CHECK_NOTNULL(ptr)) {}
     Something* ptr_;
   };

Note that you cannot use this macro as a C++ stream due to this feature. Please use CHECK_EQ described above to log a custom message before aborting the application.

If you are comparing C strings (char *), a handy set of macros performs case sensitive as well as case insensitive comparisons - CHECK_STREQ, CHECK_STRNE, CHECK_STRCASEEQ, and CHECK_STRCASENE. The CASE versions are case-insensitive. You can safely pass NULL pointers for this macro. They treat NULL and any non-NULL string as not equal. Two NULLs are equal.

Note that both arguments may be temporary strings which are destructed at the end of the current "full expression" (e.g., CHECK_STREQ(Foo().c_str(), Bar().c_str()) where Foo and Bar return C++'s std::string).

The CHECK_DOUBLE_EQ macro checks the equality of two floating point values, accepting a small error margin. CHECK_NEAR accepts a third floating point argument, which specifies the acceptable error margin.

7.Verbose Logging

When you are chasing difficult bugs, thorough log messages are very useful. However, you may want to ignore too verbose messages in usual development. For such verbose logging, glog provides the VLOG macro, which allows you to define your own numeric logging levels. The --v command line option controls which verbose messages are logged:

   VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
   VLOG(2) << "I'm printed when you run the program with --v=2 or higher";

With VLOG, the lower the verbose level, the more likely messages are to be logged. For example, if --v==1, VLOG(1) will log, but VLOG(2) will not log. This is opposite of the severity level, where INFO is 0, and ERROR is 2. --minloglevel of 1 will log WARNING and above. Though you can specify any integers for both VLOG macro and --v flag, the common values for them are small positive integers. For example, if you write VLOG(0), you should specify --v=-1 or lower to silence it. This is less useful since we may not want verbose logs by default in most cases. The VLOG macros always log at the INFO log level (when they log at all).

Verbose logging can be controlled from the command line on a per-module basis:

   --vmodule=mapreduce=2,file=1,gfs*=3 --v=0

will:

  • a. Print VLOG(2) and lower messages from mapreduce.{h,cc}
  • b. Print VLOG(1) and lower messages from file.{h,cc}
  • c. Print VLOG(3) and lower messages from files prefixed with "gfs"
  • d. Print VLOG(0) and lower messages from elsewhere

The wildcarding functionality shown by (c) supports both '*' (matches 0 or more characters) and '?' (matches any single character) wildcards. Please also check the section about command line flags(Chapter 3).

There's also VLOG_IS_ON(n) "verbose level" condition macro. This macro returns true when the --v is equal or greater than n. To be used as

   if (VLOG_IS_ON(2)) {
     // do some logging preparation and logging
     // that can't be accomplished with just VLOG(2) << ...;
   }

Verbose level condition macros VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N behave analogous to LOG_IF, LOG_EVERY_N, LOF_IF_EVERY, but accept a numeric verbosity level as opposed to a severity level.

   VLOG_IF(1, (size > 1024))
      << "I'm printed when size is more than 1024 and when you run the "
         "program with --v=1 or more";
   VLOG_EVERY_N(1, 10)
      << "I'm printed every 10th occurrence, and when you run the program "
         "with --v=1 or more. Present occurence is " << google::COUNTER;
   VLOG_IF_EVERY_N(1, (size > 1024), 10)
      << "I'm printed on every 10th occurence of case when size is more "
         " than 1024, when you run the program with --v=1 or more. ";
         "Present occurence is " << google::COUNTER;

8.Failure Signal Handler

The library provides a convenient signal handler that will dump useful information when the program crashes on certain signals such as SIGSEGV. The signal handler can be installed by google::InstallFailureSignalHandler(). The following is an example of output from the signal handler.

*** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date ***
*** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: ***
PC: @           0x412eb1 TestWaitingLogSink::send()
    @     0x7f892fb417d0 (unknown)
    @           0x412eb1 TestWaitingLogSink::send()
    @     0x7f89304f7f06 google::LogMessage::SendToLog()
    @     0x7f89304f35af google::LogMessage::Flush()
    @     0x7f89304f3739 google::LogMessage::~LogMessage()
    @           0x408cf4 TestLogSinkWaitTillSent()
    @           0x4115de main
    @     0x7f892f7ef1c4 (unknown)
    @           0x4046f9 (unknown)

By default, the signal handler writes the failure dump to the standard error. You can customize the destination by InstallFailureWriter().

9.Miscellaneous Notes

9.1 Performance of Messages

The conditional logging macros provided by glog (e.g., CHECK, LOG_IF, VLOG, ...) are carefully implemented and don't execute the right hand side expressions when the conditions are false. So, the following check may not sacrifice the performance of your application.

   CHECK(obj.ok) << obj.CreatePrettyFormattedStringButVerySlow();

9.2 User-defined Failure Function

FATAL severity level messages or unsatisfied CHECK condition terminate your program. You can change the behavior of the termination by InstallFailureFunction.

   void YourFailureFunction() {
     // Reports something...
     exit(1);
   }

   int main(int argc, char* argv[]) {
     google::InstallFailureFunction(&YourFailureFunction);
   }

By default, glog tries to dump stacktrace and makes the program exit with status 1. The stacktrace is produced only when you run the program on an architecture for which glog supports stack tracing (as of September 2008, glog supports stack tracing for x86 and x86_64).

9.3 Raw Logging

The header file glog/raw_logging.h can be used for thread-safe logging, which does not allocate any memory or acquire any locks. Therefore, the macros defined in this header file can be used by low-level memory allocation and synchronization code. Please check src/glog/raw_logging.h.in for detail.

9.4 Google Style perror()

PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and CHECK equivalents with the addition that they append a description of the current state of errno to their output lines. E.g.

   PCHECK(write(1, NULL, 2) >= 0) << "Write NULL failed";

This check fails with the following error message.

   F0825 185142 test.cc:22] Check failed: write(1, NULL, 2) >= 0 Write NULL failed: Bad address [14]

9.5 Syslog

SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available. These log to syslog in addition to the normal logs. Be aware that logging to syslog can drastically impact performance, especially if syslog is configured for remote logging! Make sure you understand the implications of outputting to syslog before you use these macros. In general, it's wise to use these macros sparingly.

9.6 Strip Logging Messages

Strings used in log messages can increase the size of your binary and present a privacy concern. You can therefore instruct glog to remove all strings which fall below a certain severity level by using the GOOGLE_STRIP_LOG macro:

If your application has code like this:

   #define GOOGLE_STRIP_LOG 1    // this must go before the #include!
   #include <glog/logging.h>

The compiler will remove the log messages whose severities are less than the specified integer value. Since VLOG logs at the severity level INFO (numeric value 0), setting GOOGLE_STRIP_LOG to 1 or greater removes all log messages associated with VLOGs as well as INFO log statements.

9.7 Notes for Windows users

Google glog defines a severity level ERROR, which is also defined in windows.h . You can make glog not define INFO, WARNING, ERROR, and FATAL by defining GLOG_NO_ABBREVIATED_SEVERITIES before including glog/logging.h . Even with this macro, you can still use the iostream like logging facilities:

  #define GLOG_NO_ABBREVIATED_SEVERITIES
  #include <windows.h>
  #include <glog/logging.h>

  // ...

  LOG(ERROR) << "This should work";
  LOG_IF(ERROR, x > y) << "This should be also OK";

However, you cannot use INFO, WARNING, ERROR, and FATAL anymore for functions defined in glog/logging.h .

  #define GLOG_NO_ABBREVIATED_SEVERITIES
  #include <windows.h>
  #include <glog/logging.h>

  // ...

  // This won't work.
  // google::FlushLogFiles(google::ERROR);

  // Use this instead.
  google::FlushLogFiles(google::GLOG_ERROR);

If you don't need ERROR defined by windows.h, there are a couple of more workarounds which sometimes don't work:

#define WIN32_LEAN_AND_MEAN or NOGDI before you #include windows.h .
#undef ERROR after you #include windows.h .

See this issue for more detail.

想了解更多有关嵌入式Linux驱动、应用、常用开源库、框架、模式、重构等相关相关的主题内容,请长安下面图片,关注我的公众号(只有技术干货分享,不拉稀摆带!)。

image

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,951评论 6 497
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,606评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,601评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,478评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,565评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,587评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,590评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,337评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,785评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,096评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,273评论 1 344
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,935评论 5 339
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,578评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,199评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,440评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,163评论 2 366
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,133评论 2 352

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,319评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,459评论 0 23
  • 字符串不能被赋为"空" 看来nil并不代表空的字符串package main 发现nil并不能进行比较操作
    wu_sphinx阅读 11,765评论 0 1
  • 不论是现实生活,还是小说中,我们都常常运用到言语的力量。过去人们会觉得,你就是个只会写字的文人,能有什么用。可是,...
    我是狐狸一只阅读 404评论 0 2
  • 冥冥之中,一切皆是命运,人算不如天算; 思想之中,迷信非是科学,主观不如客观; 头脑之中,创意总是闪现,心动不如行...
    水上萍阅读 264评论 0 4