logging: fix issues detecting XLOG(FATAL) statements as noreturn
[folly.git] / folly / experimental / logging / xlog.h
1 /*
2  * Copyright 2004-present Facebook, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *   http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 #pragma once
17
18 #include <folly/Likely.h>
19 #include <folly/Range.h>
20 #include <folly/experimental/logging/LogStream.h>
21 #include <folly/experimental/logging/Logger.h>
22 #include <folly/experimental/logging/LoggerDB.h>
23 #include <cstdlib>
24
25 /*
26  * This file contains the XLOG() and XLOGF() macros.
27  *
28  * These macros make it easy to use the logging library without having to
29  * manually pick log category names.  All XLOG() and XLOGF() statements in a
30  * given file automatically use a LogCategory based on the current file name.
31  *
32  * For instance, in src/foo/bar.cpp, the default log category name will be
33  * "src.foo.bar"
34  *
35  * If desired, the log category name used by XLOG() in a .cpp file may be
36  * overridden using XLOG_SET_CATEGORY_NAME() macro.
37  */
38
39 /**
40  * Log a message to this file's default log category.
41  *
42  * By default the log category name is automatically picked based on the
43  * current filename.  In src/foo/bar.cpp the log category name "src.foo.bar"
44  * will be used.  In "lib/stuff/foo.h" the log category name will be
45  * "lib.stuff.foo"
46  *
47  * Note that the filename is based on the __FILE__ macro defined by the
48  * compiler.  This is typically dependent on the filename argument that you
49  * give to the compiler.  For example, if you compile src/foo/bar.cpp by
50  * invoking the compiler inside src/foo and only give it "bar.cpp" as an
51  * argument, the category name will simply be "bar".  In general XLOG() works
52  * best if you always invoke the compiler from the root directory of your
53  * project repository.
54  */
55 #define XLOG(level, ...)                   \
56   XLOG_IMPL(                               \
57       ::folly::LogLevel::level,            \
58       ::folly::LogStreamProcessor::APPEND, \
59       ##__VA_ARGS__)
60
61 /**
62  * Log a message to this file's default log category, using a format string.
63  */
64 #define XLOGF(level, fmt, arg1, ...)       \
65   XLOG_IMPL(                               \
66       ::folly::LogLevel::level,            \
67       ::folly::LogStreamProcessor::FORMAT, \
68       fmt,                                 \
69       arg1,                                \
70       ##__VA_ARGS__)
71
72 /**
73  * Helper macro used to implement XLOG() and XLOGF()
74  *
75  * Beware that the level argument is evalutated twice.
76  *
77  * This macro is somewhat tricky:
78  *
79  * - In order to support streaming argument support (with the << operator),
80  *   the macro must expand to a single ternary ? expression.  This is the only
81  *   way we can avoid evaluating the log arguments if the log check fails,
82  *   and still have the macro behave as expected when used as the body of an if
83  *   or else statement.
84  *
85  * - We need to store some static-scope local state in order to track the
86  *   LogCategory to use.  This is a bit tricky to do and still meet the
87  *   requirements of being a single expression, but fortunately static
88  *   variables inside a lambda work for this purpose.
89  *
90  *   Inside header files, each XLOG() statement defines to static variables:
91  *   - the LogLevel for this category
92  *   - a pointer to the LogCategory
93  *
94  *   If the __INCLUDE_LEVEL__ macro is available (both gcc and clang support
95  *   this), then we we can detect when we are inside a .cpp file versus a
96  *   header file.  If we are inside a .cpp file, we can avoid declaring these
97  *   variables once per XLOG() statement, and instead we only declare one copy
98  *   of these variables for the entire file.
99  *
100  * - We want to make sure this macro is safe to use even from inside static
101  *   initialization code that runs before main.  We also want to make the log
102  *   admittance check as cheap as possible, so that disabled debug logs have
103  *   minimal overhead, and can be left in place even in performance senstive
104  *   code.
105  *
106  *   In order to do this, we rely on zero-initialization of variables with
107  *   static storage duration.  The LogLevel variable will always be
108  *   0-initialized before any code runs.  Therefore the very first time an
109  *   XLOG() statement is hit the initial log level check will always pass
110  *   (since all level values are greater or equal to 0), and we then do a
111  *   second check to see if the log level and category variables need to be
112  *   initialized.  On all subsequent calls, disabled log statements can be
113  *   skipped with just a single check of the LogLevel.
114  */
115 #define XLOG_IMPL(level, type, ...)                                          \
116   (!XLOG_IS_ON_IMPL(level))                                                  \
117       ? ::folly::logDisabledHelper(                                          \
118             std::integral_constant<bool, ::folly::isLogLevelFatal(level)>{}) \
119       : ::folly::LogStreamVoidify<::folly::isLogLevelFatal(level)>{} &       \
120           ::folly::LogStreamProcessor(                                       \
121               [] {                                                           \
122                 static ::folly::XlogCategoryInfo<XLOG_IS_IN_HEADER_FILE>     \
123                     _xlogCategory_;                                          \
124                 return _xlogCategory_.getInfo(                               \
125                     &xlog_detail::xlogFileScopeInfo);                        \
126               }(),                                                           \
127               (level),                                                       \
128               xlog_detail::getXlogCategoryName(__FILE__, 0),                 \
129               xlog_detail::isXlogCategoryOverridden(0),                      \
130               __FILE__,                                                      \
131               __LINE__,                                                      \
132               (type),                                                        \
133               ##__VA_ARGS__)                                                 \
134               .stream()
135
136 /**
137  * Check if and XLOG() statement with the given log level would be enabled.
138  *
139  * The level parameter must be an unqualified LogLevel enum value.
140  */
141 #define XLOG_IS_ON(level) XLOG_IS_ON_IMPL(::folly::LogLevel::level)
142
143 /**
144  * Helper macro to implement of XLOG_IS_ON()
145  *
146  * This macro is used in the XLOG() implementation, and therefore must be as
147  * cheap as possible.  It stores the category's LogLevel as a local static
148  * variable.  The very first time this macro is evaluated it will look up the
149  * correct LogCategory and initialize the LogLevel.  Subsequent calls then
150  * are only a single conditional log level check.
151  *
152  * The LogCategory object keeps track of this local LogLevel variable and
153  * automatically keeps it up-to-date when the category's effective level is
154  * changed.
155  *
156  * See XlogLevelInfo for the implementation details.
157  */
158 #define XLOG_IS_ON_IMPL(level)                                         \
159   ([] {                                                                \
160     static ::folly::XlogLevelInfo<XLOG_IS_IN_HEADER_FILE> _xlogLevel_; \
161     return _xlogLevel_.check(                                          \
162         (level),                                                       \
163         xlog_detail::getXlogCategoryName(__FILE__, 0),                 \
164         xlog_detail::isXlogCategoryOverridden(0),                      \
165         &xlog_detail::xlogFileScopeInfo);                              \
166   }())
167
168 /**
169  * Get the name of the log category that will be used by XLOG() statements
170  * in this file.
171  */
172 #define XLOG_GET_CATEGORY_NAME()                       \
173   (xlog_detail::isXlogCategoryOverridden(0)            \
174        ? xlog_detail::getXlogCategoryName(__FILE__, 0) \
175        : ::folly::getXlogCategoryNameForFile(__FILE__))
176
177 /**
178  * Get a pointer to the LogCategory that will be used by XLOG() statements in
179  * this file.
180  *
181  * This is just a small wrapper around a LoggerDB::getCategory() call.
182  * This must be implemented as a macro since it uses __FILE__, and that must
183  * expand to the correct filename based on where the macro is used.
184  */
185 #define XLOG_GET_CATEGORY() \
186   folly::LoggerDB::get()->getCategory(XLOG_GET_CATEGORY_NAME())
187
188 /**
189  * XLOG_SET_CATEGORY_NAME() can be used to explicitly define the log category
190  * name used by all XLOG() and XLOGF() calls in this translation unit.
191  *
192  * This overrides the default behavior of picking a category name based on the
193  * current filename.
194  *
195  * This should be used at the top-level scope in a .cpp file, before any XLOG()
196  * or XLOGF() macros have been used in the file.
197  *
198  * XLOG_SET_CATEGORY_NAME() cannot be used inside header files.
199  */
200 #ifdef __INCLUDE_LEVEL__
201 #define XLOG_SET_CATEGORY_CHECK \
202   static_assert(                \
203       __INCLUDE_LEVEL__ == 0,   \
204       "XLOG_SET_CATEGORY_NAME() should not be used in header files");
205 #else
206 #define XLOG_SET_CATEGORY_CHECK
207 #endif
208
209 #define XLOG_SET_CATEGORY_NAME(category)                   \
210   namespace {                                              \
211   namespace xlog_detail {                                  \
212   XLOG_SET_CATEGORY_CHECK                                  \
213   constexpr inline folly::StringPiece getXlogCategoryName( \
214       folly::StringPiece,                                  \
215       int) {                                               \
216     return category;                                       \
217   }                                                        \
218   constexpr inline bool isXlogCategoryOverridden(int) {    \
219     return true;                                           \
220   }                                                        \
221   }                                                        \
222   }
223
224 /**
225  * XLOG_IS_IN_HEADER_FILE evaluates to false if we can definitively tell if we
226  * are not in a header file.  Otherwise, it evaluates to true.
227  */
228 #ifdef __INCLUDE_LEVEL__
229 #define XLOG_IS_IN_HEADER_FILE bool(__INCLUDE_LEVEL__ > 0)
230 #else
231 // Without __INCLUDE_LEVEL__ we canot tell if we are in a header file or not,
232 // and must pessimstically assume we are always in a header file.
233 #define XLOG_IS_IN_HEADER_FILE true
234 #endif
235
236 namespace folly {
237
238 class XlogFileScopeInfo {
239  public:
240 #ifdef __INCLUDE_LEVEL__
241   std::atomic<::folly::LogLevel> level;
242   ::folly::LogCategory* category;
243 #endif
244 };
245
246 /**
247  * A file-static XlogLevelInfo and XlogCategoryInfo object is declared for each
248  * XLOG() statement.
249  *
250  * We intentionally do not provide constructors for these structures, and rely
251  * on their members to be zero-initialized when the program starts.  This
252  * ensures that everything will work as desired even if XLOG() statements are
253  * used during dynamic object initialization before main().
254  */
255 template <bool IsInHeaderFile>
256 class XlogLevelInfo {
257  public:
258   bool check(
259       LogLevel levelToCheck,
260       folly::StringPiece categoryName,
261       bool isOverridden,
262       XlogFileScopeInfo*) {
263     // Do an initial relaxed check.  If this fails we know the category level
264     // is initialized and the log admittance check failed.
265     // Use LIKELY() to optimize for the case of disabled debug statements:
266     // we disabled debug statements to be cheap.  If the log message is
267     // enabled then this check will still be minimal perf overhead compared to
268     // the overall cost of logging it.
269     if (LIKELY(levelToCheck < level_.load(std::memory_order_relaxed))) {
270       return false;
271     }
272
273     // If we are still here, then either:
274     // - The log level check actually passed, or
275     // - level_ has not been initialized yet, and we have to initialize it and
276     //   then re-perform the check.
277     //
278     // Do this work in a separate helper method.  It is intentionally defined
279     // in the xlog.cpp file to avoid inlining, to reduce the amount of code
280     // emitted for each XLOG() statement.
281     auto currentLevel = loadLevelFull(categoryName, isOverridden);
282     return levelToCheck >= currentLevel;
283   }
284
285  private:
286   LogLevel loadLevelFull(folly::StringPiece categoryName, bool isOverridden);
287
288   // XlogLevelInfo objects are always defined with static storage.
289   // This member will always be zero-initialized on program start.
290   std::atomic<LogLevel> level_;
291 };
292
293 template <bool IsInHeaderFile>
294 class XlogCategoryInfo {
295  public:
296   bool isInitialized() const {
297     return isInitialized_.load(std::memory_order_acquire);
298   }
299
300   LogCategory* init(folly::StringPiece categoryName, bool isOverridden);
301
302   LogCategory* getCategory(XlogFileScopeInfo*) {
303     return category_;
304   }
305
306   /**
307    * Get a pointer to pass into the LogStreamProcessor constructor,
308    * so that it is able to look up the LogCategory information.
309    */
310   XlogCategoryInfo<IsInHeaderFile>* getInfo(XlogFileScopeInfo*) {
311     return this;
312   }
313
314  private:
315   // These variables will always be zero-initialized on program start.
316   std::atomic<bool> isInitialized_;
317   LogCategory* category_;
318 };
319
320 #ifdef __INCLUDE_LEVEL__
321 /**
322  * Specialization of XlogLevelInfo for XLOG() statements in the .cpp file being
323  * compiled.  In this case we only define a single file-static LogLevel object
324  * for the entire file, rather than defining one for each XLOG() statement.
325  */
326 template <>
327 class XlogLevelInfo<false> {
328  public:
329   static bool check(
330       LogLevel levelToCheck,
331       folly::StringPiece categoryName,
332       bool isOverridden,
333       XlogFileScopeInfo* fileScopeInfo) {
334     // As above in the non-specialized XlogFileScopeInfo code, do a simple
335     // relaxed check first.
336     if (LIKELY(
337             levelToCheck <
338             fileScopeInfo->level.load(::std::memory_order_relaxed))) {
339       return false;
340     }
341
342     // If we are still here we the file-scope log level either needs to be
343     // initalized, or the log level check legitimately passed.
344     auto currentLevel =
345         loadLevelFull(categoryName, isOverridden, fileScopeInfo);
346     return levelToCheck >= currentLevel;
347   }
348
349  private:
350   static LogLevel loadLevelFull(
351       folly::StringPiece categoryName,
352       bool isOverridden,
353       XlogFileScopeInfo* fileScopeInfo);
354 };
355
356 /**
357  * Specialization of XlogCategoryInfo for XLOG() statements in the .cpp file
358  * being compiled.  In this case we only define a single file-static LogLevel
359  * object for the entire file, rather than defining one for each XLOG()
360  * statement.
361  */
362 template <>
363 class XlogCategoryInfo<false> {
364  public:
365   /**
366    * Get a pointer to pass into the LogStreamProcessor constructor,
367    * so that it is able to look up the LogCategory information.
368    */
369   XlogFileScopeInfo* getInfo(XlogFileScopeInfo* fileScopeInfo) {
370     return fileScopeInfo;
371   }
372 };
373 #endif
374
375 /**
376  * Get the default XLOG() category name for the given filename.
377  *
378  * This function returns the category name that will be used by XLOG() if
379  * XLOG_SET_CATEGORY_NAME() has not been used.
380  */
381 std::string getXlogCategoryNameForFile(folly::StringPiece filename);
382 }
383
384 /*
385  * We intentionally use an unnamed namespace inside a header file here.
386  *
387  * We want each .cpp file that uses xlog.h to get its own separate
388  * implementation of the following functions and variables.
389  */
390 namespace {
391 namespace xlog_detail {
392 /**
393  * The default getXlogCategoryName() function.
394  *
395  * By default this simply returns the filename argument passed in.
396  * The default isXlogCategoryOverridden() function returns false, indicating
397  * that the return value from getXlogCategoryName() needs to be converted
398  * using getXlogCategoryNameForFile().
399  *
400  * These are two separate steps because getXlogCategoryName() itself needs to
401  * remain constexpr--it is always evaluated in XLOG() statements, but we only
402  * want to call getXlogCategoryNameForFile() the very first time through, when
403  * we have to initialize the LogCategory object.
404  *
405  * This is a template function purely so that XLOG_SET_CATEGORY_NAME() can
406  * define a more specific version of this function that will take precedence
407  * over this one.
408  */
409 template <typename T>
410 constexpr inline folly::StringPiece getXlogCategoryName(
411     folly::StringPiece filename,
412     T) {
413   return filename;
414 }
415
416 /**
417  * The default isXlogCategoryOverridden() function.
418  *
419  * This returns false indicating that the category name has not been
420  * overridden, so getXlogCategoryName() returns a raw filename that needs
421  * to be translated with getXlogCategoryNameForFile().
422  *
423  * This is a template function purely so that XLOG_SET_CATEGORY_NAME() can
424  * define a more specific version of this function that will take precedence
425  * over this one.
426  */
427 template <typename T>
428 constexpr inline bool isXlogCategoryOverridden(T) {
429   return false;
430 }
431
432 /**
433  * File-scope LogLevel and LogCategory data for XLOG() statements,
434  * if __INCLUDE_LEVEL__ is supported.
435  *
436  * This allows us to only have one LogLevel and LogCategory pointer for the
437  * entire .cpp file, rather than needing a separate copy for each XLOG()
438  * statement.
439  */
440 ::folly::XlogFileScopeInfo xlogFileScopeInfo;
441 }
442 }