ca229af5046a588067a4db9b493a7183c89cc9b4
[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       ? static_cast<void>(0)                                             \
118       : ::folly::LogStreamVoidify<::folly::isLogLevelFatal(level)>{} &   \
119           ::folly::LogStreamProcessor(                                   \
120               [] {                                                       \
121                 static ::folly::XlogCategoryInfo<XLOG_IS_IN_HEADER_FILE> \
122                     _xlogCategory_;                                      \
123                 return _xlogCategory_.getInfo(                           \
124                     &xlog_detail::xlogFileScopeInfo);                    \
125               }(),                                                       \
126               (level),                                                   \
127               xlog_detail::getXlogCategoryName(__FILE__, 0),             \
128               xlog_detail::isXlogCategoryOverridden(0),                  \
129               __FILE__,                                                  \
130               __LINE__,                                                  \
131               (type),                                                    \
132               ##__VA_ARGS__)                                             \
133               .stream()
134
135 /**
136  * Check if and XLOG() statement with the given log level would be enabled.
137  */
138 #define XLOG_IS_ON(level) XLOG_IS_ON_IMPL(::folly::LogLevel::level)
139
140 /**
141  * Helper macro to implement of XLOG_IS_ON()
142  *
143  * This macro is used in the XLOG() implementation, and therefore must be as
144  * cheap as possible.  It stores the category's LogLevel as a local static
145  * variable.  The very first time this macro is evaluated it will look up the
146  * correct LogCategory and initialize the LogLevel.  Subsequent calls then
147  * are only a single conditional log level check.
148  *
149  * The LogCategory object keeps track of this local LogLevel variable and
150  * automatically keeps it up-to-date when the category's effective level is
151  * changed.
152  *
153  * See XlogLevelInfo for the implementation details.
154  */
155 #define XLOG_IS_ON_IMPL(level)                                         \
156   ([] {                                                                \
157     static ::folly::XlogLevelInfo<XLOG_IS_IN_HEADER_FILE> _xlogLevel_; \
158     return _xlogLevel_.check(                                          \
159         (level),                                                       \
160         xlog_detail::getXlogCategoryName(__FILE__, 0),                 \
161         xlog_detail::isXlogCategoryOverridden(0),                      \
162         &xlog_detail::xlogFileScopeInfo);                              \
163   }())
164
165 /**
166  * Get the name of the log category that will be used by XLOG() statements
167  * in this file.
168  */
169 #define XLOG_GET_CATEGORY_NAME()                       \
170   (xlog_detail::isXlogCategoryOverridden(0)            \
171        ? xlog_detail::getXlogCategoryName(__FILE__, 0) \
172        : ::folly::getXlogCategoryNameForFile(__FILE__))
173
174 /**
175  * Get a pointer to the LogCategory that will be used by XLOG() statements in
176  * this file.
177  *
178  * This is just a small wrapper around a LoggerDB::getCategory() call.
179  * This must be implemented as a macro since it uses __FILE__, and that must
180  * expand to the correct filename based on where the macro is used.
181  */
182 #define XLOG_GET_CATEGORY() \
183   folly::LoggerDB::get()->getCategory(XLOG_GET_CATEGORY_NAME())
184
185 /**
186  * XLOG_SET_CATEGORY_NAME() can be used to explicitly define the log category
187  * name used by all XLOG() and XLOGF() calls in this translation unit.
188  *
189  * This overrides the default behavior of picking a category name based on the
190  * current filename.
191  *
192  * This should be used at the top-level scope in a .cpp file, before any XLOG()
193  * or XLOGF() macros have been used in the file.
194  *
195  * XLOG_SET_CATEGORY_NAME() cannot be used inside header files.
196  */
197 #ifdef __INCLUDE_LEVEL__
198 #define XLOG_SET_CATEGORY_CHECK \
199   static_assert(                \
200       __INCLUDE_LEVEL__ == 0,   \
201       "XLOG_SET_CATEGORY_NAME() should not be used in header files");
202 #else
203 #define XLOG_SET_CATEGORY_CHECK
204 #endif
205
206 #define XLOG_SET_CATEGORY_NAME(category)                   \
207   namespace {                                              \
208   namespace xlog_detail {                                  \
209   XLOG_SET_CATEGORY_CHECK                                  \
210   constexpr inline folly::StringPiece getXlogCategoryName( \
211       folly::StringPiece,                                  \
212       int) {                                               \
213     return category;                                       \
214   }                                                        \
215   constexpr inline bool isXlogCategoryOverridden(int) {    \
216     return true;                                           \
217   }                                                        \
218   }                                                        \
219   }
220
221 /**
222  * XLOG_IS_IN_HEADER_FILE evaluates to false if we can definitively tell if we
223  * are not in a header file.  Otherwise, it evaluates to true.
224  */
225 #ifdef __INCLUDE_LEVEL__
226 #define XLOG_IS_IN_HEADER_FILE bool(__INCLUDE_LEVEL__ > 0)
227 #else
228 // Without __INCLUDE_LEVEL__ we canot tell if we are in a header file or not,
229 // and must pessimstically assume we are always in a header file.
230 #define XLOG_IS_IN_HEADER_FILE true
231 #endif
232
233 namespace folly {
234
235 class XlogFileScopeInfo {
236  public:
237 #ifdef __INCLUDE_LEVEL__
238   std::atomic<::folly::LogLevel> level;
239   ::folly::LogCategory* category;
240 #endif
241 };
242
243 /**
244  * A file-static XlogLevelInfo and XlogCategoryInfo object is declared for each
245  * XLOG() statement.
246  *
247  * We intentionally do not provide constructors for these structures, and rely
248  * on their members to be zero-initialized when the program starts.  This
249  * ensures that everything will work as desired even if XLOG() statements are
250  * used during dynamic object initialization before main().
251  */
252 template <bool IsInHeaderFile>
253 class XlogLevelInfo {
254  public:
255   bool check(
256       LogLevel levelToCheck,
257       folly::StringPiece categoryName,
258       bool isOverridden,
259       XlogFileScopeInfo*) {
260     // Do an initial relaxed check.  If this fails we know the category level
261     // is initialized and the log admittance check failed.
262     // Use LIKELY() to optimize for the case of disabled debug statements:
263     // we disabled debug statements to be cheap.  If the log message is
264     // enabled then this check will still be minimal perf overhead compared to
265     // the overall cost of logging it.
266     if (LIKELY(levelToCheck < level_.load(std::memory_order_relaxed))) {
267       return false;
268     }
269
270     // If we are still here, then either:
271     // - The log level check actually passed, or
272     // - level_ has not been initialized yet, and we have to initialize it and
273     //   then re-perform the check.
274     //
275     // Do this work in a separate helper method.  It is intentionally defined
276     // in the xlog.cpp file to avoid inlining, to reduce the amount of code
277     // emitted for each XLOG() statement.
278     auto currentLevel = loadLevelFull(categoryName, isOverridden);
279     return levelToCheck >= currentLevel;
280   }
281
282  private:
283   LogLevel loadLevelFull(folly::StringPiece categoryName, bool isOverridden);
284
285   // XlogLevelInfo objects are always defined with static storage.
286   // This member will always be zero-initialized on program start.
287   std::atomic<LogLevel> level_;
288 };
289
290 template <bool IsInHeaderFile>
291 class XlogCategoryInfo {
292  public:
293   bool isInitialized() const {
294     return isInitialized_.load(std::memory_order_acquire);
295   }
296
297   LogCategory* init(folly::StringPiece categoryName, bool isOverridden);
298
299   LogCategory* getCategory(XlogFileScopeInfo*) {
300     return category_;
301   }
302
303   /**
304    * Get a pointer to pass into the LogStreamProcessor constructor,
305    * so that it is able to look up the LogCategory information.
306    */
307   XlogCategoryInfo<IsInHeaderFile>* getInfo(XlogFileScopeInfo*) {
308     return this;
309   }
310
311  private:
312   // These variables will always be zero-initialized on program start.
313   std::atomic<bool> isInitialized_;
314   LogCategory* category_;
315 };
316
317 #ifdef __INCLUDE_LEVEL__
318 /**
319  * Specialization of XlogLevelInfo for XLOG() statements in the .cpp file being
320  * compiled.  In this case we only define a single file-static LogLevel object
321  * for the entire file, rather than defining one for each XLOG() statement.
322  */
323 template <>
324 class XlogLevelInfo<false> {
325  public:
326   static bool check(
327       LogLevel levelToCheck,
328       folly::StringPiece categoryName,
329       bool isOverridden,
330       XlogFileScopeInfo* fileScopeInfo) {
331     // As above in the non-specialized XlogFileScopeInfo code, do a simple
332     // relaxed check first.
333     if (LIKELY(
334             levelToCheck <
335             fileScopeInfo->level.load(::std::memory_order_relaxed))) {
336       return false;
337     }
338
339     // If we are still here we the file-scope log level either needs to be
340     // initalized, or the log level check legitimately passed.
341     auto currentLevel =
342         loadLevelFull(categoryName, isOverridden, fileScopeInfo);
343     return levelToCheck >= currentLevel;
344   }
345
346  private:
347   static LogLevel loadLevelFull(
348       folly::StringPiece categoryName,
349       bool isOverridden,
350       XlogFileScopeInfo* fileScopeInfo);
351 };
352
353 /**
354  * Specialization of XlogCategoryInfo for XLOG() statements in the .cpp file
355  * being compiled.  In this case we only define a single file-static LogLevel
356  * object for the entire file, rather than defining one for each XLOG()
357  * statement.
358  */
359 template <>
360 class XlogCategoryInfo<false> {
361  public:
362   /**
363    * Get a pointer to pass into the LogStreamProcessor constructor,
364    * so that it is able to look up the LogCategory information.
365    */
366   XlogFileScopeInfo* getInfo(XlogFileScopeInfo* fileScopeInfo) {
367     return fileScopeInfo;
368   }
369 };
370 #endif
371
372 /**
373  * Get the default XLOG() category name for the given filename.
374  *
375  * This function returns the category name that will be used by XLOG() if
376  * XLOG_SET_CATEGORY_NAME() has not been used.
377  */
378 std::string getXlogCategoryNameForFile(folly::StringPiece filename);
379 }
380
381 /*
382  * We intentionally use an unnamed namespace inside a header file here.
383  *
384  * We want each .cpp file that uses xlog.h to get its own separate
385  * implementation of the following functions and variables.
386  */
387 namespace {
388 namespace xlog_detail {
389 /**
390  * The default getXlogCategoryName() function.
391  *
392  * By default this simply returns the filename argument passed in.
393  * The default isXlogCategoryOverridden() function returns false, indicating
394  * that the return value from getXlogCategoryName() needs to be converted
395  * using getXlogCategoryNameForFile().
396  *
397  * These are two separate steps because getXlogCategoryName() itself needs to
398  * remain constexpr--it is always evaluated in XLOG() statements, but we only
399  * want to call getXlogCategoryNameForFile() the very first time through, when
400  * we have to initialize the LogCategory object.
401  *
402  * This is a template function purely so that XLOG_SET_CATEGORY_NAME() can
403  * define a more specific version of this function that will take precedence
404  * over this one.
405  */
406 template <typename T>
407 constexpr inline folly::StringPiece getXlogCategoryName(
408     folly::StringPiece filename,
409     T) {
410   return filename;
411 }
412
413 /**
414  * The default isXlogCategoryOverridden() function.
415  *
416  * This returns false indicating that the category name has not been
417  * overridden, so getXlogCategoryName() returns a raw filename that needs
418  * to be translated with getXlogCategoryNameForFile().
419  *
420  * This is a template function purely so that XLOG_SET_CATEGORY_NAME() can
421  * define a more specific version of this function that will take precedence
422  * over this one.
423  */
424 template <typename T>
425 constexpr inline bool isXlogCategoryOverridden(T) {
426   return false;
427 }
428
429 /**
430  * File-scope LogLevel and LogCategory data for XLOG() statements,
431  * if __INCLUDE_LEVEL__ is supported.
432  *
433  * This allows us to only have one LogLevel and LogCategory pointer for the
434  * entire .cpp file, rather than needing a separate copy for each XLOG()
435  * statement.
436  */
437 ::folly::XlogFileScopeInfo xlogFileScopeInfo;
438 }
439 }