logging: make XLOG_GET_CATEGORY() safe for all callers
[folly.git] / folly / experimental / logging / Init.cpp
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 #include <folly/experimental/logging/Init.h>
17
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>
24
25 using std::shared_ptr;
26 using std::string;
27 using std::vector;
28
29 namespace folly {
30
31 void initLogLevels(StringPiece configString, LogLevel defaultRootLevel) {
32   // Set the default root category log level first
33   LoggerDB::get()->getCategory(".")->setLevel(defaultRootLevel);
34
35   // Then apply the configuration string
36   if (!configString.empty()) {
37     auto ret = LoggerDB::get()->processConfigString(configString);
38     if (!ret.empty()) {
39       throw LoggingConfigError(ret);
40     }
41   }
42 }
43
44 void initLoggingGlogStyle(
45     StringPiece configString,
46     LogLevel defaultRootLevel,
47     bool asyncWrites) {
48   // Configure log levels
49   initLogLevels(configString, defaultRootLevel);
50
51   // Create the LogHandler
52   std::shared_ptr<LogWriter> writer;
53   folly::File file{STDERR_FILENO, false};
54   if (asyncWrites) {
55     writer = std::make_shared<AsyncFileWriter>(std::move(file));
56   } else {
57     writer = std::make_shared<ImmediateFileWriter>(std::move(file));
58   }
59   auto handler = std::make_shared<StandardLogHandler>(
60       std::make_shared<GlogStyleFormatter>(), std::move(writer));
61
62   // Add the handler to the root category.
63   LoggerDB::get()->getCategory(".")->addHandler(std::move(handler));
64 }
65
66 LoggingConfigError::LoggingConfigError(const vector<string>& errors)
67     : invalid_argument{computeMessage(errors)} {}
68
69 std::string LoggingConfigError::computeMessage(const vector<string>& errors) {
70   string msg = "error parsing logging configuration:";
71   for (const auto& error : errors) {
72     msg += "\n" + error;
73   }
74   return msg;
75 }
76 }