d65324f7ce004bc5154f89fc169c2078e9dee92c
[folly.git] / folly / experimental / logging / LoggerDB.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/Conv.h>
19 #include <folly/CppAttributes.h>
20 #include <folly/Range.h>
21 #include <folly/Synchronized.h>
22 #include <memory>
23 #include <string>
24 #include <unordered_map>
25 #include <vector>
26
27 #include <folly/experimental/logging/LogName.h>
28
29 namespace folly {
30
31 class LogCategory;
32 class LogConfig;
33 class LogHandler;
34 class LogHandlerFactory;
35 enum class LogLevel : uint32_t;
36
37 /**
38  * LoggerDB stores the set of LogCategory objects.
39  */
40 class LoggerDB {
41  public:
42   /**
43    * Get the main LoggerDB singleton.
44    */
45   static LoggerDB* get();
46
47   ~LoggerDB();
48
49   /**
50    * Get the LogCategory for the specified name.
51    *
52    * This creates the LogCategory for the specified name if it does not exist
53    * already.
54    */
55   LogCategory* getCategory(folly::StringPiece name);
56
57   /**
58    * Get the LogCategory for the specified name, if it already exists.
59    *
60    * This returns nullptr if no LogCategory has been created yet for the
61    * specified name.
62    */
63   LogCategory* FOLLY_NULLABLE getCategoryOrNull(folly::StringPiece name);
64
65   /**
66    * Set the log level for the specified category.
67    *
68    * Messages logged to a specific log category will be ignored unless the
69    * message log level is greater than the LogCategory's effective log level.
70    *
71    * If inherit is true, LogCategory's effective log level is the minimum of
72    * its level and it's parent category's effective log level.  If inherit is
73    * false, the LogCategory's effective log level is simply its log level.
74    * (Setting inherit to false is necessary if you want a child LogCategory to
75    * use a less verbose level than its parent categories.)
76    */
77   void setLevel(folly::StringPiece name, LogLevel level, bool inherit = true);
78   void setLevel(LogCategory* category, LogLevel level, bool inherit = true);
79
80   /**
81    * Get a LogConfig object describing the current state of the LoggerDB.
82    *
83    * Note that this may not 100% accurately describe the current configuration
84    * if callers have manually added LogHandlers to some categories without
85    * using the updateConfig() or resetConfig() functions.  In this case
86    * getConfig() will simply report these handlers as "unknown_handler" when
87    * returning handler names for the categories in question.
88    */
89   LogConfig getConfig() const;
90
91   /**
92    * Apply a configuration string specifying a series a log levels.
93    *
94    * The string format is a comma separated list of <name>=<level> sections.
95    * e.g.: "foo=DBG3,log.bar=WARN"
96    *
97    * Returns a list of error messages for each error encountered trying to
98    * parse the config string.  The return value will be an empty vector if no
99    * errors were encountered.
100    */
101   std::vector<std::string> processConfigString(folly::StringPiece config);
102
103   /**
104    * Remove all registered LogHandlers on all LogCategory objects.
105    *
106    * This is called on the main LoggerDB object during shutdown.
107    */
108   void cleanupHandlers();
109
110   /**
111    * Call flush() on all LogHandler objects registered on any LogCategory in
112    * this LoggerDB.
113    *
114    * Returns the number of registered LogHandlers.
115    */
116   size_t flushAllHandlers();
117
118   /**
119    * Register a LogHandlerFactory.
120    *
121    * The LogHandlerFactory will be used to create LogHandler objects from a
122    * LogConfig object during updateConfig() and resetConfig() calls.
123    *
124    * Only one factory can be registered for a given handler type name.
125    * LogHandlerFactory::getType() returns the handler type supported by this
126    * LogHandlerFactory.
127    *
128    * If an existing LogHandlerFactory is already registered with this type name
129    * and replaceExisting is false a std::range_error will be thrown.
130    * Otherwise, if replaceExisting is true, the new factory will replace the
131    * existing factory.
132    */
133   void registerHandlerFactory(
134       std::unique_ptr<LogHandlerFactory> factory,
135       bool replaceExisting = false);
136
137   /**
138    * Remove a registered LogHandlerFactory.
139    *
140    * The type parameter should be the name of the handler type, as returned by
141    * LogHandlerFactory::getType().
142    *
143    * Throws std::range_error if no handler factory with this type name exists.
144    */
145   void unregisterHandlerFactory(folly::StringPiece type);
146
147   /**
148    * Initialize the LogCategory* and std::atomic<LogLevel> used by an XLOG()
149    * statement.
150    *
151    * Returns the current effective LogLevel of the category.
152    */
153   LogLevel xlogInit(
154       folly::StringPiece categoryName,
155       std::atomic<LogLevel>* xlogCategoryLevel,
156       LogCategory** xlogCategory);
157   LogCategory* xlogInitCategory(
158       folly::StringPiece categoryName,
159       LogCategory** xlogCategory,
160       std::atomic<bool>* isInitialized);
161
162   enum TestConstructorArg { TESTING };
163
164   /**
165    * Construct a LoggerDB for testing purposes.
166    *
167    * Most callers should not need this function, and should use
168    * LoggerDB::get() to obtain the main LoggerDB singleton.  This function
169    * exists mainly to allow testing LoggerDB objects in unit tests.
170    * It requires an explicit argument just to prevent callers from calling it
171    * unintentionally.
172    */
173   explicit LoggerDB(TestConstructorArg);
174
175   /**
176    * internalWarning() is used to report a problem when something goes wrong
177    * internally in the logging library.
178    *
179    * We can't log these messages through the normal logging flow since logging
180    * itself has failed.
181    *
182    * Example scenarios where this is used:
183    * - We fail to write to a log file (for instance, when the disk is full)
184    * - A LogHandler throws an unexpected exception
185    */
186   template <typename... Args>
187   static void internalWarning(
188       folly::StringPiece file,
189       int lineNumber,
190       Args&&... args) noexcept {
191     internalWarningImpl(
192         file, lineNumber, folly::to<std::string>(std::forward<Args>(args)...));
193   }
194
195   using InternalWarningHandler =
196       void (*)(folly::StringPiece file, int lineNumber, std::string&&);
197
198   /**
199    * Set a function to be called when the logging library generates an internal
200    * warning.
201    *
202    * The supplied handler should never throw exceptions.
203    *
204    * If a null handler is supplied, the default built-in handler will be used.
205    *
206    * The default handler reports the message with _CrtDbgReport(_CRT_WARN) on
207    * Windows, and prints the message to stderr on other platforms.  It also
208    * rate limits messages if they are arriving too quickly.
209    */
210   static void setInternalWarningHandler(InternalWarningHandler handler);
211
212  private:
213   using LoggerNameMap = std::unordered_map<
214       folly::StringPiece,
215       std::unique_ptr<LogCategory>,
216       LogName::Hash,
217       LogName::Equals>;
218
219   using HandlerFactoryMap =
220       std::unordered_map<std::string, std::unique_ptr<LogHandlerFactory>>;
221   using HandlerMap = std::unordered_map<std::string, std::weak_ptr<LogHandler>>;
222   struct HandlerInfo {
223     HandlerFactoryMap factories;
224     HandlerMap handlers;
225   };
226
227   // Forbidden copy constructor and assignment operator
228   LoggerDB(LoggerDB const&) = delete;
229   LoggerDB& operator=(LoggerDB const&) = delete;
230
231   LoggerDB();
232   LogCategory* getOrCreateCategoryLocked(
233       LoggerNameMap& loggersByName,
234       folly::StringPiece name);
235   LogCategory* createCategoryLocked(
236       LoggerNameMap& loggersByName,
237       folly::StringPiece name,
238       LogCategory* parent);
239
240   static void internalWarningImpl(
241       folly::StringPiece filename,
242       int lineNumber,
243       std::string&& msg) noexcept;
244   static void defaultInternalWarningImpl(
245       folly::StringPiece filename,
246       int lineNumber,
247       std::string&& msg) noexcept;
248
249   /**
250    * A map of LogCategory objects by name.
251    *
252    * Lookups can be performed using arbitrary StringPiece values that do not
253    * have to be in canonical form.
254    */
255   folly::Synchronized<LoggerNameMap> loggersByName_;
256
257   /**
258    * The LogHandlers and LogHandlerFactories.
259    */
260   folly::Synchronized<HandlerInfo> handlerInfo_;
261
262   static std::atomic<InternalWarningHandler> warningHandler_;
263 };
264 } // namespace folly