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.
16 #include <folly/experimental/logging/LoggerDB.h>
20 #include <folly/Conv.h>
21 #include <folly/FileUtil.h>
22 #include <folly/String.h>
23 #include <folly/experimental/logging/LogCategory.h>
24 #include <folly/experimental/logging/LogConfig.h>
25 #include <folly/experimental/logging/LogHandler.h>
26 #include <folly/experimental/logging/LogHandlerFactory.h>
27 #include <folly/experimental/logging/LogLevel.h>
28 #include <folly/experimental/logging/Logger.h>
29 #include <folly/experimental/logging/RateLimiter.h>
36 class LoggerDBSingleton {
38 explicit LoggerDBSingleton(LoggerDB* db) : db_{db} {}
39 ~LoggerDBSingleton() {
40 // We intentionally leak the LoggerDB object on destruction.
41 // We want Logger objects to remain valid for the entire lifetime of the
42 // program, without having to worry about destruction ordering issues, or
43 // making the Logger perform reference counting on the LoggerDB.
45 // Therefore the main LoggerDB object, and all of the LogCategory objects
46 // it contains, are always intentionally leaked.
48 // However, we do call db_->cleanupHandlers() to destroy any registered
49 // LogHandler objects. The LogHandlers can be user-defined objects and may
50 // hold resources that should be cleaned up. This also ensures that the
51 // LogHandlers flush all outstanding messages before we exit.
52 db_->cleanupHandlers();
55 LoggerDB* getDB() const {
64 LoggerDB* LoggerDB::get() {
65 // Intentionally leaky singleton
66 static LoggerDBSingleton singleton{new LoggerDB()};
67 return singleton.getDB();
70 LoggerDB::LoggerDB() {
71 // Create the root log category, and set the level to ERR by default
72 auto rootUptr = std::make_unique<LogCategory>(this);
73 LogCategory* root = rootUptr.get();
75 loggersByName_.wlock()->emplace(root->getName(), std::move(rootUptr));
78 root->setLevelLocked(LogLevel::ERR, false);
81 LoggerDB::LoggerDB(TestConstructorArg) : LoggerDB() {}
83 LoggerDB::~LoggerDB() {}
85 LogCategory* LoggerDB::getCategory(StringPiece name) {
86 return getOrCreateCategoryLocked(*loggersByName_.wlock(), name);
89 LogCategory* FOLLY_NULLABLE LoggerDB::getCategoryOrNull(StringPiece name) {
90 auto loggersByName = loggersByName_.rlock();
92 auto it = loggersByName->find(name);
93 if (it == loggersByName->end()) {
96 return it->second.get();
99 void LoggerDB::setLevel(folly::StringPiece name, LogLevel level, bool inherit) {
100 auto loggersByName = loggersByName_.wlock();
101 LogCategory* category = getOrCreateCategoryLocked(*loggersByName, name);
102 category->setLevelLocked(level, inherit);
105 void LoggerDB::setLevel(LogCategory* category, LogLevel level, bool inherit) {
106 auto loggersByName = loggersByName_.wlock();
107 category->setLevelLocked(level, inherit);
110 LogConfig LoggerDB::getConfig() const {
111 auto handlerInfo = handlerInfo_.rlock();
113 LogConfig::HandlerConfigMap handlerConfigs;
114 std::unordered_map<std::shared_ptr<LogHandler>, string> handlersToName;
115 for (const auto& entry : handlerInfo->handlers) {
116 auto handler = entry.second.lock();
120 handlersToName.emplace(handler, entry.first);
121 handlerConfigs.emplace(entry.first, handler->getConfig());
124 size_t anonymousNameIndex = 1;
125 auto generateAnonymousHandlerName = [&]() {
126 // Return a unique name of the form "anonymousHandlerN"
127 // Keep incrementing N until we find a name that isn't currently taken.
129 auto name = to<string>("anonymousHandler", anonymousNameIndex);
130 ++anonymousNameIndex;
131 if (handlerInfo->handlers.find(name) == handlerInfo->handlers.end()) {
137 LogConfig::CategoryConfigMap categoryConfigs;
139 auto loggersByName = loggersByName_.rlock();
140 for (const auto& entry : *loggersByName) {
141 auto* category = entry.second.get();
142 auto levelInfo = category->getLevelInfo();
143 auto handlers = category->getHandlers();
145 // Don't report categories that have default settings.
146 if (handlers.empty() && levelInfo.first == LogLevel::MAX_LEVEL &&
151 // Translate the handler pointers to names
152 std::vector<string> handlerNames;
153 for (const auto& handler : handlers) {
154 auto iter = handlersToName.find(handler);
155 if (iter == handlersToName.end()) {
156 // This LogHandler must have been manually attached to the category,
157 // rather than defined with `updateConfig()` or `resetConfig()`.
158 // Generate a unique name to use for reporting it in the config.
159 auto name = generateAnonymousHandlerName();
160 handlersToName.emplace(handler, name);
161 handlerConfigs.emplace(name, handler->getConfig());
162 handlerNames.emplace_back(name);
164 handlerNames.emplace_back(iter->second);
168 LogCategoryConfig categoryConfig(
169 levelInfo.first, levelInfo.second, handlerNames);
170 categoryConfigs.emplace(category->getName(), std::move(categoryConfig));
174 return LogConfig{std::move(handlerConfigs), std::move(categoryConfigs)};
178 * Process handler config information when starting a config update operation.
180 void LoggerDB::startConfigUpdate(
181 const Synchronized<HandlerInfo>::LockedPtr& handlerInfo,
182 const LogConfig& config,
183 NewHandlerMap* handlers,
184 OldToNewHandlerMap* oldToNewHandlerMap) {
185 // Get a map of all currently existing LogHandlers.
186 // This resolves weak_ptrs to shared_ptrs, and ignores expired weak_ptrs.
187 // This prevents any of these LogHandler pointers from expiring during the
189 for (const auto& entry : handlerInfo->handlers) {
190 auto handler = entry.second.lock();
192 handlers->emplace(entry.first, std::move(handler));
196 // Create all of the new LogHandlers needed from this configuration
197 for (const auto& entry : config.getHandlerConfigs()) {
198 // Look up the LogHandlerFactory
199 auto factoryIter = handlerInfo->factories.find(entry.second.type);
200 if (factoryIter == handlerInfo->factories.end()) {
201 throw std::invalid_argument(to<std::string>(
202 "unknown log handler type \"", entry.second.type, "\""));
205 // Check to see if there is an existing LogHandler with this name
206 std::shared_ptr<LogHandler> oldHandler;
207 auto iter = handlers->find(entry.first);
208 if (iter != handlers->end()) {
209 oldHandler = iter->second;
212 // Create the new log handler
213 const auto& factory = factoryIter->second;
214 std::shared_ptr<LogHandler> handler;
216 handler = factory->updateHandler(oldHandler, entry.second.options);
217 if (handler != oldHandler) {
218 oldToNewHandlerMap->emplace(oldHandler, handler);
221 handler = factory->createHandler(entry.second.options);
223 handlerInfo->handlers[entry.first] = handler;
224 (*handlers)[entry.first] = handler;
227 // Before we start making any LogCategory changes, confirm that all handlers
228 // named in the category configs are known handlers.
229 for (const auto& entry : config.getCategoryConfigs()) {
230 if (!entry.second.handlers.hasValue()) {
233 for (const auto& handlerName : entry.second.handlers.value()) {
234 auto iter = handlers->find(handlerName);
235 if (iter == handlers->end()) {
236 throw std::invalid_argument(to<std::string>(
237 "unknown log handler \"",
239 "\" configured for log category \"",
248 * Update handlerInfo_ at the end of a config update operation.
250 void LoggerDB::finishConfigUpdate(
251 const Synchronized<HandlerInfo>::LockedPtr& handlerInfo,
252 NewHandlerMap* handlers,
253 OldToNewHandlerMap* oldToNewHandlerMap) {
254 // Build a new map to replace handlerInfo->handlers
255 // This will contain only the LogHandlers that are still in use by the
256 // current LogCategory settings.
257 std::unordered_map<std::string, std::weak_ptr<LogHandler>> newHandlerMap;
258 for (const auto& entry : *handlers) {
259 newHandlerMap.emplace(entry.first, entry.second);
261 // Drop all of our shared_ptr references to LogHandler objects,
262 // and then remove entries in newHandlerMap that are unreferenced.
264 oldToNewHandlerMap->clear();
265 handlerInfo->handlers.clear();
266 for (auto iter = newHandlerMap.begin(); iter != newHandlerMap.end(); /**/) {
267 if (iter->second.expired()) {
268 iter = newHandlerMap.erase(iter);
273 handlerInfo->handlers.swap(newHandlerMap);
276 std::vector<std::shared_ptr<LogHandler>> LoggerDB::buildCategoryHandlerList(
277 const NewHandlerMap& handlerMap,
278 StringPiece categoryName,
279 const std::vector<std::string>& categoryHandlerNames) {
280 std::vector<std::shared_ptr<LogHandler>> catHandlers;
281 for (const auto& handlerName : categoryHandlerNames) {
282 auto iter = handlerMap.find(handlerName);
283 if (iter == handlerMap.end()) {
284 // This really shouldn't be possible; the checks in startConfigUpdate()
285 // should have already bailed out if there was an unknown handler.
286 throw std::invalid_argument(to<std::string>(
287 "bug: unknown log handler \"",
289 "\" configured for log category \"",
293 catHandlers.push_back(iter->second);
299 void LoggerDB::updateConfig(const LogConfig& config) {
300 // Grab the handlerInfo_ lock.
301 // We hold it in write mode for the entire config update operation. This
302 // ensures that only a single config update operation ever runs at once.
303 auto handlerInfo = handlerInfo_.wlock();
305 NewHandlerMap handlers;
306 OldToNewHandlerMap oldToNewHandlerMap;
307 startConfigUpdate(handlerInfo, config, &handlers, &oldToNewHandlerMap);
309 // If an existing LogHandler was replaced with a new one,
310 // walk all current LogCategories and replace this handler.
311 if (!oldToNewHandlerMap.empty()) {
312 auto loggerMap = loggersByName_.rlock();
313 for (const auto& entry : *loggerMap) {
314 entry.second->updateHandlers(oldToNewHandlerMap);
318 // Update log levels and handlers mentioned in the config update
319 auto loggersByName = loggersByName_.wlock();
320 for (const auto& entry : config.getCategoryConfigs()) {
321 LogCategory* category =
322 getOrCreateCategoryLocked(*loggersByName, entry.first);
324 // Update the log handlers
325 if (entry.second.handlers.hasValue()) {
326 auto catHandlers = buildCategoryHandlerList(
327 handlers, entry.first, entry.second.handlers.value());
328 category->replaceHandlers(std::move(catHandlers));
331 // Update the level settings
332 category->setLevelLocked(
333 entry.second.level, entry.second.inheritParentLevel);
336 finishConfigUpdate(handlerInfo, &handlers, &oldToNewHandlerMap);
339 void LoggerDB::resetConfig(const LogConfig& config) {
340 // Grab the handlerInfo_ lock.
341 // We hold it in write mode for the entire config update operation. This
342 // ensures that only a single config update operation ever runs at once.
343 auto handlerInfo = handlerInfo_.wlock();
345 NewHandlerMap handlers;
346 OldToNewHandlerMap oldToNewHandlerMap;
347 startConfigUpdate(handlerInfo, config, &handlers, &oldToNewHandlerMap);
349 // Make sure all log categories mentioned in the new config exist.
350 // This ensures that we will cover them in our walk below.
351 LogCategory* rootCategory;
353 auto loggersByName = loggersByName_.wlock();
354 rootCategory = getOrCreateCategoryLocked(*loggersByName, "");
355 for (const auto& entry : config.getCategoryConfigs()) {
356 getOrCreateCategoryLocked(*loggersByName, entry.first);
361 // Update all log categories
362 auto loggersByName = loggersByName_.rlock();
363 for (const auto& entry : *loggersByName) {
364 auto* category = entry.second.get();
366 auto configIter = config.getCategoryConfigs().find(category->getName());
367 if (configIter == config.getCategoryConfigs().end()) {
368 // This category is not listed in the config settings.
369 // Reset it to the default settings.
370 category->clearHandlers();
372 if (category == rootCategory) {
373 category->setLevelLocked(LogLevel::ERR, false);
375 category->setLevelLocked(LogLevel::MAX_LEVEL, true);
380 const auto& catConfig = configIter->second;
382 // Update the category log level
383 category->setLevelLocked(catConfig.level, catConfig.inheritParentLevel);
385 // Update the category handlers list.
386 // If the handler list is not set in the config, clear out any existing
387 // handlers rather than leaving it as-is.
388 std::vector<std::shared_ptr<LogHandler>> catHandlers;
389 if (catConfig.handlers.hasValue()) {
390 catHandlers = buildCategoryHandlerList(
391 handlers, entry.first, catConfig.handlers.value());
393 category->replaceHandlers(std::move(catHandlers));
397 finishConfigUpdate(handlerInfo, &handlers, &oldToNewHandlerMap);
400 LogCategory* LoggerDB::getOrCreateCategoryLocked(
401 LoggerNameMap& loggersByName,
403 auto it = loggersByName.find(name);
404 if (it != loggersByName.end()) {
405 return it->second.get();
408 StringPiece parentName = LogName::getParent(name);
409 LogCategory* parent = getOrCreateCategoryLocked(loggersByName, parentName);
410 return createCategoryLocked(loggersByName, name, parent);
413 LogCategory* LoggerDB::createCategoryLocked(
414 LoggerNameMap& loggersByName,
416 LogCategory* parent) {
417 auto uptr = std::make_unique<LogCategory>(name, parent);
418 LogCategory* logger = uptr.get();
419 auto ret = loggersByName.emplace(logger->getName(), std::move(uptr));
424 void LoggerDB::cleanupHandlers() {
425 // Get a copy of all categories, so we can call clearHandlers() without
426 // holding the loggersByName_ lock. We don't need to worry about LogCategory
427 // lifetime, since LogCategory objects always live for the lifetime of the
429 std::vector<LogCategory*> categories;
431 auto loggersByName = loggersByName_.wlock();
432 categories.reserve(loggersByName->size());
433 for (const auto& entry : *loggersByName) {
434 categories.push_back(entry.second.get());
438 // Also extract our HandlerFactoryMap and HandlerMap, so we can clear them
439 // later without holding the handlerInfo_ lock.
440 HandlerFactoryMap factories;
443 auto handlerInfo = handlerInfo_.wlock();
444 factories.swap(handlerInfo->factories);
445 handlers.swap(handlerInfo->handlers);
448 // Remove all of the LogHandlers from all log categories,
449 // to drop any shared_ptr references to the LogHandlers
450 for (auto* category : categories) {
451 category->clearHandlers();
455 size_t LoggerDB::flushAllHandlers() {
456 // Build a set of all LogHandlers. We use a set to avoid calling flush()
457 // more than once on the same handler if it is registered on multiple
458 // different categories.
459 std::set<std::shared_ptr<LogHandler>> handlers;
461 auto loggersByName = loggersByName_.wlock();
462 for (const auto& entry : *loggersByName) {
463 for (const auto& handler : entry.second->getHandlers()) {
464 handlers.emplace(handler);
469 // Call flush() on each handler
470 for (const auto& handler : handlers) {
473 return handlers.size();
476 void LoggerDB::registerHandlerFactory(
477 std::unique_ptr<LogHandlerFactory> factory,
478 bool replaceExisting) {
479 auto type = factory->getType();
480 auto handlerInfo = handlerInfo_.wlock();
481 if (replaceExisting) {
482 handlerInfo->factories[type.str()] = std::move(factory);
484 auto ret = handlerInfo->factories.emplace(type.str(), std::move(factory));
486 throw std::range_error(to<std::string>(
487 "a LogHandlerFactory for the type \"", type, "\" already exists"));
492 void LoggerDB::unregisterHandlerFactory(StringPiece type) {
493 auto handlerInfo = handlerInfo_.wlock();
494 auto numRemoved = handlerInfo->factories.erase(type.str());
495 if (numRemoved != 1) {
496 throw std::range_error(
497 to<std::string>("no LogHandlerFactory for type \"", type, "\" found"));
501 LogLevel LoggerDB::xlogInit(
502 StringPiece categoryName,
503 std::atomic<LogLevel>* xlogCategoryLevel,
504 LogCategory** xlogCategory) {
505 // Hold the lock for the duration of the operation
506 // xlogInit() may be called from multiple threads simultaneously.
507 // Only one needs to perform the initialization.
508 auto loggersByName = loggersByName_.wlock();
509 if (xlogCategory != nullptr && *xlogCategory != nullptr) {
510 // The xlogCategory was already initialized before we acquired the lock
511 return (*xlogCategory)->getEffectiveLevel();
514 auto* category = getOrCreateCategoryLocked(*loggersByName, categoryName);
516 // Set *xlogCategory before we update xlogCategoryLevel below.
517 // This is important, since the XLOG() macros check xlogCategoryLevel to
518 // tell if *xlogCategory has been initialized yet.
519 *xlogCategory = category;
521 auto level = category->getEffectiveLevel();
522 xlogCategoryLevel->store(level, std::memory_order_release);
523 category->registerXlogLevel(xlogCategoryLevel);
527 LogCategory* LoggerDB::xlogInitCategory(
528 StringPiece categoryName,
529 LogCategory** xlogCategory,
530 std::atomic<bool>* isInitialized) {
531 // Hold the lock for the duration of the operation
532 // xlogInitCategory() may be called from multiple threads simultaneously.
533 // Only one needs to perform the initialization.
534 auto loggersByName = loggersByName_.wlock();
535 if (isInitialized->load(std::memory_order_acquire)) {
536 // The xlogCategory was already initialized before we acquired the lock
537 return *xlogCategory;
540 auto* category = getOrCreateCategoryLocked(*loggersByName, categoryName);
541 *xlogCategory = category;
542 isInitialized->store(true, std::memory_order_release);
546 std::atomic<LoggerDB::InternalWarningHandler> LoggerDB::warningHandler_;
548 void LoggerDB::internalWarningImpl(
549 folly::StringPiece filename,
551 std::string&& msg) noexcept {
552 auto handler = warningHandler_.load();
554 handler(filename, lineNumber, std::move(msg));
556 defaultInternalWarningImpl(filename, lineNumber, std::move(msg));
560 void LoggerDB::setInternalWarningHandler(InternalWarningHandler handler) {
561 // This API is intentionally pretty basic. It has a number of limitations:
563 // - We only support plain function pointers, and not full std::function
564 // objects. This makes it possible to use std::atomic to access the
565 // handler pointer, and also makes it safe to store in a zero-initialized
566 // file-static pointer.
568 // - We don't support any void* argument to the handler. The caller is
569 // responsible for storing any callback state themselves.
571 // - When replacing or unsetting a handler we don't make any guarantees about
572 // when the old handler will stop being called. It may still be called
573 // from other threads briefly even after setInternalWarningHandler()
574 // returns. This is also a consequence of using std::atomic rather than a
577 // This provides the minimum capabilities needed to customize the handler,
578 // while still keeping the implementation simple and safe to use even before
580 warningHandler_.store(handler);
583 void LoggerDB::defaultInternalWarningImpl(
584 folly::StringPiece filename,
586 std::string&& msg) noexcept {
587 // Rate limit to 10 messages every 5 seconds.
589 // We intentonally use a leaky Meyer's singleton here over folly::Singleton:
590 // - We want this code to work even before main()
591 // - This singleton does not depend on any other singletons.
592 static auto* rateLimiter =
593 new logging::IntervalRateLimiter{10, std::chrono::seconds(5)};
594 if (!rateLimiter->check()) {
598 if (folly::kIsDebug) {
599 // Write directly to file descriptor 2.
601 // It's possible the application has closed fd 2 and is using it for
602 // something other than stderr. However we have no good way to detect
603 // this, which is the main reason we only write to stderr in debug build
604 // modes. assert() also writes directly to stderr on failure, which seems
605 // like a reasonable precedent.
607 // Another option would be to use openlog() and syslog(). However
608 // calling openlog() may inadvertently affect the behavior of other parts
609 // of the program also using syslog().
611 // We don't check for write errors here, since there's not much else we can
613 auto fullMsg = folly::to<std::string>(
614 "logging warning:", filename, ":", lineNumber, ": ", msg, "\n");
615 folly::writeFull(STDERR_FILENO, fullMsg.data(), fullMsg.size());