language_detection 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
Files changed (100) hide show
  1. data/.gitignore +19 -0
  2. data/Gemfile +4 -0
  3. data/LICENSE.txt +22 -0
  4. data/README.md +85 -0
  5. data/Rakefile +11 -0
  6. data/ext/cld/Makefile +34 -0
  7. data/ext/cld/base/basictypes.h +348 -0
  8. data/ext/cld/base/build_config.h +124 -0
  9. data/ext/cld/base/casts.h +156 -0
  10. data/ext/cld/base/commandlineflags.h +443 -0
  11. data/ext/cld/base/crash.h +41 -0
  12. data/ext/cld/base/dynamic_annotations.h +358 -0
  13. data/ext/cld/base/global_strip_options.h +59 -0
  14. data/ext/cld/base/log_severity.h +46 -0
  15. data/ext/cld/base/logging.h +1403 -0
  16. data/ext/cld/base/macros.h +243 -0
  17. data/ext/cld/base/port.h +54 -0
  18. data/ext/cld/base/scoped_ptr.h +428 -0
  19. data/ext/cld/base/stl_decl.h +0 -0
  20. data/ext/cld/base/stl_decl_msvc.h +107 -0
  21. data/ext/cld/base/string_util.h +29 -0
  22. data/ext/cld/base/strtoint.h +93 -0
  23. data/ext/cld/base/template_util.h +96 -0
  24. data/ext/cld/base/type_traits.h +198 -0
  25. data/ext/cld/base/vlog_is_on.h +143 -0
  26. data/ext/cld/cld.so +0 -0
  27. data/ext/cld/encodings/compact_lang_det/cldutil.cc +905 -0
  28. data/ext/cld/encodings/compact_lang_det/cldutil.h +1205 -0
  29. data/ext/cld/encodings/compact_lang_det/cldutil_dbg.h +76 -0
  30. data/ext/cld/encodings/compact_lang_det/cldutil_dbg_empty.cc +76 -0
  31. data/ext/cld/encodings/compact_lang_det/compact_lang_det.cc +62 -0
  32. data/ext/cld/encodings/compact_lang_det/compact_lang_det.h +145 -0
  33. data/ext/cld/encodings/compact_lang_det/compact_lang_det_impl.cc +2574 -0
  34. data/ext/cld/encodings/compact_lang_det/compact_lang_det_impl.h +173 -0
  35. data/ext/cld/encodings/compact_lang_det/compact_lang_det_unittest_small.cc +406 -0
  36. data/ext/cld/encodings/compact_lang_det/compile.cmd +1 -0
  37. data/ext/cld/encodings/compact_lang_det/ext_lang_enc.cc +545 -0
  38. data/ext/cld/encodings/compact_lang_det/ext_lang_enc.h +119 -0
  39. data/ext/cld/encodings/compact_lang_det/generated/cld_generated_score_deltaoctachrome_0406.cc +380 -0
  40. data/ext/cld/encodings/compact_lang_det/generated/cld_generated_score_quadchrome_0406.cc +382 -0
  41. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_cjkbis_0.cc +49 -0
  42. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_ctjkvz.cc +7119 -0
  43. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_ctjkvz_0.cc +61 -0
  44. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_deltaoctachrome.cc +1263 -0
  45. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_longwords8_0.cc +53 -0
  46. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_meanscore.h +10 -0
  47. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_quads_0.cc +50 -0
  48. data/ext/cld/encodings/compact_lang_det/generated/compact_lang_det_generated_quadschrome.cc +70935 -0
  49. data/ext/cld/encodings/compact_lang_det/getonescriptspan.cc +570 -0
  50. data/ext/cld/encodings/compact_lang_det/getonescriptspan.h +131 -0
  51. data/ext/cld/encodings/compact_lang_det/letterscript_enum.cc +117 -0
  52. data/ext/cld/encodings/compact_lang_det/letterscript_enum.h +99 -0
  53. data/ext/cld/encodings/compact_lang_det/subsetsequence.cc +259 -0
  54. data/ext/cld/encodings/compact_lang_det/subsetsequence.h +44 -0
  55. data/ext/cld/encodings/compact_lang_det/subsetsequence_unittest.cc +99 -0
  56. data/ext/cld/encodings/compact_lang_det/tote.cc +299 -0
  57. data/ext/cld/encodings/compact_lang_det/tote.h +89 -0
  58. data/ext/cld/encodings/compact_lang_det/unittest_data.h +193 -0
  59. data/ext/cld/encodings/compact_lang_det/utf8propjustletter.h +1162 -0
  60. data/ext/cld/encodings/compact_lang_det/utf8propletterscriptnum.h +1222 -0
  61. data/ext/cld/encodings/compact_lang_det/utf8scannotjustletterspecial.h +1185 -0
  62. data/ext/cld/encodings/compact_lang_det/win/cld_basictypes.h +10 -0
  63. data/ext/cld/encodings/compact_lang_det/win/cld_commandlineflags.h +28 -0
  64. data/ext/cld/encodings/compact_lang_det/win/cld_google.h +18 -0
  65. data/ext/cld/encodings/compact_lang_det/win/cld_htmlutils.h +13 -0
  66. data/ext/cld/encodings/compact_lang_det/win/cld_htmlutils_google3.cc +32 -0
  67. data/ext/cld/encodings/compact_lang_det/win/cld_htmlutils_windows.cc +29 -0
  68. data/ext/cld/encodings/compact_lang_det/win/cld_logging.h +21 -0
  69. data/ext/cld/encodings/compact_lang_det/win/cld_macros.h +19 -0
  70. data/ext/cld/encodings/compact_lang_det/win/cld_strtoint.h +26 -0
  71. data/ext/cld/encodings/compact_lang_det/win/cld_unicodetext.cc +84 -0
  72. data/ext/cld/encodings/compact_lang_det/win/cld_unicodetext.h +40 -0
  73. data/ext/cld/encodings/compact_lang_det/win/cld_unilib.h +15 -0
  74. data/ext/cld/encodings/compact_lang_det/win/cld_unilib_google3.cc +18 -0
  75. data/ext/cld/encodings/compact_lang_det/win/cld_unilib_windows.cc +29 -0
  76. data/ext/cld/encodings/compact_lang_det/win/cld_utf.h +24 -0
  77. data/ext/cld/encodings/compact_lang_det/win/cld_utf8statetable.cc +224 -0
  78. data/ext/cld/encodings/compact_lang_det/win/cld_utf8statetable.h +141 -0
  79. data/ext/cld/encodings/compact_lang_det/win/cld_utf8utils.h +22 -0
  80. data/ext/cld/encodings/compact_lang_det/win/cld_utf8utils_google3.cc +18 -0
  81. data/ext/cld/encodings/compact_lang_det/win/cld_utf8utils_windows.cc +17 -0
  82. data/ext/cld/encodings/compact_lang_det/win/normalizedunicodetext.cc +172 -0
  83. data/ext/cld/encodings/compact_lang_det/win/normalizedunicodetext.h +67 -0
  84. data/ext/cld/encodings/internal/encodings.cc +12 -0
  85. data/ext/cld/encodings/lang_enc.h +254 -0
  86. data/ext/cld/encodings/proto/encodings.pb.h +169 -0
  87. data/ext/cld/encodings/public/encodings.h +301 -0
  88. data/ext/cld/extconf.rb +1 -0
  89. data/ext/cld/language_detection.cc +88 -0
  90. data/ext/cld/languages/internal/languages.cc +337 -0
  91. data/ext/cld/languages/proto/languages.pb.h +179 -0
  92. data/ext/cld/languages/public/languages.h +379 -0
  93. data/language_detection.gemspec +28 -0
  94. data/lib/language_detection/string.rb +1 -0
  95. data/lib/language_detection/version.rb +3 -0
  96. data/lib/language_detection.rb +54 -0
  97. data/test/_helper.rb +15 -0
  98. data/test/fixtures/languages.csv +80 -0
  99. data/test/language_detection_test.rb +88 -0
  100. metadata +250 -0
@@ -0,0 +1,1403 @@
1
+ // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2
+ // Use of this source code is governed by a BSD-style license that can be
3
+ // found in the LICENSE file.
4
+
5
+ #ifndef _LOGGING_H_
6
+ #define _LOGGING_H_
7
+
8
+ #include <errno.h>
9
+ #include <string.h>
10
+ #include <time.h>
11
+ #include <string>
12
+ #include <strstream>
13
+ #include <vector>
14
+
15
+ #ifndef COMPILER_MSVC
16
+ #include <unistd.h> // for _exit()
17
+ #endif
18
+
19
+ #include "base/port.h"
20
+ #include "base/basictypes.h"
21
+ #include "base/commandlineflags.h"
22
+ #include "base/crash.h"
23
+ #include "base/dynamic_annotations.h"
24
+ #include "base/macros.h"
25
+ #include "base/memory/scoped_ptr.h"
26
+ #include "base/stl_decl_msvc.h"
27
+ #include "base/log_severity.h"
28
+ #include "base/vlog_is_on.h"
29
+ #include "global_strip_options.h"
30
+
31
+ // Make a bunch of macros for logging. The way to log things is to stream
32
+ // things to LOG(<a particular severity level>). E.g.,
33
+ //
34
+ // LOG(INFO) << "Found " << num_cookies << " cookies";
35
+ //
36
+ // You can capture log messages in a string, rather than reporting them
37
+ // immediately:
38
+ //
39
+ // vector<string> errors;
40
+ // LOG_STRING(ERROR, &errors) << "Couldn't parse cookie #" << cookie_num;
41
+ //
42
+ // This pushes back the new error onto 'errors'; if given a NULL pointer,
43
+ // it reports the error via LOG(ERROR).
44
+ //
45
+ // You can also do conditional logging:
46
+ //
47
+ // LOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
48
+ //
49
+ // You can also do occasional logging (log every n'th occurrence of an
50
+ // event):
51
+ //
52
+ // LOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
53
+ //
54
+ // The above will cause log messages to be output on the 1st, 11th, 21st, ...
55
+ // times it is executed. Note that the special COUNTER value is used to
56
+ // identify which repetition is happening.
57
+ //
58
+ // You can also do occasional conditional logging (log every n'th
59
+ // occurrence of an event, when condition is satisfied):
60
+ //
61
+ // LOG_IF_EVERY_N(INFO, (size > 1024), 10) << "Got the " << COUNTER
62
+ // << "th big cookie";
63
+ //
64
+ // You can log messages the first N times your code executes a line. E.g.
65
+ //
66
+ // LOG_FIRST_N(INFO, 20) << "Got the " << COUNTER << "th cookie";
67
+ //
68
+ // Outputs log messages for the first 20 times it is executed.
69
+ //
70
+ // Analogous SYSLOG, SYSLOG_IF, and SYSLOG_EVERY_N macros are available.
71
+ // These log to syslog as well as to the normal logs. If you use these at
72
+ // all, you need to be aware that syslog can drastically reduce performance,
73
+ // especially if it is configured for remote logging! Don't use these
74
+ // unless you fully understand this and have a concrete need to use them.
75
+ // Even then, try to minimize your use of them.
76
+ //
77
+ // There are also "debug mode" logging macros like the ones above:
78
+ //
79
+ // DLOG(INFO) << "Found cookies";
80
+ //
81
+ // DLOG_IF(INFO, num_cookies > 10) << "Got lots of cookies";
82
+ //
83
+ // DLOG_EVERY_N(INFO, 10) << "Got the " << COUNTER << "th cookie";
84
+ //
85
+ // All "debug mode" logging is compiled away to nothing for non-debug mode
86
+ // compiles.
87
+ //
88
+ // We also have
89
+ //
90
+ // LOG_ASSERT(assertion);
91
+ // DLOG_ASSERT(assertion);
92
+ //
93
+ // which is syntactic sugar for {,D}LOG_IF(FATAL, assert fails) << assertion;
94
+ //
95
+ // We also override the standard 'assert' to use 'DLOG_ASSERT'.
96
+ //
97
+ // There are "verbose level" logging macros. They look like
98
+ //
99
+ // VLOG(1) << "I'm printed when you run the program with --v=1 or more";
100
+ // VLOG(2) << "I'm printed when you run the program with --v=2 or more";
101
+ //
102
+ // These always log at the INFO log level (when they log at all).
103
+ // The verbose logging can also be turned on module-by-module. For instance,
104
+ // --vmodule=recordio=2,file=1,gfs*=3 --v=0
105
+ // will cause:
106
+ // a. VLOG(2) and lower messages to be printed from recordio.{h,cc}
107
+ // b. VLOG(1) and lower messages to be printed from google2file
108
+ // c. VLOG(3) and lower messages to be printed from files prefixed with "gfs"
109
+ // d. VLOG(0) and lower messages to be printed from elsewhere
110
+ //
111
+ // The wildcarding functionality shown by (c) supports both '*' (match
112
+ // 0 or more characters) and '?' (match any single character) wildcards.
113
+ //
114
+ // There's also VLOG_IS_ON(n) "verbose level" condition macro. To be used as
115
+ //
116
+ // if (VLOG_IS_ON(2)) {
117
+ // // do some logging preparation and logging
118
+ // // that can't be accomplished with just VLOG(2) << ...;
119
+ // }
120
+ //
121
+ // There are also VLOG_IF, VLOG_EVERY_N and VLOG_IF_EVERY_N "verbose level"
122
+ // condition macros for sample cases, when some extra computation and
123
+ // preparation for logs is not needed.
124
+ // VLOG_IF(1, (size > 1024))
125
+ // << "I'm printed when size is more than 1024 and when you run the "
126
+ // "program with --v=1 or more";
127
+ // VLOG_EVERY_N(1, 10)
128
+ // << "I'm printed every 10th occurrence, and when you run the program "
129
+ // "with --v=1 or more. Present occurence is " << COUNTER;
130
+ // VLOG_IF_EVERY_N(1, (size > 1024), 10)
131
+ // << "I'm printed on every 10th occurence of case when size is more "
132
+ // " than 1024, when you run the program with --v=1 or more. ";
133
+ // "Present occurence is " << COUNTER;
134
+ //
135
+ // [MLOG is OBSOLETE - use the more convenient VLOG(n) macros]
136
+ // There is also an MLOG option that enables module-level logging. MLOG
137
+ // is associated with a specific flag by defining a MODULE_FLAG macro.
138
+ // Other than this, it behaves like VLOG. Example:
139
+ // DEFINE_int32(dnsverbose, 0, "Verbose level for DNS module");
140
+ // #define MODULE_FLAG FLAGS_dnsverbose
141
+ // MLOG(1) << "I'm printed when you run with --dnsverbose=1 or more";
142
+ //
143
+ // The supported severity levels for macros that allow you to specify one
144
+ // are (in increasing order of severity) INFO, WARNING, ERROR, and FATAL.
145
+ // Note that messages of a given severity are logged not only in the
146
+ // logfile for that severity, but also in all logfiles of lower severity.
147
+ // E.g., a message of severity FATAL will be logged to the logfiles of
148
+ // severity FATAL, ERROR, WARNING, and INFO.
149
+ //
150
+ // There is also the special severity of DFATAL, which logs FATAL in
151
+ // debug mode, ERROR in normal mode.
152
+ //
153
+ // Very important: logging a message at the FATAL severity level causes
154
+ // the program to terminate (after the message is logged).
155
+ //
156
+ // Unless otherwise specified, logs will be written to the filename
157
+ // "<program name>.<hostname>.<user name>.log.<severity level>.", followed
158
+ // by the date, time, and pid (you can't prevent the date, time, and pid
159
+ // from being in the filename).
160
+ //
161
+ // The logging code takes two flags:
162
+ // --v=# set the verbose level
163
+ // --logtostderr log all the messages to stderr instead of to logfiles
164
+
165
+ // LOG LINE PREFIX FORMAT
166
+ //
167
+ // Log lines have this form:
168
+ //
169
+ // Lmmdd hh:mm:ss.uuuuuu threadid file:line] msg...
170
+ //
171
+ // where the fields are defined as follows:
172
+ //
173
+ // L A single character, representing the log level
174
+ // (eg 'I' for INFO)
175
+ // mm The month (zero padded; ie May is '05')
176
+ // dd The day (zero padded)
177
+ // hh:mm:ss.uuuuuu Time in hours, minutes and fractional seconds
178
+ // threadid The space-padded thread ID as returned by GetTID()
179
+ // (this matches the PID on Linux)
180
+ // file The file name
181
+ // line The line number
182
+ // msg The user-supplied message
183
+ //
184
+ // Example:
185
+ //
186
+ // I1103 11:57:31.739339 24395 google.cc:2341] Command line: ./some_prog
187
+ // I1103 11:57:31.739403 24395 google.cc:2342] Process id 24395
188
+ //
189
+ // NOTE: although the microseconds are useful for comparing events on
190
+ // a single machine, clocks on different machines may not be well
191
+ // synchronized. Hence, use caution when comparing the low bits of
192
+ // timestamps from different machines.
193
+
194
+ // Set whether log messages go to stderr instead of logfiles
195
+ DECLARE_bool(logtostderr);
196
+
197
+ // Set whether log messages go to stderr in addition to logfiles.
198
+ DECLARE_bool(alsologtostderr);
199
+
200
+ // Log messages at a level >= this flag are automatically sent to
201
+ // stderr in addition to log files.
202
+ DECLARE_int32(stderrthreshold);
203
+
204
+ // Set whether the log prefix should be prepended to each line of output.
205
+ DECLARE_bool(log_prefix);
206
+
207
+ // Log messages at a level <= this flag are buffered.
208
+ // Log messages at a higher level are flushed immediately.
209
+ DECLARE_int32(logbuflevel);
210
+
211
+ // Sets the maximum number of seconds which logs may be buffered for.
212
+ DECLARE_int32(logbufsecs);
213
+
214
+ // Should Google1 logging be turned on?
215
+ DECLARE_bool(logging);
216
+
217
+ // Log suppression level: messages logged at a lower level than this
218
+ // are suppressed.
219
+ DECLARE_int32(minloglevel);
220
+
221
+ // If specified, logfiles are written into this directory instead of the
222
+ // default logging directory.
223
+ DECLARE_string(log_dir);
224
+
225
+ // Sets the path of the directory into which to put additional links
226
+ // to the log files.
227
+ DECLARE_string(log_link);
228
+
229
+ // Sets the maximum log file size (in MB).
230
+ DECLARE_int32(max_log_size);
231
+
232
+ // Should log IO be directed to a background thread? This flag has no
233
+ // effect unless //thread/logger:logger is linked into the binary.
234
+ DECLARE_bool(threaded_logging);
235
+
236
+ // Set to cause StatusMessage() to write status to ./STATUS file.
237
+ DECLARE_bool(status_messages_to_status_file);
238
+
239
+ // Sets whether to avoid logging to the disk if the disk is full.
240
+ DECLARE_bool(stop_logging_if_full_disk);
241
+
242
+ // Log messages below the STRIP_LOG level will be compiled away for
243
+ // security reasons. See LOG(severtiy) below. STRIP_LOG is defined in
244
+ // //base/global_strip_log.h
245
+
246
+ // A few definitions of macros that don't generate much code. Since
247
+ // LOG(INFO) and its ilk are used all over our code, it's
248
+ // better to have compact code for these operations.
249
+
250
+ #if STRIP_LOG == 0
251
+ #define COMPACT_GOOGLE_LOG_INFO LogMessage(__FILE__, __LINE__)
252
+ #define LOG_TO_STRING_INFO(message) LogMessage(__FILE__, __LINE__, INFO, \
253
+ message)
254
+ #else
255
+ #define COMPACT_GOOGLE_LOG_INFO NullStream()
256
+ #define LOG_TO_STRING_INFO(message) NullStream()
257
+ #endif
258
+
259
+ #if STRIP_LOG <= 1
260
+ #define COMPACT_GOOGLE_LOG_WARNING LogMessage(__FILE__, __LINE__, WARNING)
261
+ #define LOG_TO_STRING_WARNING(message) LogMessage(__FILE__, __LINE__, \
262
+ WARNING, message)
263
+ #else
264
+ #define COMPACT_GOOGLE_LOG_WARNING NullStream()
265
+ #define LOG_TO_STRING_WARNING(message) NullStream()
266
+ #endif
267
+
268
+ #if STRIP_LOG <= 2
269
+ #define COMPACT_GOOGLE_LOG_ERROR LogMessage(__FILE__, __LINE__, ERROR)
270
+ #define LOG_TO_STRING_ERROR(message) LogMessage(__FILE__, __LINE__, ERROR, \
271
+ message)
272
+ #else
273
+ #define COMPACT_GOOGLE_LOG_ERROR NullStream()
274
+ #define LOG_TO_STRING_ERROR(message) NullStream()
275
+ #endif
276
+
277
+ #if STRIP_LOG <= 3
278
+ #define COMPACT_GOOGLE_LOG_FATAL LogMessageFatal(__FILE__, __LINE__)
279
+ #define COMPACT_GOOGLE_LOG_QFATAL LogMessageQuietlyFatal(__FILE__, __LINE__)
280
+ #define LOG_TO_STRING_FATAL(message) LogMessage(__FILE__, __LINE__, FATAL, \
281
+ message)
282
+ #else
283
+ #define COMPACT_GOOGLE_LOG_FATAL NullStreamFatal()
284
+ #define COMPACT_GOOGLE_LOG_QFATAL NullStreamFatal()
285
+ #define LOG_TO_STRING_FATAL(message) NullStreamFatal()
286
+ #endif
287
+
288
+ // For DFATAL, we want to use LogMessage (as opposed to
289
+ // LogMessageFatal), to be consistent with the original behavior.
290
+ #ifdef NDEBUG
291
+ #define COMPACT_GOOGLE_LOG_DFATAL COMPACT_GOOGLE_LOG_ERROR
292
+ #elif STRIP_LOG <= 3
293
+ #define COMPACT_GOOGLE_LOG_DFATAL LogMessage(__FILE__, __LINE__, FATAL)
294
+ #else
295
+ #define COMPACT_GOOGLE_LOG_DFATAL NullStreamFatal()
296
+ #endif
297
+
298
+ #define GOOGLE_LOG_INFO(counter) \
299
+ LogMessage(__FILE__, __LINE__, INFO, counter, &LogMessage::SendToLog)
300
+ #define SYSLOG_INFO(counter) \
301
+ LogMessage(__FILE__, __LINE__, INFO, counter, \
302
+ &LogMessage::SendToSyslogAndLog)
303
+ #define GOOGLE_LOG_WARNING(counter) \
304
+ LogMessage(__FILE__, __LINE__, WARNING, counter, &LogMessage::SendToLog)
305
+ #define SYSLOG_WARNING(counter) \
306
+ LogMessage(__FILE__, __LINE__, WARNING, counter, \
307
+ &LogMessage::SendToSyslogAndLog)
308
+ #define GOOGLE_LOG_ERROR(counter) \
309
+ LogMessage(__FILE__, __LINE__, ERROR, counter, &LogMessage::SendToLog)
310
+ #define SYSLOG_ERROR(counter) \
311
+ LogMessage(__FILE__, __LINE__, ERROR, counter, \
312
+ &LogMessage::SendToSyslogAndLog)
313
+ #define GOOGLE_LOG_FATAL(counter) \
314
+ LogMessage(__FILE__, __LINE__, FATAL, counter, &LogMessage::SendToLog)
315
+ #define SYSLOG_FATAL(counter) \
316
+ LogMessage(__FILE__, __LINE__, FATAL, counter, \
317
+ &LogMessage::SendToSyslogAndLog)
318
+ #define GOOGLE_LOG_DFATAL(counter) \
319
+ LogMessage(__FILE__, __LINE__, DFATAL_LEVEL, counter, &LogMessage::SendToLog)
320
+ #define SYSLOG_DFATAL(counter) \
321
+ LogMessage(__FILE__, __LINE__, DFATAL_LEVEL, counter, \
322
+ &LogMessage::SendToSyslogAndLog)
323
+
324
+ #ifdef OS_WINDOWS
325
+ // A very useful logging macro to log windows errors:
326
+ #define LOG_SYSRESULT(result) \
327
+ if (FAILED(result)) { \
328
+ LPTSTR message = NULL; \
329
+ LPTSTR msg = reinterpret_cast<LPTSTR>(&message); \
330
+ DWORD message_length = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | \
331
+ FORMAT_MESSAGE_FROM_SYSTEM, \
332
+ 0, result, 0, msg, 100, NULL); \
333
+ if (message_length > 0) { \
334
+ LogMessage(__FILE__, __LINE__, ERROR, 0, \
335
+ &LogMessage::SendToLog).stream() << message; \
336
+ LocalFree(message); \
337
+ } \
338
+ }
339
+ #endif
340
+
341
+ // We use the preprocessor's merging operator, "##", so that, e.g.,
342
+ // LOG(INFO) becomes the token GOOGLE_LOG_INFO. There's some funny
343
+ // subtle difference between ostream member streaming functions (e.g.,
344
+ // ostream::operator<<(int) and ostream non-member streaming functions
345
+ // (e.g., ::operator<<(ostream&, string&): it turns out that it's
346
+ // impossible to stream something like a string directly to an unnamed
347
+ // ostream. We employ a neat hack by calling the stream() member
348
+ // function of LogMessage which seems to avoid the problem.
349
+ #define LOG(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
350
+ #define SYSLOG(severity) SYSLOG_ ## severity(0).stream()
351
+
352
+ // A convenient shorthand
353
+ #define LG LOG(INFO)
354
+
355
+ class LogSink; // defined below
356
+
357
+ // If a non-NULL sink pointer is given, we push this message to that sink.
358
+ // For LOG_TO_SINK we then do normal LOG(severity) logging as well.
359
+ // This is useful for capturing messages and passing/storing them
360
+ // somewhere more specific than the global log of the process.
361
+ // Argument types:
362
+ // LogSink* sink;
363
+ // LogSeverity severity;
364
+ // The cast is to disambiguate NULL arguments.
365
+ #define LOG_TO_SINK(sink, severity) \
366
+ LogMessage(__FILE__, __LINE__, severity, \
367
+ static_cast<LogSink*>(sink), true).stream()
368
+ #define LOG_TO_SINK_BUT_NOT_TO_LOGFILE(sink, severity) \
369
+ LogMessage(__FILE__, __LINE__, severity, \
370
+ static_cast<LogSink*>(sink), false).stream()
371
+
372
+ // If a non-NULL string pointer is given, we write this message to that string.
373
+ // We then do normal LOG(severity) logging as well.
374
+ // This is useful for capturing messages and storing them somewhere more
375
+ // specific than the global log of the process.
376
+ // Argument types:
377
+ // string* message;
378
+ // LogSeverity severity;
379
+ // The cast is to disambiguate NULL arguments.
380
+ // NOTE: LOG(severity) expands to LogMessage().stream() for the specified
381
+ // severity.
382
+ #define LOG_TO_STRING(severity, message) \
383
+ LOG_TO_STRING_##severity(static_cast<string*>(message)).stream()
384
+
385
+ // If a non-NULL pointer is given, we push the message onto the end
386
+ // of a vector of strings; otherwise, we report it with LOG(severity).
387
+ // This is handy for capturing messages and perhaps passing them back
388
+ // to the caller, rather than reporting them immediately.
389
+ // Argument types:
390
+ // LogSeverity severity;
391
+ // vector<string> *outvec;
392
+ // The cast is to disambiguate NULL arguments.
393
+ #define LOG_STRING(severity, outvec) \
394
+ LOG_TO_STRING_##severity(static_cast<vector<string>*>(outvec)).stream()
395
+
396
+ #define LOG_IF(severity, condition) \
397
+ !(condition) ? (void) 0 : LogMessageVoidify() & LOG(severity)
398
+ #define SYSLOG_IF(severity, condition) \
399
+ !(condition) ? (void) 0 : LogMessageVoidify() & SYSLOG(severity)
400
+
401
+ #define LOG_ASSERT(condition) \
402
+ LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
403
+ #define SYSLOG_ASSERT(condition) \
404
+ SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition
405
+
406
+ // CHECK dies with a fatal error if condition is not true. It is *not*
407
+ // controlled by NDEBUG, so the check will be executed regardless of
408
+ // compilation mode. Therefore, it is safe to do things like:
409
+ // CHECK(fp->Write(x) == 4)
410
+ #define CHECK(condition) \
411
+ LOG_IF(FATAL, PREDICT_FALSE(!(condition))) \
412
+ << "Check failed: " #condition " "
413
+
414
+ // QCHECK is a quiet version of CHECK. It has all of the same properties,
415
+ // except that when it dies it simply prints out this message and doesn't
416
+ // dump a giant stack trace, etc. This is good for tests like sanity-checking
417
+ // user inputs, where your own failure message is really the only thing you
418
+ // need or want to display.
419
+ #define QCHECK(condition) \
420
+ LOG_IF(QFATAL, PREDICT_FALSE(!(condition))) \
421
+ << "Check failed: " #condition " "
422
+
423
+ // A container for a string pointer which can be evaluated to a bool -
424
+ // true iff the pointer is NULL.
425
+ struct CheckOpString {
426
+ CheckOpString(string* str) : str_(str) { }
427
+ // No destructor: if str_ is non-NULL, we're about to LOG(FATAL),
428
+ // so there's no point in cleaning up str_.
429
+ operator bool() const { return PREDICT_FALSE(str_ != NULL); }
430
+ string* str_;
431
+ };
432
+
433
+ // Function is overloaded for integral types to allow static const
434
+ // integrals declared in classes and not defined to be used as arguments to
435
+ // CHECK* macros. It's not encouraged though.
436
+ template <class T>
437
+ inline const T& GetReferenceableValue(const T& t) { return t; }
438
+ inline char GetReferenceableValue(char t) { return t; }
439
+ inline unsigned char GetReferenceableValue(unsigned char t) { return t; }
440
+ inline signed char GetReferenceableValue(signed char t) { return t; }
441
+ inline short GetReferenceableValue(short t) { return t; }
442
+ inline unsigned short GetReferenceableValue(unsigned short t) { return t; }
443
+ inline int GetReferenceableValue(int t) { return t; }
444
+ inline unsigned int GetReferenceableValue(unsigned int t) { return t; }
445
+ inline long GetReferenceableValue(long t) { return t; }
446
+ inline unsigned long GetReferenceableValue(unsigned long t) { return t; }
447
+ inline long long GetReferenceableValue(long long t) { return t; }
448
+ inline unsigned long long GetReferenceableValue(unsigned long long t) {
449
+ return t;
450
+ }
451
+
452
+ // Build the error message string.
453
+ template<class t1, class t2>
454
+ string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
455
+ strstream ss;
456
+ ss << names << " (" << v1 << " vs. " << v2 << ")";
457
+ return new string(ss.str(), ss.pcount());
458
+ }
459
+
460
+ // Helper functions for CHECK_OP macro.
461
+ // The (int, int) specialization works around the issue that the compiler
462
+ // will not instantiate the template version of the function on values of
463
+ // unnamed enum type - see comment below.
464
+ #define DEFINE_CHECK_OP_IMPL(name, op) \
465
+ template <class t1, class t2> \
466
+ inline string* Check##name##Impl(const t1& v1, const t2& v2, \
467
+ const char* names) { \
468
+ if (v1 op v2) return NULL; \
469
+ else return MakeCheckOpString(v1, v2, names); \
470
+ } \
471
+ inline string* Check##name##Impl(int v1, int v2, const char* names) { \
472
+ return Check##name##Impl<int, int>(v1, v2, names); \
473
+ }
474
+
475
+ // Use _EQ, _NE, _LE, etc. in case the file including base/logging.h
476
+ // provides its own #defines for the simpler names EQ, NE, LE, etc.
477
+ // This happens if, for example, those are used as token names in a
478
+ // yacc grammar.
479
+ DEFINE_CHECK_OP_IMPL(_EQ, ==)
480
+ DEFINE_CHECK_OP_IMPL(_NE, !=)
481
+ DEFINE_CHECK_OP_IMPL(_LE, <=)
482
+ DEFINE_CHECK_OP_IMPL(_LT, < )
483
+ DEFINE_CHECK_OP_IMPL(_GE, >=)
484
+ DEFINE_CHECK_OP_IMPL(_GT, > )
485
+ #undef DEFINE_CHECK_OP_IMPL
486
+
487
+ // Helper macro for binary operators.
488
+ // Don't use this macro directly in your code, use CHECK_EQ et al below.
489
+
490
+ #if defined(STATIC_ANALYSIS)
491
+ // Only for static analysis tool to know that it is equivalent to assert
492
+ #define CHECK_OP_LOG(name, op, val1, val2, log) CHECK((val1) op (val2))
493
+ #elif !defined(NDEBUG)
494
+ // In debug mode, avoid constructing CheckOpStrings if possible,
495
+ // to reduce the overhead of CHECK statments by 2x.
496
+ // Real DCHECK-heavy tests have seen 1.5x speedups.
497
+
498
+ // The meaning of "string" might be different between now and
499
+ // when this macro gets invoked (e.g., if someone is experimenting
500
+ // with other string implementations that get defined after this
501
+ // file is included). Save the current meaning now and use it
502
+ // in the macro.
503
+ typedef string _Check_string;
504
+ #define CHECK_OP_LOG(name, op, val1, val2, log) \
505
+ while (_Check_string* _result = \
506
+ Check##name##Impl(GetReferenceableValue(val1), \
507
+ GetReferenceableValue(val2), \
508
+ #val1 " " #op " " #val2)) \
509
+ log(__FILE__, __LINE__, CheckOpString(_result)).stream()
510
+ #else
511
+ // In optimized mode, use CheckOpString to hint to compiler that
512
+ // the while condition is unlikely.
513
+ #define CHECK_OP_LOG(name, op, val1, val2, log) \
514
+ while (CheckOpString _result = \
515
+ Check##name##Impl(GetReferenceableValue(val1), \
516
+ GetReferenceableValue(val2), \
517
+ #val1 " " #op " " #val2)) \
518
+ log(__FILE__, __LINE__, _result).stream()
519
+ #endif // STATIC_ANALYSIS, !NDEBUG
520
+
521
+ #if STRIP_LOG <= 3
522
+ #define CHECK_OP(name, op, val1, val2) \
523
+ CHECK_OP_LOG(name, op, val1, val2, LogMessageFatal)
524
+ #else
525
+ #define CHECK_OP(name, op, val1, val2) \
526
+ CHECK_OP_LOG(name, op, val1, val2, NullStreamFatal)
527
+ #endif // STRIP_LOG <= 3
528
+ #define QCHECK_OP(name, op, val1, val2) \
529
+ CHECK_OP_LOG(name, op, val1, val2, LogMessageQuietlyFatal)
530
+
531
+ // Equality/Inequality checks - compare two values, and log a FATAL message
532
+ // including the two values when the result is not as expected. The values
533
+ // must have operator<<(ostream, ...) defined.
534
+ //
535
+ // You may append to the error message like so:
536
+ // CHECK_NE(1, 2) << ": The world must be ending!";
537
+ //
538
+ // We are very careful to ensure that each argument is evaluated exactly
539
+ // once, and that anything which is legal to pass as a function argument is
540
+ // legal here. In particular, the arguments may be temporary expressions
541
+ // which will end up being destroyed at the end of the apparent statement,
542
+ // for example:
543
+ // CHECK_EQ(string("abc")[1], 'b');
544
+ //
545
+ // WARNING: These don't compile correctly if one of the arguments is a pointer
546
+ // and the other is NULL. To work around this, simply static_cast NULL to the
547
+ // type of the desired pointer.
548
+
549
+ #define CHECK_EQ(val1, val2) CHECK_OP(_EQ, ==, val1, val2)
550
+ #define CHECK_NE(val1, val2) CHECK_OP(_NE, !=, val1, val2)
551
+ #define CHECK_LE(val1, val2) CHECK_OP(_LE, <=, val1, val2)
552
+ #define CHECK_LT(val1, val2) CHECK_OP(_LT, < , val1, val2)
553
+ #define CHECK_GE(val1, val2) CHECK_OP(_GE, >=, val1, val2)
554
+ #define CHECK_GT(val1, val2) CHECK_OP(_GT, > , val1, val2)
555
+
556
+ #define QCHECK_EQ(val1, val2) QCHECK_OP(_EQ, ==, val1, val2)
557
+ #define QCHECK_NE(val1, val2) QCHECK_OP(_NE, !=, val1, val2)
558
+ #define QCHECK_LE(val1, val2) QCHECK_OP(_LE, <=, val1, val2)
559
+ #define QCHECK_LT(val1, val2) QCHECK_OP(_LT, < , val1, val2)
560
+ #define QCHECK_GE(val1, val2) QCHECK_OP(_GE, >=, val1, val2)
561
+ #define QCHECK_GT(val1, val2) QCHECK_OP(_GT, > , val1, val2)
562
+
563
+
564
+ // Check that the input is non NULL. This very useful in constructor
565
+ // initializer lists.
566
+
567
+ #define CHECK_NOTNULL(val) \
568
+ CheckNotNull(__FILE__, __LINE__, "'" #val "' Must be non NULL", (val))
569
+
570
+ // Helper functions for string comparisons.
571
+ // To avoid bloat, the definitions are in logging.cc.
572
+ #define DECLARE_CHECK_STROP_IMPL(func, expected) \
573
+ string* Check##func##expected##Impl(const char* s1, const char* s2, \
574
+ const char* names);
575
+ DECLARE_CHECK_STROP_IMPL(strcmp, true)
576
+ DECLARE_CHECK_STROP_IMPL(strcmp, false)
577
+ DECLARE_CHECK_STROP_IMPL(strcasecmp, true)
578
+ DECLARE_CHECK_STROP_IMPL(strcasecmp, false)
579
+ #undef DECLARE_CHECK_STROP_IMPL
580
+
581
+ // Helper macro for string comparisons.
582
+ // Don't use this macro directly in your code, use CHECK_STREQ et al below.
583
+ #define CHECK_STROP(func, op, expected, s1, s2) \
584
+ while (CheckOpString _result = \
585
+ Check##func##expected##Impl((s1), (s2), \
586
+ #s1 " " #op " " #s2)) \
587
+ LOG(FATAL) << *_result.str_
588
+ #define QCHECK_STROP(func, op, expected, s1, s2) \
589
+ while (CheckOpString _result = \
590
+ Check##func##expected##Impl((s1), (s2), \
591
+ #s1 " " #op " " #s2)) \
592
+ LOG(QFATAL) << *_result.str_
593
+
594
+
595
+ // String (char*) equality/inequality checks.
596
+ // CASE versions are case-insensitive.
597
+ //
598
+ // Note that "s1" and "s2" may be temporary strings which are destroyed
599
+ // by the compiler at the end of the current "full expression"
600
+ // (e.g. CHECK_STREQ(Foo().c_str(), Bar().c_str())).
601
+
602
+ #define CHECK_STREQ(s1, s2) CHECK_STROP(strcmp, ==, true, s1, s2)
603
+ #define CHECK_STRNE(s1, s2) CHECK_STROP(strcmp, !=, false, s1, s2)
604
+ #define CHECK_STRCASEEQ(s1, s2) CHECK_STROP(strcasecmp, ==, true, s1, s2)
605
+ #define CHECK_STRCASENE(s1, s2) CHECK_STROP(strcasecmp, !=, false, s1, s2)
606
+
607
+ #define CHECK_INDEX(I,A) CHECK(I < (sizeof(A)/sizeof(A[0])))
608
+ #define CHECK_BOUND(B,A) CHECK(B <= (sizeof(A)/sizeof(A[0])))
609
+
610
+ #define QCHECK_STREQ(s1, s2) QCHECK_STROP(strcmp, ==, true, s1, s2)
611
+ #define QCHECK_STRNE(s1, s2) QCHECK_STROP(strcmp, !=, false, s1, s2)
612
+ #define QCHECK_STRCASEEQ(s1, s2) QCHECK_STROP(strcasecmp, ==, true, s1, s2)
613
+ #define QCHECK_STRCASENE(s1, s2) QCHECK_STROP(strcasecmp, !=, false, s1, s2)
614
+
615
+ #define QCHECK_INDEX(I,A) QCHECK(I < (sizeof(A)/sizeof(A[0])))
616
+ #define QCHECK_BOUND(B,A) QCHECK(B <= (sizeof(A)/sizeof(A[0])))
617
+
618
+ // Likely to be deprecated; instead use
619
+ // CHECK(MathUtil::NearByMargin(x, y))
620
+ // (or another similar function from util/math/mathutil.h).
621
+ #define CHECK_DOUBLE_EQ(val1, val2) \
622
+ do { \
623
+ CHECK_LE((val1), (val2)+0.000000000000001L); \
624
+ CHECK_GE((val1), (val2)-0.000000000000001L); \
625
+ } while (0)
626
+
627
+ // Likely to be deprecated; instead use
628
+ // CHECK(MathUtil::WithinMargin(x, y, margin))
629
+ // (or another similar function from util/math/mathutil.h).
630
+ #define CHECK_NEAR(val1, val2, margin) \
631
+ do { \
632
+ CHECK_LE((val1), (val2)+(margin)); \
633
+ CHECK_GE((val1), (val2)-(margin)); \
634
+ } while (0)
635
+
636
+ // perror()..googly style!
637
+ //
638
+ // PLOG() and PLOG_IF() and PCHECK() behave exactly like their LOG* and
639
+ // CHECK equivalents with the addition that they postpend a description
640
+ // of the current state of errno to their output lines.
641
+
642
+ #define PLOG(severity) GOOGLE_PLOG(severity, 0).stream()
643
+
644
+ #define GOOGLE_PLOG(severity, counter) \
645
+ ErrnoLogMessage(__FILE__, __LINE__, severity, counter, \
646
+ &LogMessage::SendToLog)
647
+
648
+ #define PLOG_IF(severity, condition) \
649
+ !(condition) ? (void) 0 : LogMessageVoidify() & PLOG(severity)
650
+
651
+ // A CHECK() macro that postpends errno if the condition is false. E.g.
652
+ //
653
+ // if (poll(fds, nfds, timeout) == -1) { PCHECK(errno == EINTR); ... }
654
+ #define PCHECK(condition) \
655
+ PLOG_IF(FATAL, PREDICT_FALSE(!(condition))) \
656
+ << "Check failed: " #condition " "
657
+
658
+ // A CHECK() macro that lets you assert the success of a function that
659
+ // returns -1 and sets errno in case of an error. E.g.
660
+ //
661
+ // CHECK_ERR(mkdir(path, 0700));
662
+ //
663
+ // or
664
+ //
665
+ // int fd = open(filename, flags); CHECK_ERR(fd) << ": open " << filename;
666
+ #define CHECK_ERR(invocation) \
667
+ PLOG_IF(FATAL, PREDICT_FALSE((invocation) == -1)) << #invocation
668
+
669
+ // Use macro expansion to create, for each use of LOG_EVERY_N(), static
670
+ // variables with the __LINE__ expansion as part of the variable name.
671
+ #define LOG_EVERY_N_VARNAME(base, line) LOG_EVERY_N_VARNAME_CONCAT(base, line)
672
+ #define LOG_EVERY_N_VARNAME_CONCAT(base, line) base ## line
673
+
674
+ #define LOG_OCCURRENCES LOG_EVERY_N_VARNAME(occurrences_, __LINE__)
675
+ #define LOG_OCCURRENCES_MOD_N LOG_EVERY_N_VARNAME(occurrences_mod_n_, __LINE__)
676
+
677
+ #define SOME_KIND_OF_LOG_EVERY_N(severity, n, what_to_do) \
678
+ static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
679
+ ++LOG_OCCURRENCES; \
680
+ if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
681
+ if (LOG_OCCURRENCES_MOD_N == 1) \
682
+ LogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \
683
+ &what_to_do).stream()
684
+
685
+ #define SOME_KIND_OF_LOG_IF_EVERY_N(severity, condition, n, what_to_do) \
686
+ static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
687
+ ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES, "logging"); \
688
+ ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES_MOD_N, "logging"); \
689
+ ++LOG_OCCURRENCES; \
690
+ if (condition && \
691
+ ((LOG_OCCURRENCES_MOD_N=(LOG_OCCURRENCES_MOD_N + 1) % n) == (1 % n))) \
692
+ LogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \
693
+ &what_to_do).stream()
694
+
695
+ #define SOME_KIND_OF_PLOG_EVERY_N(severity, n, what_to_do) \
696
+ static int LOG_OCCURRENCES = 0, LOG_OCCURRENCES_MOD_N = 0; \
697
+ ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES, "logging"); \
698
+ ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES_MOD_N, "logging"); \
699
+ ++LOG_OCCURRENCES; \
700
+ if (++LOG_OCCURRENCES_MOD_N > n) LOG_OCCURRENCES_MOD_N -= n; \
701
+ if (LOG_OCCURRENCES_MOD_N == 1) \
702
+ ErrnoLogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \
703
+ &what_to_do).stream()
704
+
705
+ #define SOME_KIND_OF_LOG_FIRST_N(severity, n, what_to_do) \
706
+ static int LOG_OCCURRENCES = 0; \
707
+ ANNOTATE_BENIGN_RACE(&LOG_OCCURRENCES, "logging"); \
708
+ if (LOG_OCCURRENCES <= n) \
709
+ ++LOG_OCCURRENCES; \
710
+ if (LOG_OCCURRENCES <= n) \
711
+ LogMessage(__FILE__, __LINE__, severity, LOG_OCCURRENCES, \
712
+ &what_to_do).stream()
713
+
714
+ #define LOG_EVERY_N(severity, n) \
715
+ COMPILE_ASSERT(severity < NUM_SEVERITIES, \
716
+ INVALID_REQUESTED_LOG_SEVERITY); \
717
+ SOME_KIND_OF_LOG_EVERY_N(severity, (n), LogMessage::SendToLog)
718
+
719
+ #define SYSLOG_EVERY_N(severity, n) \
720
+ SOME_KIND_OF_LOG_EVERY_N(severity, (n), LogMessage::SendToSyslogAndLog)
721
+
722
+ #define PLOG_EVERY_N(severity, n) \
723
+ SOME_KIND_OF_PLOG_EVERY_N(severity, (n), LogMessage::SendToLog)
724
+
725
+ #define LOG_FIRST_N(severity, n) \
726
+ SOME_KIND_OF_LOG_FIRST_N(severity, (n), LogMessage::SendToLog)
727
+
728
+ #define LOG_IF_EVERY_N(severity, condition, n) \
729
+ SOME_KIND_OF_LOG_IF_EVERY_N(severity, (condition), (n), LogMessage::SendToLog)
730
+
731
+ // We want the special COUNTER value available for LOG_EVERY_X()'ed messages
732
+ enum PRIVATE_Counter {COUNTER};
733
+
734
+
735
+ // Plus some debug-logging macros that get compiled to nothing for production
736
+
737
+ #ifndef NDEBUG
738
+
739
+ #define DLOG(severity) LOG(severity)
740
+ #define DVLOG(verboselevel) VLOG(verboselevel)
741
+ #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
742
+ #define DLOG_EVERY_N(severity, n) LOG_EVERY_N(severity, n)
743
+ #define DLOG_IF_EVERY_N(severity, condition, n) \
744
+ LOG_IF_EVERY_N(severity, condition, n)
745
+ #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
746
+
747
+ // debug-only checking. not executed in NDEBUG mode.
748
+ #define DCHECK(condition) CHECK(condition)
749
+ #define DCHECK_EQ(val1, val2) CHECK_EQ(val1, val2)
750
+ #define DCHECK_NE(val1, val2) CHECK_NE(val1, val2)
751
+ #define DCHECK_LE(val1, val2) CHECK_LE(val1, val2)
752
+ #define DCHECK_LT(val1, val2) CHECK_LT(val1, val2)
753
+ #define DCHECK_GE(val1, val2) CHECK_GE(val1, val2)
754
+ #define DCHECK_GT(val1, val2) CHECK_GT(val1, val2)
755
+ #define DCHECK_STREQ(str1, str2) CHECK_STREQ(str1, str2)
756
+ #define DCHECK_STRCASEEQ(str1, str2) CHECK_STRCASEEQ(str1, str2)
757
+ #define DCHECK_STRNE(str1, str2) CHECK_STRNE(str1, str2)
758
+ #define DCHECK_STRCASENE(str1, str2) CHECK_STRCASENE(str1, str2)
759
+
760
+ #else // NDEBUG
761
+
762
+ #define DLOG(severity) \
763
+ true ? (void) 0 : LogMessageVoidify() & LOG(severity)
764
+
765
+ #define DVLOG(verboselevel) \
766
+ (true || !VLOG_IS_ON(verboselevel)) ?\
767
+ (void) 0 : LogMessageVoidify() & LOG(INFO)
768
+
769
+ #define DLOG_IF(severity, condition) \
770
+ (true || !(condition)) ? (void) 0 : LogMessageVoidify() & LOG(severity)
771
+
772
+ #define DLOG_EVERY_N(severity, n) \
773
+ true ? (void) 0 : LogMessageVoidify() & LOG(severity)
774
+
775
+ #define DLOG_IF_EVERY_N(severity, condition, n) \
776
+ (true || !(condition))? (void) 0 : LogMessageVoidify() & LOG(severity)
777
+
778
+ #define DLOG_ASSERT(condition) \
779
+ true ? (void) 0 : LOG_ASSERT(condition)
780
+
781
+ #define DCHECK(condition) \
782
+ while (false) \
783
+ CHECK(condition)
784
+
785
+ #define DCHECK_EQ(val1, val2) \
786
+ while (false) \
787
+ CHECK_EQ(val1, val2)
788
+
789
+ #define DCHECK_NE(val1, val2) \
790
+ while (false) \
791
+ CHECK_NE(val1, val2)
792
+
793
+ #define DCHECK_LE(val1, val2) \
794
+ while (false) \
795
+ CHECK_LE(val1, val2)
796
+
797
+ #define DCHECK_LT(val1, val2) \
798
+ while (false) \
799
+ CHECK_LT(val1, val2)
800
+
801
+ #define DCHECK_GE(val1, val2) \
802
+ while (false) \
803
+ CHECK_GE(val1, val2)
804
+
805
+ #define DCHECK_GT(val1, val2) \
806
+ while (false) \
807
+ CHECK_GT(val1, val2)
808
+
809
+ #define DCHECK_STREQ(str1, str2) \
810
+ while (false) \
811
+ CHECK_STREQ(str1, str2)
812
+
813
+ #define DCHECK_STRCASEEQ(str1, str2) \
814
+ while (false) \
815
+ CHECK_STRCASEEQ(str1, str2)
816
+
817
+ #define DCHECK_STRNE(str1, str2) \
818
+ while (false) \
819
+ CHECK_STRNE(str1, str2)
820
+
821
+ #define DCHECK_STRCASENE(str1, str2) \
822
+ while (false) \
823
+ CHECK_STRCASENE(str1, str2)
824
+
825
+
826
+ #endif // NDEBUG
827
+
828
+ // Log only in verbose mode.
829
+
830
+ #define VLOG(verboselevel) LOG_IF(INFO, VLOG_IS_ON(verboselevel))
831
+
832
+ #define VLOG_IF(verboselevel, condition) \
833
+ LOG_IF(INFO, (condition) && VLOG_IS_ON(verboselevel))
834
+
835
+ #define VLOG_EVERY_N(verboselevel, n) \
836
+ LOG_IF_EVERY_N(INFO, VLOG_IS_ON(verboselevel), n)
837
+
838
+ #define VLOG_IF_EVERY_N(verboselevel, condition, n) \
839
+ LOG_IF_EVERY_N(INFO, (condition) && VLOG_IS_ON(verboselevel), n)
840
+
841
+
842
+ // [MLOG is OBSOLETE - use the more convenient VLOG(n) macros]
843
+ // Log only when a module-specific value (MODULE_FLAG) has a specific
844
+ // value. MODULE_FLAG must be a macro that evaluates to the name of
845
+ // the flag that you wish to use. You should '#define MODULE_FLAG
846
+ // <variable name>' before using this macro. (For example:
847
+ // #define MODULE_FLAG FLAGS_dnsverbose
848
+ #define MLOG(verboselevel) LOG_IF(INFO, MODULE_FLAG >= (verboselevel))
849
+
850
+ // Redefine the standard assert to use our nice log files
851
+ #undef assert
852
+ #define assert(x) DLOG_ASSERT(x)
853
+
854
+ //
855
+ // This class more or less represents a particular log message. You
856
+ // create an instance of LogMessage and then stream stuff to it.
857
+ // When you finish streaming to it, ~LogMessage is called and the
858
+ // full message gets streamed to the appropriate destination.
859
+ //
860
+ // You shouldn't actually use LogMessage's constructor to log things,
861
+ // though. You should use the LOG() macro (and variants thereof)
862
+ // above.
863
+ class LogMessage {
864
+ public:
865
+ enum {
866
+ // Passing kNoLogPrefix for the line number disables the
867
+ // log-message prefix. Useful for using the LogMessage
868
+ // infrastructure as a printing utility. See also the --log_prefix
869
+ // flag for controlling the log-message prefix on an
870
+ // application-wide basis.
871
+ kNoLogPrefix = -1
872
+ };
873
+
874
+ class LogStream : public ostrstream {
875
+ public:
876
+ LogStream(char *buf, int len, int ctr)
877
+ : ostrstream(buf, len),
878
+ ctr_(ctr) {
879
+ self_ = this;
880
+ }
881
+
882
+ int ctr() const { return ctr_; }
883
+ void set_ctr(int ctr) { ctr_ = ctr; }
884
+ LogStream* self() const { return self_; }
885
+
886
+ private:
887
+ int ctr_; // Counter hack (for the LOG_EVERY_X() macro)
888
+ LogStream *self_; // Consistency check hack
889
+ };
890
+
891
+ public:
892
+ // icc 8 requires this typedef to avoid an internal compiler error.
893
+ typedef void (LogMessage::*SendMethod)();
894
+
895
+ LogMessage(const char* file, int line, LogSeverity severity, int ctr,
896
+ SendMethod send_method);
897
+
898
+ // Two special constructors that generate reduced amounts of code at
899
+ // LOG call sites for common cases.
900
+
901
+ // Used for LOG(INFO): Implied are:
902
+ // severity = INFO, ctr = 0, send_method = &LogMessage::SendToLog.
903
+ //
904
+ // Using this constructor instead of the more complex constructor above
905
+ // saves 19 bytes per call site.
906
+ LogMessage(const char* file, int line);
907
+
908
+ // Used for LOG(severity) where severity != INFO. Implied
909
+ // are: ctr = 0, send_method = &LogMessage::SendToLog
910
+ //
911
+ // Using this constructor instead of the more complex constructor above
912
+ // saves 17 bytes per call site.
913
+ LogMessage(const char* file, int line, LogSeverity severity);
914
+
915
+ // Constructor to log this message to a specified sink (if not NULL).
916
+ // Implied are: ctr = 0, send_method = &LogMessage::SendToSinkAndLog if
917
+ // also_send_to_log is true, send_method = &LogMessage::SendToSink otherwise.
918
+ LogMessage(const char* file, int line, LogSeverity severity, LogSink* sink,
919
+ bool also_send_to_log);
920
+
921
+ // Constructor where we also give a vector<string> pointer
922
+ // for storing the messages (if the pointer is not NULL).
923
+ // Implied are: ctr = 0, send_method = &LogMessage::SaveOrSendToLog.
924
+ LogMessage(const char* file, int line, LogSeverity severity,
925
+ vector<string>* outvec);
926
+
927
+ // Constructor where we also give a string pointer for storing the
928
+ // message (if the pointer is not NULL). Implied are: ctr = 0,
929
+ // send_method = &LogMessage::WriteToStringAndLog.
930
+ LogMessage(const char* file, int line, LogSeverity severity,
931
+ string* message);
932
+
933
+ // A special constructor used for check failures
934
+ LogMessage(const char* file, int line, const CheckOpString& result);
935
+
936
+ ~LogMessage();
937
+
938
+ // Flush a buffered message to the sink set in the constructor. Always
939
+ // called by the destructor, it may also be called from elsewhere if
940
+ // needed. Only the first call is actioned; any later ones are ignored.
941
+ void Flush();
942
+
943
+ // An arbitrary limit on the length of a single log message. This
944
+ // is so that streaming can be done more efficiently.
945
+ static const size_t kMaxLogMessageLen;
946
+
947
+ // Theses should not be called directly outside of logging.*,
948
+ // only passed as SendMethod arguments to other LogMessage methods:
949
+ void SendToLog(); // Actually dispatch to the logs
950
+ void SendToSyslogAndLog(); // Actually dispatch to syslog and the logs
951
+
952
+ // Call abort() or similar to perform LOG(FATAL) crash.
953
+ // Writes current stack trace to stderr.
954
+ static void Fail() ATTRIBUTE_NORETURN;
955
+
956
+ // Same as Fail(), but without writing out the stack trace.
957
+ // It is assumed that the caller has already generated and
958
+ // written the trace as appropriate.
959
+ static void FailWithoutStackTrace() ATTRIBUTE_NORETURN;
960
+
961
+ // Similar to FailWithoutStackTrace(), but without abort()ing.
962
+ // Terminates the process with error exit code.
963
+ static void FailQuietly() ATTRIBUTE_NORETURN;
964
+
965
+ ostream& stream() { return *(data_->stream_); }
966
+
967
+ int preserved_errno() const { return data_->preserved_errno_; }
968
+
969
+ // Must be called without the log_mutex held. (L < log_mutex)
970
+ static int64 num_messages(int severity);
971
+
972
+ private:
973
+ // Fully internal SendMethod cases:
974
+ void SendToSinkAndLog(); // Send to sink if provided and dispatch to the logs
975
+ void SendToSink(); // Send to sink if provided, do nothing otherwise.
976
+
977
+ // Write to string if provided and dispatch to the logs.
978
+ void WriteToStringAndLog();
979
+
980
+ void SaveOrSendToLog(); // Save to stringvec if provided, else to logs
981
+
982
+ void Init(const char* file, int line, LogSeverity severity,
983
+ void (LogMessage::*send_method)());
984
+
985
+ // Used to fill in crash information during LOG(FATAL) failures.
986
+ void RecordCrashReason(base::CrashReason* reason);
987
+
988
+ // Counts of messages sent at each priority:
989
+ static int64 num_messages_[NUM_SEVERITIES]; // under log_mutex
990
+
991
+ // We keep the data in a separate struct so that each instance of
992
+ // LogMessage uses less stack space.
993
+ struct LogMessageData {
994
+ LogMessageData() {};
995
+
996
+ int preserved_errno_; // errno at Init() time
997
+ scoped_array<char> buf_; // buffer space for non FATAL messages
998
+ char* message_text_; // Complete message text
999
+ scoped_ptr<LogStream> stream_alloc_;
1000
+ LogStream* stream_;
1001
+ char severity_; // level of LogMessage (ex. I, W, E, F)
1002
+ int line_; // line number of file that called LOG
1003
+ void (LogMessage::*send_method_)(); // Call this in destructor to send
1004
+ union { // At most one of these is used: union to keep the size low.
1005
+ LogSink* sink_; // NULL or sink to send message to
1006
+ vector<string>* outvec_; // NULL or vector to push message onto
1007
+ string* message_; // NULL or string to write message into
1008
+ };
1009
+ time_t timestamp_; // Time of creation of LogMessage
1010
+ struct tm tm_time_; // Time of creation of LogMessage
1011
+ size_t num_prefix_chars_; // # of chars of prefix in this message
1012
+ size_t num_chars_to_log_; // # of chars of msg to send to log
1013
+ size_t num_chars_to_syslog_; // # of chars of msg to send to syslog
1014
+ const char* basename_; // basename of file that called LOG
1015
+ const char* fullname_; // fullname of file that called LOG
1016
+ bool has_been_flushed_; // false => data has not been flushed
1017
+ bool first_fatal_; // true => this was first fatal msg
1018
+
1019
+ private:
1020
+ DISALLOW_EVIL_CONSTRUCTORS(LogMessageData);
1021
+ };
1022
+
1023
+ static LogMessageData fatal_msg_data_exclusive_;
1024
+ static LogMessageData fatal_msg_data_shared_;
1025
+
1026
+ scoped_ptr<LogMessageData> allocated_;
1027
+ LogMessageData* data_;
1028
+
1029
+ friend class LogDestination;
1030
+
1031
+ DISALLOW_EVIL_CONSTRUCTORS(LogMessage);
1032
+
1033
+ protected:
1034
+ // Default false; if true, all failures should be as quiet as possible. This
1035
+ // is stored in LogMessage, rather than LogMessageData, because all FATAL-
1036
+ // level handlers share the same LogMessageData for signal safety reasons.
1037
+ bool fail_quietly_;
1038
+ };
1039
+
1040
+ // This class happens to be thread-hostile because all instances share
1041
+ // a single data buffer, but since it can only be created just before
1042
+ // the process dies, we don't worry so much.
1043
+ class LogMessageFatal : public LogMessage {
1044
+ public:
1045
+ LogMessageFatal(const char* file, int line);
1046
+ LogMessageFatal(const char* file, int line, const CheckOpString& result);
1047
+ ~LogMessageFatal() ATTRIBUTE_NORETURN;
1048
+ };
1049
+
1050
+ class LogMessageQuietlyFatal : public LogMessage {
1051
+ public:
1052
+ LogMessageQuietlyFatal(const char* file, int line);
1053
+ LogMessageQuietlyFatal(const char* file, int line,
1054
+ const CheckOpString& result);
1055
+ ~LogMessageQuietlyFatal() ATTRIBUTE_NORETURN;
1056
+ };
1057
+
1058
+ // A non-macro interface to the log facility; (useful
1059
+ // when the logging level is not a compile-time constant).
1060
+ inline void LogAtLevel(int const severity, string const &msg) {
1061
+ LogMessage(__FILE__, __LINE__, severity).stream() << msg;
1062
+ }
1063
+
1064
+ // A macro alternative of LogAtLevel. New code may want to use this
1065
+ // version since there are two advantages: 1. this version outputs the
1066
+ // file name and the line number where this macro is put like other
1067
+ // LOG macros, 2. this macro can be used as C++ stream.
1068
+ #define LOG_AT_LEVEL(severity) LogMessage(__FILE__, __LINE__, severity).stream()
1069
+
1070
+ // Helpers for CHECK_NOTNULL(). Two are necessary to support both raw pointers
1071
+ // and smart pointers.
1072
+ template <typename T>
1073
+ T* CheckNotNull(const char *file, int line, const char *names, T* t) {
1074
+ return CheckNotNullCommon(file, line, names, t);
1075
+ }
1076
+
1077
+ template <typename T>
1078
+ T& CheckNotNull(const char *file, int line, const char *names, T& t) {
1079
+ return CheckNotNullCommon(file, line, names, t);
1080
+ }
1081
+
1082
+ template <typename T>
1083
+ T& CheckNotNullCommon(const char *file, int line, const char *names, T& t) {
1084
+ if (t == NULL) {
1085
+ LogMessageFatal(file, line, new string(names));
1086
+ }
1087
+ return t;
1088
+ }
1089
+
1090
+ // Allow folks to put a counter in the LOG_EVERY_X()'ed messages. This
1091
+ // only works if ostream is a LogStream. If the ostream is not a
1092
+ // LogStream you'll get an assert saying as much at runtime.
1093
+ ostream& operator<<(ostream &os, const PRIVATE_Counter&);
1094
+
1095
+
1096
+ // We need to be able to stream DocIds. But if DocIds are the same as
1097
+ // a built-in type, don't try to redefine things that are already
1098
+ // defined!
1099
+ #ifndef NDEBUG
1100
+ inline ostream& operator<<(ostream& o, const DocId& d) {
1101
+ return (o << DocidForPrintf(d));
1102
+ }
1103
+
1104
+ inline ostream& operator<<(ostream& o, const DocId32Bit& d) {
1105
+ return (o << Docid32BitForPrintf(d));
1106
+ }
1107
+ #endif // NDEBUG
1108
+
1109
+
1110
+ // Derived class for PLOG*() above.
1111
+ class ErrnoLogMessage : public LogMessage {
1112
+ public:
1113
+
1114
+ ErrnoLogMessage(const char* file, int line, LogSeverity severity, int ctr,
1115
+ void (LogMessage::*send_method)());
1116
+
1117
+ // Postpends ": strerror(errno) [errno]".
1118
+ ~ErrnoLogMessage();
1119
+
1120
+ private:
1121
+
1122
+ DISALLOW_EVIL_CONSTRUCTORS(ErrnoLogMessage);
1123
+ };
1124
+
1125
+
1126
+ // This class is used to explicitly ignore values in the conditional
1127
+ // logging macros. This avoids compiler warnings like "value computed
1128
+ // is not used" and "statement has no effect".
1129
+
1130
+ class LogMessageVoidify {
1131
+ public:
1132
+ LogMessageVoidify() { }
1133
+ // This has to be an operator with a precedence lower than << but
1134
+ // higher than ?:
1135
+ void operator&(ostream&) { }
1136
+ };
1137
+
1138
+
1139
+ // Flushes all log files that contains messages that are at least of
1140
+ // the specified severity level. Thread-safe.
1141
+ void FlushLogFiles(LogSeverity min_severity);
1142
+
1143
+ // Flushes all log files that contains messages that are at least of
1144
+ // the specified severity level. Thread-hostile because it ignores
1145
+ // locking -- used for catastrophic failures.
1146
+ void FlushLogFilesUnsafe(LogSeverity min_severity);
1147
+
1148
+ //
1149
+ // Set the destination to which a particular severity level of log
1150
+ // messages is sent. If base_filename is "", it means "don't log this
1151
+ // severity". Thread-safe.
1152
+ //
1153
+ void SetLogDestination(LogSeverity severity, const char* base_filename);
1154
+
1155
+ //
1156
+ // Set the basename of the symlink to the latest log file at a given
1157
+ // severity. If symlink_basename is empty, do not make a symlink. If
1158
+ // you don't call this function, the symlink basename is the
1159
+ // invocation name of the program. Thread-safe.
1160
+ //
1161
+ void SetLogSymlink(LogSeverity severity, const char* symlink_basename);
1162
+
1163
+ //
1164
+ // Used to send logs to some other kind of destination
1165
+ // Users should subclass LogSink and override send to do whatever they want.
1166
+ // Implementations must be thread-safe because a shared instance will
1167
+ // be called from whichever thread ran the LOG(XXX) line.
1168
+ class LogSink {
1169
+ public:
1170
+ virtual ~LogSink();
1171
+
1172
+ // Sink's logging logic (message_len is such as to exclude '\n' at the end).
1173
+ // This method can't use LOG() or CHECK() as logging system mutex(s) are held
1174
+ // during this call.
1175
+ virtual void send(LogSeverity severity, const char* full_filename,
1176
+ const char* base_filename, int line,
1177
+ const struct tm* tm_time,
1178
+ const char* message, size_t message_len) = 0;
1179
+
1180
+ // Redefine this to implement waiting for
1181
+ // the sink's logging logic to complete.
1182
+ // It will be called after each send() returns,
1183
+ // but before that LogMessage exits or crashes.
1184
+ // By default this function does nothing.
1185
+ // Using this function one can implement complex logic for send()
1186
+ // that itself involves logging; and do all this w/o causing deadlocks and
1187
+ // inconsistent rearrangement of log messages.
1188
+ // E.g. if a LogSink has thread-specific actions, the send() method
1189
+ // can simply add the message to a queue and wake up another thread that
1190
+ // handles real logging while itself making some LOG() calls;
1191
+ // WaitTillSent() can be implemented to wait for that logic to complete.
1192
+ // See our unittest for an example.
1193
+ virtual void WaitTillSent();
1194
+
1195
+ // Returns the normal text output of the log message.
1196
+ // Can be useful to implement send().
1197
+ static string ToString(LogSeverity severity, const char* file, int line,
1198
+ const struct tm* tm_time,
1199
+ const char* message, size_t message_len);
1200
+ };
1201
+
1202
+ // Add or remove a LogSink as a consumer of logging data. Thread-safe.
1203
+ void AddLogSink(LogSink *destination);
1204
+ void RemoveLogSink(LogSink *destination);
1205
+
1206
+ //
1207
+ // Specify an "extension" added to the filename specified via
1208
+ // SetLogDestination. This applies to all severity levels. It's
1209
+ // often used to append the port we're listening on to the logfile
1210
+ // name. Thread-safe.
1211
+ //
1212
+ void SetLogFilenameExtension(const char* filename_extension);
1213
+
1214
+ //
1215
+ // Make it so that all log messages of at least a particular severity
1216
+ // are logged to stderr (in addition to logging to the usual log
1217
+ // file(s)). Thread-safe.
1218
+ //
1219
+ void SetStderrLogging(LogSeverity min_severity);
1220
+
1221
+ //
1222
+ // Make it so that all log messages go only to stderr. Thread-safe.
1223
+ //
1224
+ void LogToStderr();
1225
+
1226
+ //
1227
+ // Make it so that all log messages of at least a particular severity are
1228
+ // logged via email to a list of addresses (in addition to logging to the
1229
+ // usual log file(s)). The list of addresses is just a string containing
1230
+ // the email addresses to send to (separated by spaces, say).
1231
+ //
1232
+ // Beyond thread-hostile. This function enables email logging,
1233
+ // which calls popen() if any log messages are actually mailed.
1234
+ // A multi-thread program which calls this function, even in a single thread,
1235
+ // will randomly hang if it logs any messages which are mailed.
1236
+ void SetEmailLogging(LogSeverity min_severity, const char* addresses);
1237
+
1238
+ //
1239
+ // Generate a special "status" message. This will be useful to
1240
+ // monitoring scripts that want to know about the progress of
1241
+ // a long-running program. The two supplied arguments should have
1242
+ // identical units. The "done" argument says how much work has
1243
+ // been completed, and the "total" argument says how much total
1244
+ // work has to be done. Thread-hostile if
1245
+ // FLAGS_status_messages_to_status_file. Thread-safe otherwise.
1246
+ //
1247
+ void StatusMessage(int64 done, int64 total);
1248
+
1249
+ // Like StatusMessage(), only writes the status to the file ./STATUS
1250
+ // Intended to make life easier for processes running on the global
1251
+ // work queue, where the standard status message file is ./STATUS.
1252
+ // Thread-hostile.
1253
+ void GWQStatusMessage(const char* msg);
1254
+
1255
+ // A simple function that sends email. dest is a comma-separated
1256
+ // list of addressess.
1257
+ //
1258
+ // Beyond thread-hostile. This function calls popen().
1259
+ // A multi-thread program which calls this function, even in a single thread,
1260
+ // will randomly hang.
1261
+ bool SendEmail(const char*dest, const char *subject, const char*body);
1262
+
1263
+ // Return the set of directories to try generating a log file into.
1264
+ // Thread-hostile, but expected to only be called from InitGoogle.
1265
+ const vector<string>& GetLoggingDirectories();
1266
+
1267
+ // For tests only: Clear the internal [cached] list of logging directories to
1268
+ // force a refresh the next time GetLoggingDirectories is called.
1269
+ // Thread-hostile.
1270
+ void TestOnly_ClearLoggingDirectoriesList();
1271
+
1272
+ // Returns a set of existing temporary directories, which will be a
1273
+ // subset of the directories returned by GetLogginDirectories().
1274
+ // Thread-safe.
1275
+ void GetExistingTempDirectories(vector<string>* list);
1276
+
1277
+ // Print any fatal message again -- useful to call from signal handler
1278
+ // so that the last thing in the output is the fatal message.
1279
+ // Thread-hostile, but a race is unlikely.
1280
+ void ReprintFatalMessage();
1281
+
1282
+ // Truncate a log file that may be the append-only output of multiple
1283
+ // processes and hence can't simply be renamed/reopened (typically a
1284
+ // stdout/stderr). If the file "path" is > "limit" bytes, copy the
1285
+ // last "keep" bytes to offset 0 and truncate the rest. Since we could
1286
+ // be racing with other writers, this approach has the potential to
1287
+ // lose very small amounts of data. For security, only follow symlinks
1288
+ // if the path is /proc/self/fd/*
1289
+ void TruncateLogFile(const char *path, int64 limit, int64 keep);
1290
+
1291
+ // Truncate stdout and stderr if they are over the value specified by
1292
+ // --max_log_size; keep the final 1MB. This function has the same
1293
+ // race condition as TruncateLogFile.
1294
+ void TruncateStdoutStderr();
1295
+
1296
+ // Return the string representation of the provided LogSeverity level.
1297
+ // Thread-safe.
1298
+ const char* GetLogSeverityName(LogSeverity severity);
1299
+
1300
+ // ---------------------------------------------------------------------
1301
+ // Implementation details that are not useful to most clients
1302
+ // ---------------------------------------------------------------------
1303
+
1304
+ // A Logger is the interface used by logging modules (base/logging.cc
1305
+ // and file/logging/blog.cc) to emit entries to a log. A typical
1306
+ // implementation will dump formatted data to a sequence of files. We
1307
+ // also provide interfaces that will forward the data to another
1308
+ // thread so that the invoker never blocks. Implementations should be
1309
+ // thread-safe since the logging system will write to them from
1310
+ // multiple threads.
1311
+
1312
+ namespace base {
1313
+
1314
+ class Logger {
1315
+ public:
1316
+ virtual ~Logger();
1317
+
1318
+ // Writes "message[0,message_len-1]" corresponding to an event that
1319
+ // occurred at "timestamp". If "force_flush" is true, the log file
1320
+ // is flushed immediately.
1321
+ //
1322
+ // The input message has already been formatted as deemed
1323
+ // appropriate by the higher level logging facility. For example,
1324
+ // textual log messages already contain timestamps, and the
1325
+ // file:linenumber header.
1326
+ virtual void Write(bool force_flush,
1327
+ time_t timestamp,
1328
+ const char* message,
1329
+ int message_len) = 0;
1330
+
1331
+ // Flush any buffered messages
1332
+ virtual void Flush() = 0;
1333
+
1334
+ // Get the current LOG file size.
1335
+ // The returned value is approximate since some
1336
+ // logged data may not have been flushed to disk yet.
1337
+ virtual uint32 LogSize() = 0;
1338
+ };
1339
+
1340
+ // Get the logger for the specified severity level. The logger
1341
+ // remains the property of the logging module and should not be
1342
+ // deleted by the caller. Thread-safe.
1343
+ extern Logger* GetLogger(LogSeverity level);
1344
+
1345
+ // Set the logger for the specified severity level. The logger
1346
+ // becomes the property of the logging module and should not
1347
+ // be deleted by the caller. Thread-safe.
1348
+ extern void SetLogger(LogSeverity level, Logger* logger);
1349
+
1350
+ }
1351
+
1352
+ // glibc has traditionally implemented two incompatible versions of
1353
+ // strerror_r(). There is a poorly defined convention for picking the
1354
+ // version that we want, but it is not clear whether it even works with
1355
+ // all versions of glibc.
1356
+ // So, instead, we provide this wrapper that automatically detects the
1357
+ // version that is in use, and then implements POSIX semantics.
1358
+ // N.B. In addition to what POSIX says, we also guarantee that "buf" will
1359
+ // be set to an empty string, if this function failed. This means, in most
1360
+ // cases, you do not need to check the error code and you can directly
1361
+ // use the value of "buf". It will never have an undefined value.
1362
+ int posix_strerror_r(int err, char *buf, size_t len);
1363
+
1364
+
1365
+ // A class for which we define operator<<, which does nothing.
1366
+ class NullStream : public LogMessage::LogStream {
1367
+ public:
1368
+ // Initialize the LogStream so the messages can be written somewhere
1369
+ // (they'll never be actually displayed). This will be needed if a
1370
+ // NullStream& is implicitly converted to LogStream&, in which case
1371
+ // the overloaded NullStream::operator<< will not be invoked.
1372
+ NullStream() : LogMessage::LogStream(message_buffer_, 1, 0) { }
1373
+ NullStream(const char* /*file*/, int /*line*/,
1374
+ const CheckOpString& /*result*/) :
1375
+ LogMessage::LogStream(message_buffer_, 1, 0) { }
1376
+ NullStream &stream() { return *this; }
1377
+ private:
1378
+ // A very short buffer for messages (which we discard anyway). This
1379
+ // will be needed if NullStream& converted to LogStream& (e.g. as a
1380
+ // result of a conditional expression).
1381
+ char message_buffer_[2];
1382
+ };
1383
+
1384
+ // Do nothing. This operator is inline, allowing the message to be
1385
+ // compiled away. The message will not be compiled away if we do
1386
+ // something like (flag ? LOG(INFO) : LOG(ERROR)) << message; when
1387
+ // SKIP_LOG=WARNING. In those cases, NullStream will be implicitly
1388
+ // converted to LogStream and the message will be computed and then
1389
+ // quietly discarded.
1390
+ template<class T>
1391
+ inline NullStream& operator<<(NullStream &str, const T &value) { return str; }
1392
+
1393
+ // Similar to NullStream, but aborts the program (without stack
1394
+ // trace), like LogMessageFatal.
1395
+ class NullStreamFatal : public NullStream {
1396
+ public:
1397
+ NullStreamFatal() { }
1398
+ NullStreamFatal(const char* file, int line, const CheckOpString& result) :
1399
+ NullStream(file, line, result) { }
1400
+ ~NullStreamFatal() ATTRIBUTE_NORETURN { _exit(1); }
1401
+ };
1402
+
1403
+ #endif // _LOGGING_H_