glog 0.1
[platform/upstream/glog.git] / doc / glog.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2
3 <html>
4 <head>
5 <title>How To Use Google Logging Library (glog)</title>
6
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"
9       rel="shortcut icon">
10 <link href="designstyle.css" type="text/css" rel="stylesheet">
11 <style type="text/css">
12 <!--
13   ol.bluelist li {
14     color: #3366ff;
15     font-family: sans-serif;
16   }
17   ol.bluelist li p {
18     color: #000;
19     font-family: "Times Roman", times, serif;
20   }
21   ul.blacklist li {  
22     color: #000;
23     font-family: "Times Roman", times, serif;
24   }
25 //-->
26 </style>
27 </head>
28
29 <body>
30
31 <h1>How To Use Google Logging Library (glog)</h1>
32 <small>(as of
33 <script type=text/javascript>
34   var lm = new Date(document.lastModified);
35   document.write(lm.toDateString());
36 </script>)
37 </small>
38 <br>
39
40 <h2> <A NAME=intro>Introduction</A> </h2>
41
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(&lt;a
46 particular <a href="#severity">severity level</a>&gt;), e.g.
47
48 <pre>
49    #include &lt;google/logging.h&gt;
50
51    int main(int argc, char* argv[]) {
52      // Initialize Google's logging library.
53      google::InitGoogleLogging(argv[0]);
54
55      // ...
56      LOG(INFO) &lt;&lt; "Found " &lt;&lt; num_cookies &lt;&lt; " cookies";
57    }
58 </pre>
59
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/google</code> directory.
69
70 <h2> <A NAME=severity>Severity Level</A> </h2>
71
72 <p>
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
77 message is logged).
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>.
83
84 <p>
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>.
89
90 <p>Unless otherwise specified, glog writes to the filename
91 "/tmp/&lt;program name&gt;.&lt;hostname&gt;.&lt;user name&gt;.log.&lt;severity level&gt;.&lt;date&gt;.&lt;time&gt;.&lt;pid&gt;"
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.
96
97 <h2><A NAME=flags>Setting Flags</A></h2>
98
99 <p>Several flags influences 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:
107
108 <pre>
109    ./your_application --logtostderr=1
110 </pre>
111
112 If the Google gflags library isn't installed, you set flags via
113 environment variables, prefixing the flag name with "GLOG_", e.g.
114
115 <pre>
116    GLOG_logtostderr=1 ./your_application
117 </pre>
118
119 <p>The following flags are most commonly used:
120
121 <dl>
122 <dt><code>logtostderr</code> (<code>bool</code>, default=<code>false</code>)
123 <dd>Log messages to stderr instead of logfiles.<br>
124 Note: you can set binary flags to <code>true</code> by specifying
125 <code>1</code>, <code>true</code> , or <code>yes</code> (case
126 insensitive).
127 Also, you can set binary flags to <code>false</code> by specifying
128 <code>0</code>, <code>false</code>, or <code>no</code> (again, case
129 insensitive).
130 <dt><code>stderrthreshold</code> (<code>int</code>, default=2, which
131 is <code>ERROR</code>)
132 <dd>Copy log messages at or above this level to stderr in
133 addition to logfiles.  The numbers of severity levels
134 <code>INFO</code>, <code>WARNING</code>, <code>ERROR</code>, and 
135 <code>FATAL</code> are 0, 1, 2, and 3, respectively.
136 <dt><code>minloglevel</code> (<code>int</code>, default=0, which
137 is <code>INFO</code>)
138 <dd>Log messages at or above this level.  Again, the numbers of
139 severity levels <code>INFO</code>, <code>WARNING</code>,
140 <code>ERROR</code>, and <code>FATAL</code> are 0, 1, 2, and 3,
141 respectively.
142 <dt><code>log_dir</code> (<code>string</code>, default="")
143 <dd>If specified, logfiles are written into this directory instead
144 of the default logging directory.
145 <dt><code>v</code> (<code>int</code>, default=0)
146 <dd>Show all <code>VLOG(m)</code> messages for <code>m</code> less or
147 equal the value of this flag.  Overridable by --vmodule.
148 See <a href="#verbose">the section about verbose logging</a> for more
149 detail.
150 <dt><code>vmodule</code> (<code>string</code>, default="")
151 <dd>Per-module verbose level.  The argument has to contain a
152 comma-separated list of &lt;module name&gt;=&lt;log level&gt;.
153 &lt;module name&gt;
154 is a glob pattern (e.g., <code>gfs*</code> for all modules whose name
155 starts with "gfs"), matched against the filename base
156 (that is, name ignoring .cc/.h./-inl.h).
157 &lt;log level&gt; overrides any value given by --v.
158 See also <a href="#verbose">the section about verbose logging</a>.
159 </dl>
160
161 <p>There are some other flags defined in logging.cc.  Please grep the
162 source code for "DEFINE_" to see a complete list of all flags.
163
164 <h2><A NAME=conditional>Conditional / Occasional Logging</A></h2>
165
166 <p>Sometimes, you may only want to log a message under certain
167 conditions. You can use the following macros to perform conditional
168 logging:
169
170 <pre>
171    LOG_IF(INFO, num_cookies > 10) &lt;&lt; "Got lots of cookies";
172 </pre>
173
174 The "Got lots of cookies" message is logged only when the variable
175 <code>num_cookies</code> exceeds 10.
176
177 If a line of code is executed many times, it may be useful to only log
178 a message at certain intervals.  This kind of logging is most useful
179 for informational messages. 
180
181 <pre>
182    LOG_EVERY_N(INFO, 10) &lt;&lt; "Got the " &lt;&lt; COUNTER &lt;&lt; "th cookie";
183 </pre>
184
185 <p>The above line outputs a log messages on the 1st, 11th,
186 21st, ... times it is executed.  Note that the special
187 <code>COUNTER</code> value is used to identify which repetition is
188 happening.
189
190 <p>You can combine conditional and occasional logging with the
191 following macro.
192
193 <pre>
194    LOG_IF_EVERY_N(INFO, (size > 1024), 10) &lt;&lt; "Got the " &lt;&lt; COUNTER
195                                            &lt;&lt; "th big cookie";
196 </pre>
197
198 <p>Instead of outputting a message every nth time, you can also limit
199 the output to the first n occurrences:
200
201 <pre>
202    LOG_FIRST_N(INFO, 20) &lt;&lt; "Got the " &lt;&lt; COUNTER &lt;&lt; "th cookie";
203 </pre>
204
205 <p>Outputs log messages for the first 20 times it is executed.  Again,
206 the <code>COUNTER</code> identifier indicates which repetition is
207 happening.
208
209 <h2><A NAME=debug>Debug Mode Support</A></h2>
210
211 <p>Special "debug mode" logging macros only have an effect in debug
212 mode and are compiled away to nothing for non-debug mode
213 compiles.  Use these macros to avoid slowing down your production
214 application due to excessive logging.
215
216 <pre>
217    DLOG(INFO) &lt;&lt; "Found cookies";
218
219    DLOG_IF(INFO, num_cookies > 10) &lt;&lt; "Got lots of cookies";
220
221    DLOG_EVERY_N(INFO, 10) &lt;&lt; "Got the " &lt;&lt; COUNTER &lt;&lt; "th cookie";
222 </pre>
223
224 <p>All "debug mode" logging is compiled away to nothing for non-debug mode
225 compiles.
226
227 <h2><A NAME=check>CHECK Macros</A></h2>
228
229 <p>It is a good practice to check expected conditions in your program
230 frequently to detect errors as early as possible. The
231 <code>CHECK</code> macro provides the ability to abort the application
232 when a condition is not met, similar to the <code>assert</code> macro
233 defined in the standard C library.
234
235 <p><code>CHECK</code> aborts the application if a condition is not
236 true.  Unlike <code>assert</code>, it is *not* controlled by
237 <code>NDEBUG</code>, so the check will be executed regardless of
238 compilation mode.  Therefore, <code>fp->Write(x)</code> in the
239 following example is always executed:
240
241 <pre>
242    CHECK(fp->Write(x) == 4) &lt;&lt; "Write failed!";
243 </pre>
244
245 <p>There are various helper macros for
246 equality/inequality checks - <code>CHECK_EQ</code>,
247 <code>CHECK_NE</code>, <code>CHECK_LE</code>, <code>CHECK_LT</code>,
248 <code>CHECK_GE</code>, and <code>CHECK_GT</code>.
249 They compare two values, and log a
250 <code>FATAL</code> message including the two values when the result is
251 not as expected.  The values must have <code>operator&lt;&lt;(ostream,
252 ...)</code> defined.
253
254 <p>You may append to the error message like so:
255
256 <pre>
257    CHECK_NE(1, 2) &lt;&lt; ": The world must be ending!";
258 </pre>
259
260 <p>We are very careful to ensure that each argument is evaluated exactly
261 once, and that anything which is legal to pass as a function argument is
262 legal here.  In particular, the arguments may be temporary expressions
263 which will end up being destroyed at the end of the apparent statement,
264 for example:
265
266 <pre>
267    CHECK_EQ(string("abc")[1], 'b');
268 </pre>
269
270 <p>The compiler reports an error if one of the arguments is a
271 pointer and the other is NULL. To work around this, simply static_cast
272 NULL to the type of the desired pointer.
273
274 <pre>
275    CHECK_EQ(some_ptr, static_cast<SomeType*>(NULL));
276 </pre>
277
278 <p>Better yet, use the CHECK_NOTNULL macro:
279
280 <pre>
281    CHECK_NOTNULL(some_ptr);
282    some_ptr->DoSomething();
283 </pre>
284
285 <p>Since this macro returns the given pointer, this is very useful in
286 constructor initializer lists.
287
288 <pre>
289    struct S {
290      S(Something* ptr) : ptr_(CHECK_NOTNULL(ptr)) {}
291      Something* ptr_;
292    };
293 </pre>
294
295 <p>Note that you cannot use this macro as a C++ stream due to this
296 feature.  Please use <code>CHECK_EQ</code> described above to log a
297 custom message before aborting the application.
298
299 <p>If you are comparing C strings (char *), a handy set of macros
300 performs case sensitive as well as case insensitive comparisons -
301 <code>CHECK_STREQ</code>, <code>CHECK_STRNE</code>,
302 <code>CHECK_STRCASEEQ</code>, and <code>CHECK_STRCASENE</code>.  The
303 CASE versions are case-insensitive.  You can safely pass <code>NULL</code>
304 pointers for this macro.  They treat <code>NULL</code> and any
305 non-<code>NULL</code> string as not equal.  Two <code>NULL</code>s are
306 equal.
307
308 <p>Note that both arguments may be temporary strings which are
309 destructed at the end of the current "full expression"
310 (e.g., <code>CHECK_STREQ(Foo().c_str(), Bar().c_str())</code> where
311 <code>Foo</code> and <code>Bar</code> returns C++'s
312 <code>std::string</code>).
313
314 <p>The <code>CHECK_DOUBLE_EQ</code> macro checks the equality of two
315 floating point values, accepting a small error margin.
316 <code>CHECK_NEAR</code> accepts a third floating point argument, which
317 specifies the acceptable error margin.
318
319 <h2><A NAME=verbose>Verbose Logging</A></h2>
320
321 <p>When you are chasing difficult bugs, thorough log messages are very
322 useful.  However, you may want to ignore too verbose messages in usual
323 development.  For such verbose logging, glog provides the
324 <code>VLOG</code> macro, which allows you to define your own numeric
325 logging levels.  The <code>--v</code> command line option controls
326 which verbose messages are logged: 
327
328 <pre>
329    VLOG(1) &lt;&lt; "I'm printed when you run the program with --v=1 or higher";
330    VLOG(2) &lt;&lt; "I'm printed when you run the program with --v=2 or higher";
331 </pre>
332
333 <p>With <code>VLOG</code>, the lower the verbose level, the more
334 likely messages are to be logged.  For example, if
335 <code>--v==1</code>, <code>VLOG(1)</code> will log, but
336 <code>VLOG(2)</code> will not log.  This is opposite of the severity
337 level, where <code>INFO</code> is 0, and <code>ERROR</code> is 2.
338 <code>--minloglevel</code> of 1 will log <code>WARNING</code> and
339 above.  Though you can specify any integers for both <code>VLOG</code>
340 macro and <code>--v</code> flag, the common values for them are small
341 positive integers.  For example, if you write <code>VLOG(0)</code>,
342 you should specify <code>--v=-1</code> or lower to silence it.  This
343 is less useful since we may not want verbose logs by default in most
344 cases.  The <code>VLOG</code> macros always log at the
345 <code>INFO</code> log level (when they log at all).
346
347 <p>Verbose logging can be controlled from the command line on a
348 per-module basis:
349
350 <pre>
351    --vmodule=mapreduce=2,file=1,gfs*=3 --v=0
352 </pre>
353
354 <p>will:
355
356 <ul>
357   <li>a. Print VLOG(2) and lower messages from mapreduce.{h,cc}
358   <li>b. Print VLOG(1) and lower messages from file.{h,cc}
359   <li>c. Print VLOG(3) and lower messages from files prefixed with "gfs"
360   <li>d. Print VLOG(0) and lower messages from elsewhere
361 </ul>
362
363 <p>The wildcarding functionality shown by (c) supports both '*'
364 (matches 0 or more characters) and '?' (matches any single character)
365 wildcards.  Please also check the section about <a
366 href="#flags">command line flags</a>.
367
368 <p>There's also <code>VLOG_IS_ON(n)</code> "verbose level" condition
369 macro.  This macro returns true when the <code>--v</code> is equal or
370 greater than <code>n</code>.  To be used as
371
372 <pre>
373    if (VLOG_IS_ON(2)) {
374      // do some logging preparation and logging
375      // that can't be accomplished with just VLOG(2) &lt;&lt; ...;
376    }
377 </pre>
378
379 <p>Verbose level condition macros <code>VLOG_IF</code>,
380 <code>VLOG_EVERY_N</code> and <code>VLOG_IF_EVERY_N</code> behave
381 analogous to <code>LOG_IF</code>, <code>LOG_EVERY_N</code>,
382 <code>LOF_IF_EVERY</code>, but accept a numeric verbosity level as
383 opposed to a severity level.
384
385 <pre>
386    VLOG_IF(1, (size > 1024))
387       &lt;&lt; "I'm printed when size is more than 1024 and when you run the "
388          "program with --v=1 or more";
389    VLOG_EVERY_N(1, 10)
390       &lt;&lt; "I'm printed every 10th occurrence, and when you run the program "
391          "with --v=1 or more. Present occurence is " &lt;&lt; COUNTER;
392    VLOG_IF_EVERY_N(1, (size > 1024), 10)
393       &lt;&lt; "I'm printed on every 10th occurence of case when size is more "
394          " than 1024, when you run the program with --v=1 or more. ";
395          "Present occurence is " &lt;&lt; COUNTER;
396 </pre>
397
398 <h2> <A name="misc">Miscellaneous Notes</A> </h2>
399
400 <h3><A NAME=message>Performance of Messages</A></h3>
401
402 <p>The conditional logging macros provided by glog (e.g.,
403 <code>CHECK</code>, <code>LOG_IF</code>, <code>VLOG</code>, ...) are
404 carefully implemented and don't execute the right hand side
405 expressions when the conditions are false.  So, the following check
406 may not sacrifice the performance of your application.
407
408 <pre>
409    CHECK(obj.ok) << obj.CreatePrettyFormattedStringButVerySlow();
410 </pre>
411
412 <h3><A NAME=failure>User-defined Failure Function</A></h3>
413
414 <p><code>FATAL</code> severity level messages or unsatisfied
415 <code>CHECK</code> condition terminate your program.  You can change
416 the behavior of the termination by
417 <code>InstallFailureFunction</code>.
418
419 <pre>
420    void YourFailureFunction() {
421      // Reports something...
422      exit(1);
423    }
424
425    int main(int argc, char* argv[]) {
426      google::InstallFailureFunction(&amp;YourFailureFunction);
427    }
428 </pre>
429
430 <p>By default, glog tries to dump stacktrace and makes the program
431 exit with status 1.  The stacktrace is produced only when you run the
432 program on an architecture for which glog supports stack tracing (as
433 of September 2008, glog supports stack tracing for x86 and x86_64).
434
435 <h3><A NAME=raw>Raw Logging</A></h3>
436
437 <p>The header file <code>&lt;google/raw_logging.h&gt;</code> can be
438 used for thread-safe logging, which does not allocate any memory or
439 acquire any locks.  Therefore, the macros defined in this
440 header file can be used by low-level memory allocation and
441 synchronization code.
442 Please check <code>src/google/raw_logging.h.in</code> for detail.
443 </p>
444
445 <h3><A NAME=plog>Google Style perror()</A></h3>
446
447 <p><code>PLOG()</code> and <code>PLOG_IF()</code> and
448 <code>PCHECK()</code> behave exactly like their <code>LOG*</code> and
449 <code>CHECK</code> equivalents with the addition that they append a
450 description of the current state of errno to their output lines.
451 E.g.
452
453 <pre>
454    PCHECK(write(1, NULL, 2) >= 0) << "Write NULL failed";
455 </pre>
456
457 <p>This check fails with the following error message.
458
459 <pre>
460    F0825 185142 test.cc:22] Check failed: write(1, NULL, 2) >= 0 Write NULL failed: Bad address [14]
461 </pre>
462
463 <h3><A NAME=syslog>Syslog</A></h3>
464
465 <p><code>SYSLOG</code>, <code>SYSLOG_IF</code>, and
466 <code>SYSLOG_EVERY_N</code> macros are available.
467 These log to syslog in addition to the normal logs.  Be aware that
468 logging to syslog can drastically impact performance, especially if
469 syslog is configured for remote logging!  Make sure you understand the
470 implications of outputting to syslog before you use these macros. In
471 general, it's wise to use these macros sparingly.
472
473 <h3><A NAME=strip>Strip Logging Messages</A></h3>
474
475 <p>Strings used in log messages can increase the size of your binary
476 and present a privacy concern.  You can therefore instruct glog to
477 remove all strings which fall below a certain severity level by using
478 the GOOGLE_STRIP_LOG macro:
479
480 <p>If your application has code like this:
481
482 <pre>
483    #define GOOGLE_STRIP_LOG 1    // this must go before the #include!
484    #include &lt;google/logging.h&gt;
485 </pre>
486
487 <p>The compiler will remove the log messages whose severity are less
488 than the specified integer value.  Since
489 <code>VLOG</code> logs at the severity level <code>INFO</code>
490 (numeric value <code>0</code>),
491 setting <code>GOOGLE_STRIP_LOG</code> to 1 or greater removes
492 all log messages associated with <code>VLOG</code>s as well as
493 <code>INFO</code> log statements.
494
495 <hr>
496 <address>
497 Shinichiro Hamaji<br>
498 Gregor Hohpe<br>
499 <script type=text/javascript>
500   var lm = new Date(document.lastModified);
501   document.write(lm.toDateString());
502 </script>
503 </address>
504
505 </body>
506 </html>