2 * Copyright 2004-present Facebook, Inc.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 #include <folly/Conv.h>
19 #include <folly/CppAttributes.h>
20 #include <folly/Range.h>
21 #include <folly/Synchronized.h>
24 #include <unordered_map>
27 #include <folly/experimental/logging/LogName.h>
34 class LogHandlerFactory;
35 enum class LogLevel : uint32_t;
38 * LoggerDB stores the set of LogCategory objects.
43 * Get the main LoggerDB singleton.
45 static LoggerDB* get();
50 * Get the LogCategory for the specified name.
52 * This creates the LogCategory for the specified name if it does not exist
55 LogCategory* getCategory(folly::StringPiece name);
58 * Get the LogCategory for the specified name, if it already exists.
60 * This returns nullptr if no LogCategory has been created yet for the
63 LogCategory* FOLLY_NULLABLE getCategoryOrNull(folly::StringPiece name);
66 * Set the log level for the specified category.
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.
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.)
77 void setLevel(folly::StringPiece name, LogLevel level, bool inherit = true);
78 void setLevel(LogCategory* category, LogLevel level, bool inherit = true);
81 * Get a LogConfig object describing the current state of the LoggerDB.
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.
89 LogConfig getConfig() const;
92 * Apply a configuration string specifying a series a log levels.
94 * The string format is a comma separated list of <name>=<level> sections.
95 * e.g.: "foo=DBG3,log.bar=WARN"
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.
101 std::vector<std::string> processConfigString(folly::StringPiece config);
104 * Remove all registered LogHandlers on all LogCategory objects.
106 * This is called on the main LoggerDB object during shutdown.
108 void cleanupHandlers();
111 * Call flush() on all LogHandler objects registered on any LogCategory in
114 * Returns the number of registered LogHandlers.
116 size_t flushAllHandlers();
119 * Register a LogHandlerFactory.
121 * The LogHandlerFactory will be used to create LogHandler objects from a
122 * LogConfig object during updateConfig() and resetConfig() calls.
124 * Only one factory can be registered for a given handler type name.
125 * LogHandlerFactory::getType() returns the handler type supported by this
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
133 void registerHandlerFactory(
134 std::unique_ptr<LogHandlerFactory> factory,
135 bool replaceExisting = false);
138 * Remove a registered LogHandlerFactory.
140 * The type parameter should be the name of the handler type, as returned by
141 * LogHandlerFactory::getType().
143 * Throws std::range_error if no handler factory with this type name exists.
145 void unregisterHandlerFactory(folly::StringPiece type);
148 * Initialize the LogCategory* and std::atomic<LogLevel> used by an XLOG()
151 * Returns the current effective LogLevel of the category.
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);
162 enum TestConstructorArg { TESTING };
165 * Construct a LoggerDB for testing purposes.
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
173 explicit LoggerDB(TestConstructorArg);
176 * internalWarning() is used to report a problem when something goes wrong
177 * internally in the logging library.
179 * We can't log these messages through the normal logging flow since logging
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
186 template <typename... Args>
187 static void internalWarning(
188 folly::StringPiece file,
190 Args&&... args) noexcept {
192 file, lineNumber, folly::to<std::string>(std::forward<Args>(args)...));
195 using InternalWarningHandler =
196 void (*)(folly::StringPiece file, int lineNumber, std::string&&);
199 * Set a function to be called when the logging library generates an internal
202 * The supplied handler should never throw exceptions.
204 * If a null handler is supplied, the default built-in handler will be used.
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.
210 static void setInternalWarningHandler(InternalWarningHandler handler);
213 using LoggerNameMap = std::unordered_map<
215 std::unique_ptr<LogCategory>,
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>>;
223 HandlerFactoryMap factories;
227 // Forbidden copy constructor and assignment operator
228 LoggerDB(LoggerDB const&) = delete;
229 LoggerDB& operator=(LoggerDB const&) = delete;
232 LogCategory* getOrCreateCategoryLocked(
233 LoggerNameMap& loggersByName,
234 folly::StringPiece name);
235 LogCategory* createCategoryLocked(
236 LoggerNameMap& loggersByName,
237 folly::StringPiece name,
238 LogCategory* parent);
240 static void internalWarningImpl(
241 folly::StringPiece filename,
243 std::string&& msg) noexcept;
244 static void defaultInternalWarningImpl(
245 folly::StringPiece filename,
247 std::string&& msg) noexcept;
250 * A map of LogCategory objects by name.
252 * Lookups can be performed using arbitrary StringPiece values that do not
253 * have to be in canonical form.
255 folly::Synchronized<LoggerNameMap> loggersByName_;
258 * The LogHandlers and LogHandlerFactories.
260 folly::Synchronized<HandlerInfo> handlerInfo_;
262 static std::atomic<InternalWarningHandler> warningHandler_;