glog(Google Logging Library)

对MPI支持一样好用  记得要传递FLAGS_v

http://code.google.com/p/google-glog/downloads/detail?name=glog-0.3.3.tar.gz&can=2&q=


How To Use Google Logging Library (glog)

(as ofFri Jan 25 2013)

Introduction

Google glog is a library that implements application-levellogging. This library provides logging APIs based on C++-stylestreams and various helper macros.You can log a message by simply streaming things to LOG(<aparticularseverity level>), 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 loggingtasks. You can log messages by severity level, control loggingbehavior from the command line, log based on conditionals, abort theprogram when expected conditions are not met, introduce your ownverbose logging levels, and more. This document describes thefunctionality supported by glog. Please note that this documentdoesn't describe all features in this library, but the most usefulones. If you want to find less common features, please checkheader files under src/glog directory.

Severity Level

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

The DFATAL severity logs a FATAL error indebug mode (i.e., there is noNDEBUG macro defined), butavoids halting the program in production by automatically reducing theseverity toERROR.

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 levelERROR or FATAL to standard error (stderr)in addition to log files.

Setting Flags

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

   ./your_application --logtostderr=1
If the Google gflags library isn't installed, you set flags viaenvironment 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 (caseinsensitive).Also, you can set binary flags to false by specifying 0, false, or no (again, caseinsensitive).
stderrthreshold ( int, default=2, whichis ERROR)
Copy log messages at or above this level to stderr inaddition to logfiles. The numbers of severity levels INFO, WARNING, ERROR, and FATAL are 0, 1, 2, and 3, respectively.
minloglevel ( int, default=0, whichis INFO)
Log messages at or above this level. Again, the numbers ofseverity 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 insteadof the default logging directory.
v ( int, default=0)
Show all VLOG(m) messages for m less orequal the value of this flag. Overridable by --vmodule.See the section about verbose logging for moredetail.
vmodule ( string, default="")
Per-module verbose level. The argument has to contain acomma-separated list of <module name>=<log level>.<module name>is a glob pattern (e.g., gfs* for all modules whose namestarts 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.

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

You can also modify flag values in your program by modifying globalvariables FLAGS_* . Most settings start workingimmediately after you update FLAGS_* . The exceptions arethe flags related to destination files. For example, you might want tosetFLAGS_log_dir beforecallinggoogle::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";

Conditional / Occasional Logging

Sometimes, you may only want to log a message under certainconditions. You can use the following macros to perform conditionallogging:

   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 loga message at certain intervals. This kind of logging is most usefulfor 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 specialgoogle::COUNTER value is used to identify which repetition ishappening.

You can combine conditional and occasional logging with thefollowing 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 limitthe 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 ishappening.

Debug Mode Support

Special "debug mode" logging macros only have an effect in debugmode and are compiled away to nothing for non-debug modecompiles. Use these macros to avoid slowing down your productionapplication 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";

CHECK Macros

It is a good practice to check expected conditions in your programfrequently to detect errors as early as possible. TheCHECK macro provides the ability to abort the applicationwhen a condition is not met, similar to theassert macrodefined in the standard C library.

CHECK aborts the application if a condition is nottrue. Unlike assert, it is *not* controlled byNDEBUG, so the check will be executed regardless ofcompilation mode. Therefore,fp->Write(x) in thefollowing example is always executed:

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

There are various helper macros forequality/inequality checks - CHECK_EQ,CHECK_NE,CHECK_LE,CHECK_LT,CHECK_GE, and CHECK_GT.They compare two values, and log aFATAL message including the two values when the result isnot as expected. The values must haveoperator<<(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 exactlyonce, and that anything which is legal to pass as a function argument islegal here. In particular, the arguments may be temporary expressionswhich 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 apointer and the other is NULL. To work around this, simply static_castNULL 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 inconstructor 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 thisfeature. Please useCHECK_EQ described above to log acustom message before aborting the application.

If you are comparing C strings (char *), a handy set of macrosperforms case sensitive as well as case insensitive comparisons -CHECK_STREQ,CHECK_STRNE,CHECK_STRCASEEQ, andCHECK_STRCASENE. TheCASE versions are case-insensitive. You can safely passNULLpointers for this macro. They treatNULL and anynon-NULL string as not equal. TwoNULLs areequal.

Note that both arguments may be temporary strings which aredestructed at the end of the current "full expression"(e.g.,CHECK_STREQ(Foo().c_str(), Bar().c_str()) whereFoo andBar return C++'sstd::string).

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

Verbose Logging

When you are chasing difficult bugs, thorough log messages are veryuseful. However, you may want to ignore too verbose messages in usualdevelopment. For such verbose logging, glog provides theVLOG macro, which allows you to define your own numericlogging levels. The --v command line option controlswhich 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 morelikely messages are to be logged. For example, if--v==1,VLOG(1) will log, butVLOG(2) will not log. This is opposite of the severitylevel, whereINFO is 0, and ERROR is 2.--minloglevel of 1 will logWARNING andabove. Though you can specify any integers for bothVLOGmacro and --v flag, the common values for them are smallpositive integers. For example, if you writeVLOG(0),you should specify--v=-1 or lower to silence it. Thisis less useful since we may not want verbose logs by default in mostcases. TheVLOG macros always log at theINFO log level (when they log at all).

Verbose logging can be controlled from the command line on aper-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 aboutcommand line flags.

There's also VLOG_IS_ON(n) "verbose level" conditionmacro. This macro returns true when the--v is equal orgreater thann. 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 andVLOG_IF_EVERY_N behaveanalogous toLOG_IF, LOG_EVERY_N,LOF_IF_EVERY, but accept a numeric verbosity level asopposed 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;

Failure Signal Handler

The library provides a convenient signal handler that will dump usefulinformation when the program crashes on certain signals such as SIGSEGV.The signal handler can be installed bygoogle::InstallFailureSignalHandler(). The following is an example of outputfrom 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 standarderror. You can customize the destination by InstallFailureWriter().

Miscellaneous Notes

Performance of Messages

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

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

User-defined Failure Function

FATAL severity level messages or unsatisfiedCHECK condition terminate your program. You can changethe behavior of the termination byInstallFailureFunction.

   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 programexit with status 1. The stacktrace is produced only when you run theprogram on an architecture for which glog supports stack tracing (asof September 2008, glog supports stack tracing for x86 and x86_64).

Raw Logging

The header file <glog/raw_logging.h> can beused for thread-safe logging, which does not allocate any memory oracquire any locks. Therefore, the macros defined in thisheader file can be used by low-level memory allocation andsynchronization code.Please check src/glog/raw_logging.h.in for detail.

Google Style perror()

PLOG() and PLOG_IF() andPCHECK() behave exactly like theirLOG* andCHECK equivalents with the addition that they append adescription 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]

Syslog

SYSLOG, SYSLOG_IF, andSYSLOG_EVERY_N macros are available.These log to syslog in addition to the normal logs. Be aware thatlogging to syslog can drastically impact performance, especially ifsyslog is configured for remote logging! Make sure you understand theimplications of outputting to syslog before you use these macros. Ingeneral, it's wise to use these macros sparingly.

Strip Logging Messages

Strings used in log messages can increase the size of your binaryand present a privacy concern. You can therefore instruct glog toremove all strings which fall below a certain severity level by usingthe 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 lessthan the specified integer value. SinceVLOG logs at the severity levelINFO(numeric value0),setting GOOGLE_STRIP_LOG to 1 or greater removesall log messages associated withVLOGs as well asINFO log statements.

Notes for Windows users

Google glog defines a severity level ERROR, which isalso defined inwindows.h . You can make glog not defineINFO,WARNING,ERROR,and FATAL by definingGLOG_NO_ABBREVIATED_SEVERITIES beforeincludingglog/logging.h . Even with this macro, you canstill 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 cannotuse INFO, WARNING, ERROR,andFATAL anymore for functions definedinglog/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 definedby windows.h, there are a couple of more workaroundswhich sometimes don't work:

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

See this issue for more detail.


Shinichiro Hamaji
Gregor Hohpe
Fri Jan 25 2013

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: <glog/logging.h>是Google的开源C ++日志记录库,用于在C ++程序中实现灵活且高效的日志记录功能。它提供了一个易于使用的接口,可以将各种日志消息记录到控制台、文件或其他输出目标中。 <glog/logging.h>库主要由以下几个组件组成: 1. Logger(日志记录器):提供了不同级别的日志记录功能,例如INFO、WARNING、ERROR和FATAL。可以通过使用Logger对象的接口来记录不同级别的日志消息。 2. LogSink(日志汇):定义了将日志消息写入目标的接口。可以通过创建和注册不同类型的LogSink对象来将日志消息输出到不同的目标,例如控制台、文件或远程服务器。 3. LogMessage(日志消息):包含了要记录的日志消息的详细信息,例如发生日志记录的文件名、行号等。可以通过LogMessage提供的接口来记录日志消息。 4. Flag(标志):用于启用或禁用特定的日志记录功能。可以通过设置不同的Flag来控制日志记录的级别、输出目标等。 通过在C ++代码中包含<glog/logging.h>头文件,并使用其中的接口,开发人员可以方便地实现日志记录功能。此外,该库还提供了一些额外的功能,例如支持日志消息的格式化、日志消息的过滤和日志的分级统计等。 总而言之,<glog/logging.h>是一个强大且易于使用的C ++日志记录库,提供了丰富的功能和灵活的配置选项,可以帮助开发人员更好地追踪和调试程序中的问题。 ### 回答2: <glog/logging.h> 是一个开源的 C++ 日志库。它提供了一套灵活、功能丰富且易于使用的日志记录工具,用于帮助开发人员在程序中方便地记录和追踪各种信息。 使用<glog/logging.h>,开发人员可以通过简单的API调用来记录各种消息,包括调试信息、警告、错误和临时性信息。该库支持不同级别的日志,包括 INFO、WARNING、ERROR、FATAL,开发人员可以根据不同的需求来选择适当的日志级别。 此外,<glog/logging.h> 还提供了一些其他功能,如日志文件的自动分割、多线程支持、日志信息的颜色标记、日志信息到标准输出的同时写入到磁盘等。这些功能使得开发人员可以更好地分析和排查程序中的问题。 另外,<glog/logging.h> 是跨平台的,可以在多个操作系统上运行,如Linux、Windows和MacOS。它被广泛应用于各种规模的软件项目中,包括大型分布式系统、Web 服务器、数据库等。 总而言之,<glog/logging.h> 是一个功能强大且易于使用的C++日志记录库,可以帮助开发人员在程序中方便地记录各种信息,并提供了许多有用的功能来方便开发人员分析和排查问题。无论是开发大型软件还是小型项目,都可以考虑使用这个库来提高开发效率和日志记录的质量。 ### 回答3: <glog/logging.h> 是一个开源的 C++ 日志库,由 Google 开发并维护。它提供了一种简单且高效的方式来在代码中记录日志信息。 使用 <glog/logging.h>,开发者可以通过调用相应的函数将各种级别的日志信息输出到控制台或文件中。这些日志级别包括 DEBUG、INFO、WARNING、ERROR 和 FATAL,可以根据需要选择不同的级别来记录日志,以方便在开发和调试过程中进行有效的日志跟踪和错误定位。 <glog/logging.h> 的优势在于其高性能和灵活的配置选项。它通过多线程和缓冲技术,能够在高并发的情况下保持较低的性能开销。此外,开发者还可以通过配置文件或命令行参数来调整日志记录的行为,包括输出格式、日志文件路径、日志级别等。这使得 <glog/logging.h> 能够灵活地适应各种不同的应用场景和需求。 另外,<glog/logging.h> 还提供了一些其他功能,如栈追踪信息的记录、日志的自动滚动和分割、对日志进行查找和过滤等。这些功能进一步增强了日志的可读性和可管理性,有助于快速定位和排查问题。 总之,<glog/logging.h> 是一个功能强大、易用且高性能的 C++ 日志库。它通过简化日志记录的过程和提供丰富的配置选项,极大地方便了开发人员进行日志管理和问题排查,是很多 C++ 项目中常用的工具之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值