1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
5 <title>How To Use Google Logging Library (glog)</title>
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
8 <link href="http://www.google.com/favicon.ico" type="image/x-icon"
10 <link href="designstyle.css" type="text/css" rel="stylesheet">
11 <style type="text/css">
15 font-family: sans-serif;
19 font-family: "Times Roman", times, serif;
23 font-family: "Times Roman", times, serif;
31 <h1>How To Use Google Logging Library (glog)</h1>
33 <script type=text/javascript>
34 var lm = new Date(document.lastModified);
35 document.write(lm.toDateString());
40 <h2> <A NAME=intro>Introduction</A> </h2>
42 <p><b>Google glog</b> is a library that implements application-level
43 logging. This library provides logging APIs based on C++-style
44 streams and various helper macros.
45 You can log a message by simply streaming things to LOG(<a
46 particular <a href="#severity">severity level</a>>), e.g.
49 #include <glog/logging.h>
51 int main(int argc, char* argv[]) {
52 // Initialize Google's logging library.
53 google::InitGoogleLogging(argv[0]);
56 LOG(INFO) << "Found " << num_cookies << " cookies";
60 <p>Google glog defines a series of macros that simplify many common logging
61 tasks. You can log messages by severity level, control logging
62 behavior from the command line, log based on conditionals, abort the
63 program when expected conditions are not met, introduce your own
64 verbose logging levels, and more. This document describes the
65 functionality supported by glog. Please note that this document
66 doesn't describe all features in this library, but the most useful
67 ones. If you want to find less common features, please check
68 header files under <code>src/glog</code> directory.
70 <h2> <A NAME=severity>Severity Level</A> </h2>
73 You can specify one of the following severity levels (in
74 increasing order of severity): <code>INFO</code>, <code>WARNING</code>,
75 <code>ERROR</code>, and <code>FATAL</code>.
76 Logging a <code>FATAL</code> message terminates the program (after the
78 Note that messages of a given severity are logged not only in the
79 logfile for that severity, but also in all logfiles of lower severity.
80 E.g., a message of severity <code>FATAL</code> will be logged to the
81 logfiles of severity <code>FATAL</code>, <code>ERROR</code>,
82 <code>WARNING</code>, and <code>INFO</code>.
85 The <code>DFATAL</code> severity logs a <code>FATAL</code> error in
86 debug mode (i.e., there is no <code>NDEBUG</code> macro defined), but
87 avoids halting the program in production by automatically reducing the
88 severity to <code>ERROR</code>.
90 <p>Unless otherwise specified, glog writes to the filename
91 "/tmp/<program name>.<hostname>.<user name>.log.<severity level>.<date>.<time>.<pid>"
92 (e.g., "/tmp/hello_world.example.com.hamaji.log.INFO.20080709-222411.10474").
93 By default, glog copies the log messages of severity level
94 <code>ERROR</code> or <code>FATAL</code> to standard error (stderr)
95 in addition to log files.
97 <h2><A NAME=flags>Setting Flags</A></h2>
99 <p>Several flags influence glog's output behavior.
100 If the <a href="http://code.google.com/p/google-gflags/">Google
101 gflags library</a> is installed on your machine, the
102 <code>configure</code> script (see the INSTALL file in the package for
103 detail of this script) will automatically detect and use it,
104 allowing you to pass flags on the command line. For example, if you
105 want to turn the flag <code>--logtostderr</code> on, you can start
106 your application with the following command line:
109 ./your_application --logtostderr=1
112 If the Google gflags library isn't installed, you set flags via
113 environment variables, prefixing the flag name with "GLOG_", e.g.
116 GLOG_logtostderr=1 ./your_application
119 <!-- TODO(hamaji): Fill the version number
120 <p>By glog version 0.x.x, you can use GLOG_* environment variables
121 even if you have gflags. If both an environment variable and a flag
122 are specified, the value specified by a flag wins. E.g., if GLOG_v=0
123 and --v=1, the verbosity will be 1, not 0.
126 <p>The following flags are most commonly used:
129 <dt><code>logtostderr</code> (<code>bool</code>, default=<code>false</code>)
130 <dd>Log messages to stderr instead of logfiles.<br>
131 Note: you can set binary flags to <code>true</code> by specifying
132 <code>1</code>, <code>true</code>, or <code>yes</code> (case
134 Also, you can set binary flags to <code>false</code> by specifying
135 <code>0</code>, <code>false</code>, or <code>no</code> (again, case
137 <dt><code>stderrthreshold</code> (<code>int</code>, default=2, which
138 is <code>ERROR</code>)
139 <dd>Copy log messages at or above this level to stderr in
140 addition to logfiles. The numbers of severity levels
141 <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>, and
142 <code>FATAL</code> are 0, 1, 2, and 3, respectively.
143 <dt><code>minloglevel</code> (<code>int</code>, default=0, which
144 is <code>INFO</code>)
145 <dd>Log messages at or above this level. Again, the numbers of
146 severity levels <code>INFO</code>, <code>WARNING</code>,
147 <code>ERROR</code>, and <code>FATAL</code> are 0, 1, 2, and 3,
149 <dt><code>log_dir</code> (<code>string</code>, default="")
150 <dd>If specified, logfiles are written into this directory instead
151 of the default logging directory.
152 <dt><code>v</code> (<code>int</code>, default=0)
153 <dd>Show all <code>VLOG(m)</code> messages for <code>m</code> less or
154 equal the value of this flag. Overridable by --vmodule.
155 See <a href="#verbose">the section about verbose logging</a> for more
157 <dt><code>vmodule</code> (<code>string</code>, default="")
158 <dd>Per-module verbose level. The argument has to contain a
159 comma-separated list of <module name>=<log level>.
161 is a glob pattern (e.g., <code>gfs*</code> for all modules whose name
162 starts with "gfs"), matched against the filename base
163 (that is, name ignoring .cc/.h./-inl.h).
164 <log level> overrides any value given by --v.
165 See also <a href="#verbose">the section about verbose logging</a>.
168 <p>There are some other flags defined in logging.cc. Please grep the
169 source code for "DEFINE_" to see a complete list of all flags.
171 <h2><A NAME=conditional>Conditional / Occasional Logging</A></h2>
173 <p>Sometimes, you may only want to log a message under certain
174 conditions. You can use the following macros to perform conditional
178 LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
181 The "Got lots of cookies" message is logged only when the variable
182 <code>num_cookies</code> exceeds 10.
184 If a line of code is executed many times, it may be useful to only log
185 a message at certain intervals. This kind of logging is most useful
186 for informational messages.
189 LOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
192 <p>The above line outputs a log messages on the 1st, 11th,
193 21st, ... times it is executed. Note that the special
194 <code>google::COUNTER</code> value is used to identify which repetition is
197 <p>You can combine conditional and occasional logging with the
201 LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << google::COUNTER
202 << "th big cookie";
205 <p>Instead of outputting a message every nth time, you can also limit
206 the output to the first n occurrences:
209 LOG_FIRST_N(INFO, 20) << "Got the " << google::COUNTER << "th cookie";
212 <p>Outputs log messages for the first 20 times it is executed. Again,
213 the <code>google::COUNTER</code> identifier indicates which repetition is
216 <h2><A NAME=debug>Debug Mode Support</A></h2>
218 <p>Special "debug mode" logging macros only have an effect in debug
219 mode and are compiled away to nothing for non-debug mode
220 compiles. Use these macros to avoid slowing down your production
221 application due to excessive logging.
224 DLOG(INFO) << "Found cookies";
226 DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
228 DLOG_EVERY_N(INFO, 10) << "Got the " << google::COUNTER << "th cookie";
231 <h2><A NAME=check>CHECK Macros</A></h2>
233 <p>It is a good practice to check expected conditions in your program
234 frequently to detect errors as early as possible. The
235 <code>CHECK</code> macro provides the ability to abort the application
236 when a condition is not met, similar to the <code>assert</code> macro
237 defined in the standard C library.
239 <p><code>CHECK</code> aborts the application if a condition is not
240 true. Unlike <code>assert</code>, it is *not* controlled by
241 <code>NDEBUG</code>, so the check will be executed regardless of
242 compilation mode. Therefore, <code>fp->Write(x)</code> in the
243 following example is always executed:
246 CHECK(fp->Write(x) == 4) << "Write failed!";
249 <p>There are various helper macros for
250 equality/inequality checks - <code>CHECK_EQ</code>,
251 <code>CHECK_NE</code>, <code>CHECK_LE</code>, <code>CHECK_LT</code>,
252 <code>CHECK_GE</code>, and <code>CHECK_GT</code>.
253 They compare two values, and log a
254 <code>FATAL</code> message including the two values when the result is
255 not as expected. The values must have <code>operator<<(ostream,
258 <p>You may append to the error message like so:
261 CHECK_NE(1, 2) << ": The world must be ending!";
264 <p>We are very careful to ensure that each argument is evaluated exactly
265 once, and that anything which is legal to pass as a function argument is
266 legal here. In particular, the arguments may be temporary expressions
267 which will end up being destroyed at the end of the apparent statement,
271 CHECK_EQ(string("abc")[1], 'b');
274 <p>The compiler reports an error if one of the arguments is a
275 pointer and the other is NULL. To work around this, simply static_cast
276 NULL to the type of the desired pointer.
279 CHECK_EQ(some_ptr, static_cast<SomeType*>(NULL));
282 <p>Better yet, use the CHECK_NOTNULL macro:
285 CHECK_NOTNULL(some_ptr);
286 some_ptr->DoSomething();
289 <p>Since this macro returns the given pointer, this is very useful in
290 constructor initializer lists.
294 S(Something* ptr) : ptr_(CHECK_NOTNULL(ptr)) {}
299 <p>Note that you cannot use this macro as a C++ stream due to this
300 feature. Please use <code>CHECK_EQ</code> described above to log a
301 custom message before aborting the application.
303 <p>If you are comparing C strings (char *), a handy set of macros
304 performs case sensitive as well as case insensitive comparisons -
305 <code>CHECK_STREQ</code>, <code>CHECK_STRNE</code>,
306 <code>CHECK_STRCASEEQ</code>, and <code>CHECK_STRCASENE</code>. The
307 CASE versions are case-insensitive. You can safely pass <code>NULL</code>
308 pointers for this macro. They treat <code>NULL</code> and any
309 non-<code>NULL</code> string as not equal. Two <code>NULL</code>s are
312 <p>Note that both arguments may be temporary strings which are
313 destructed at the end of the current "full expression"
314 (e.g., <code>CHECK_STREQ(Foo().c_str(), Bar().c_str())</code> where
315 <code>Foo</code> and <code>Bar</code> return C++'s
316 <code>std::string</code>).
318 <p>The <code>CHECK_DOUBLE_EQ</code> macro checks the equality of two
319 floating point values, accepting a small error margin.
320 <code>CHECK_NEAR</code> accepts a third floating point argument, which
321 specifies the acceptable error margin.
323 <h2><A NAME=verbose>Verbose Logging</A></h2>
325 <p>When you are chasing difficult bugs, thorough log messages are very
326 useful. However, you may want to ignore too verbose messages in usual
327 development. For such verbose logging, glog provides the
328 <code>VLOG</code> macro, which allows you to define your own numeric
329 logging levels. The <code>--v</code> command line option controls
330 which verbose messages are logged:
333 VLOG(1) << "I'm printed when you run the program with --v=1 or higher";
334 VLOG(2) << "I'm printed when you run the program with --v=2 or higher";
337 <p>With <code>VLOG</code>, the lower the verbose level, the more
338 likely messages are to be logged. For example, if
339 <code>--v==1</code>, <code>VLOG(1)</code> will log, but
340 <code>VLOG(2)</code> will not log. This is opposite of the severity
341 level, where <code>INFO</code> is 0, and <code>ERROR</code> is 2.
342 <code>--minloglevel</code> of 1 will log <code>WARNING</code> and
343 above. Though you can specify any integers for both <code>VLOG</code>
344 macro and <code>--v</code> flag, the common values for them are small
345 positive integers. For example, if you write <code>VLOG(0)</code>,
346 you should specify <code>--v=-1</code> or lower to silence it. This
347 is less useful since we may not want verbose logs by default in most
348 cases. The <code>VLOG</code> macros always log at the
349 <code>INFO</code> log level (when they log at all).
351 <p>Verbose logging can be controlled from the command line on a
355 --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
361 <li>a. Print VLOG(2) and lower messages from mapreduce.{h,cc}
362 <li>b. Print VLOG(1) and lower messages from file.{h,cc}
363 <li>c. Print VLOG(3) and lower messages from files prefixed with "gfs"
364 <li>d. Print VLOG(0) and lower messages from elsewhere
367 <p>The wildcarding functionality shown by (c) supports both '*'
368 (matches 0 or more characters) and '?' (matches any single character)
369 wildcards. Please also check the section about <a
370 href="#flags">command line flags</a>.
372 <p>There's also <code>VLOG_IS_ON(n)</code> "verbose level" condition
373 macro. This macro returns true when the <code>--v</code> is equal or
374 greater than <code>n</code>. To be used as
378 // do some logging preparation and logging
379 // that can't be accomplished with just VLOG(2) << ...;
383 <p>Verbose level condition macros <code>VLOG_IF</code>,
384 <code>VLOG_EVERY_N</code> and <code>VLOG_IF_EVERY_N</code> behave
385 analogous to <code>LOG_IF</code>, <code>LOG_EVERY_N</code>,
386 <code>LOF_IF_EVERY</code>, but accept a numeric verbosity level as
387 opposed to a severity level.
390 VLOG_IF(1, (size > 1024))
391 << "I'm printed when size is more than 1024 and when you run the "
392 "program with --v=1 or more";
394 << "I'm printed every 10th occurrence, and when you run the program "
395 "with --v=1 or more. Present occurence is " << google::COUNTER;
396 VLOG_IF_EVERY_N(1, (size > 1024), 10)
397 << "I'm printed on every 10th occurence of case when size is more "
398 " than 1024, when you run the program with --v=1 or more. ";
399 "Present occurence is " << google::COUNTER;
402 <h2> <A name="signal">Failure Signal Handler</A> </h2>
405 The library provides a convenient signal handler that will dump useful
406 information when the program crashes on certain signals such as SIGSEGV.
407 The signal handler can be installed by
408 google::InstallFailureSignalHandler(). The following is an example of output
409 from the signal handler.
412 *** Aborted at 1225095260 (unix time) try "date -d @1225095260" if you are using GNU date ***
413 *** SIGSEGV (@0x0) received by PID 17711 (TID 0x7f893090a6f0) from PID 0; stack trace: ***
414 PC: @ 0x412eb1 TestWaitingLogSink::send()
415 @ 0x7f892fb417d0 (unknown)
416 @ 0x412eb1 TestWaitingLogSink::send()
417 @ 0x7f89304f7f06 google::LogMessage::SendToLog()
418 @ 0x7f89304f35af google::LogMessage::Flush()
419 @ 0x7f89304f3739 google::LogMessage::~LogMessage()
420 @ 0x408cf4 TestLogSinkWaitTillSent()
422 @ 0x7f892f7ef1c4 (unknown)
427 By default, the signal handler writes the failure dump to the standard
428 error. You can customize the destination by InstallFailureWriter().
430 <h2> <A name="misc">Miscellaneous Notes</A> </h2>
432 <h3><A NAME=message>Performance of Messages</A></h3>
434 <p>The conditional logging macros provided by glog (e.g.,
435 <code>CHECK</code>, <code>LOG_IF</code>, <code>VLOG</code>, ...) are
436 carefully implemented and don't execute the right hand side
437 expressions when the conditions are false. So, the following check
438 may not sacrifice the performance of your application.
441 CHECK(obj.ok) << obj.CreatePrettyFormattedStringButVerySlow();
444 <h3><A NAME=failure>User-defined Failure Function</A></h3>
446 <p><code>FATAL</code> severity level messages or unsatisfied
447 <code>CHECK</code> condition terminate your program. You can change
448 the behavior of the termination by
449 <code>InstallFailureFunction</code>.
452 void YourFailureFunction() {
453 // Reports something...
457 int main(int argc, char* argv[]) {
458 google::InstallFailureFunction(&YourFailureFunction);
462 <p>By default, glog tries to dump stacktrace and makes the program
463 exit with status 1. The stacktrace is produced only when you run the
464 program on an architecture for which glog supports stack tracing (as
465 of September 2008, glog supports stack tracing for x86 and x86_64).
467 <h3><A NAME=raw>Raw Logging</A></h3>
469 <p>The header file <code><glog/raw_logging.h></code> can be
470 used for thread-safe logging, which does not allocate any memory or
471 acquire any locks. Therefore, the macros defined in this
472 header file can be used by low-level memory allocation and
473 synchronization code.
474 Please check <code>src/glog/raw_logging.h.in</code> for detail.
477 <h3><A NAME=plog>Google Style perror()</A></h3>
479 <p><code>PLOG()</code> and <code>PLOG_IF()</code> and
480 <code>PCHECK()</code> behave exactly like their <code>LOG*</code> and
481 <code>CHECK</code> equivalents with the addition that they append a
482 description of the current state of errno to their output lines.
486 PCHECK(write(1, NULL, 2) >= 0) << "Write NULL failed";
489 <p>This check fails with the following error message.
492 F0825 185142 test.cc:22] Check failed: write(1, NULL, 2) >= 0 Write NULL failed: Bad address [14]
495 <h3><A NAME=syslog>Syslog</A></h3>
497 <p><code>SYSLOG</code>, <code>SYSLOG_IF</code>, and
498 <code>SYSLOG_EVERY_N</code> macros are available.
499 These log to syslog in addition to the normal logs. Be aware that
500 logging to syslog can drastically impact performance, especially if
501 syslog is configured for remote logging! Make sure you understand the
502 implications of outputting to syslog before you use these macros. In
503 general, it's wise to use these macros sparingly.
505 <h3><A NAME=strip>Strip Logging Messages</A></h3>
507 <p>Strings used in log messages can increase the size of your binary
508 and present a privacy concern. You can therefore instruct glog to
509 remove all strings which fall below a certain severity level by using
510 the GOOGLE_STRIP_LOG macro:
512 <p>If your application has code like this:
515 #define GOOGLE_STRIP_LOG 1 // this must go before the #include!
516 #include <glog/logging.h>
519 <p>The compiler will remove the log messages whose severities are less
520 than the specified integer value. Since
521 <code>VLOG</code> logs at the severity level <code>INFO</code>
522 (numeric value <code>0</code>),
523 setting <code>GOOGLE_STRIP_LOG</code> to 1 or greater removes
524 all log messages associated with <code>VLOG</code>s as well as
525 <code>INFO</code> log statements.
527 <h3><A NAME=windows>Notes for Windows users</A></h3>
529 <p>Google glog defines a severity level <code>ERROR</code>, which is
530 also defined in <code>windows.h</code> . You can make glog not define
531 <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>,
532 and <code>FATAL</code> by defining
533 <code>GLOG_NO_ABBREVIATED_SEVERITIES</code> before
534 including <code>glog/logging.h</code> . Even with this macro, you can
535 still use the iostream like logging facilities:
538 #define GLOG_NO_ABBREVIATED_SEVERITIES
539 #include <windows.h>
540 #include <glog/logging.h>
544 LOG(ERROR) << "This should work";
545 LOG_IF(ERROR, x > y) << "This should be also OK";
550 use <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>,
551 and <code>FATAL</code> anymore for functions defined
552 in <code>glog/logging.h</code> .
555 #define GLOG_NO_ABBREVIATED_SEVERITIES
556 #include <windows.h>
557 #include <glog/logging.h>
562 // google::FlushLogFiles(google::ERROR);
565 google::FlushLogFiles(google::GLOG_ERROR);
569 If you don't need <code>ERROR</code> defined
570 by <code>windows.h</code>, there are a couple of more workarounds
571 which sometimes don't work:
574 <li>#define <code>WIN32_LEAN_AND_MEAN</code> or <code>NOGDI</code>
575 <strong>before</strong> you #include <code>windows.h</code> .
576 <li>#undef <code>ERROR</code> <strong>after</strong> you #include
577 <code>windows.h</code> .
580 <p>See <a href="http://code.google.com/p/google-glog/issues/detail?id=33">
581 this issue</a> for more detail.
585 Shinichiro Hamaji<br>
587 <script type=text/javascript>
588 var lm = new Date(document.lastModified);
589 document.write(lm.toDateString());