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/Init.h>
18 #include <folly/experimental/logging/AsyncFileWriter.h>
19 #include <folly/experimental/logging/GlogStyleFormatter.h>
20 #include <folly/experimental/logging/ImmediateFileWriter.h>
21 #include <folly/experimental/logging/LogCategory.h>
22 #include <folly/experimental/logging/LoggerDB.h>
23 #include <folly/experimental/logging/StandardLogHandler.h>
25 using std::shared_ptr;
31 void initLogLevels(StringPiece configString, LogLevel defaultRootLevel) {
32 // Set the default root category log level first
33 LoggerDB::get()->getCategory(".")->setLevel(defaultRootLevel);
35 // Then apply the configuration string
36 if (!configString.empty()) {
37 auto ret = LoggerDB::get()->processConfigString(configString);
39 throw LoggingConfigError(ret);
44 void initLoggingGlogStyle(
45 StringPiece configString,
46 LogLevel defaultRootLevel,
48 // Configure log levels
49 initLogLevels(configString, defaultRootLevel);
51 // Create the LogHandler
52 std::shared_ptr<LogWriter> writer;
53 folly::File file{STDERR_FILENO, false};
55 writer = std::make_shared<AsyncFileWriter>(std::move(file));
57 writer = std::make_shared<ImmediateFileWriter>(std::move(file));
59 auto handler = std::make_shared<StandardLogHandler>(
60 std::make_shared<GlogStyleFormatter>(), std::move(writer));
62 // Add the handler to the root category.
63 LoggerDB::get()->getCategory(".")->addHandler(std::move(handler));
66 LoggingConfigError::LoggingConfigError(const vector<string>& errors)
67 : invalid_argument{computeMessage(errors)} {}
69 std::string LoggingConfigError::computeMessage(const vector<string>& errors) {
70 string msg = "error parsing logging configuration:";
71 for (const auto& error : errors) {