logging: add LoggerDB::updateConfig() and resetConfig()
[folly.git] / folly / experimental / logging / test / TestLogHandler.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 <map>
19 #include <string>
20 #include <utility>
21 #include <vector>
22
23 #include <folly/experimental/logging/LogHandler.h>
24 #include <folly/experimental/logging/LogHandlerConfig.h>
25 #include <folly/experimental/logging/LogHandlerFactory.h>
26 #include <folly/experimental/logging/LogMessage.h>
27
28 namespace folly {
29
30 /**
31  * A LogHandler that simply keeps a vector of all LogMessages it receives.
32  *
33  * This class is not thread-safe.  It is intended to be used in single-threaded
34  * tests.
35  */
36 class TestLogHandler : public LogHandler {
37  public:
38   using Options = LogHandlerConfig::Options;
39
40   TestLogHandler() : config_{"test"} {}
41   explicit TestLogHandler(LogHandlerConfig config)
42       : config_{std::move(config)} {}
43
44   std::vector<std::pair<LogMessage, const LogCategory*>>& getMessages() {
45     return messages_;
46   }
47
48   void handleMessage(
49       const LogMessage& message,
50       const LogCategory* handlerCategory) override {
51     messages_.emplace_back(message, handlerCategory);
52   }
53
54   void flush() override {
55     ++flushCount_;
56   }
57
58   uint64_t getFlushCount() const {
59     return flushCount_;
60   }
61
62   LogHandlerConfig getConfig() const override {
63     return config_;
64   }
65
66   void setOptions(const Options& options) {
67     config_.options = options;
68   }
69
70  protected:
71   std::vector<std::pair<LogMessage, const LogCategory*>> messages_;
72   uint64_t flushCount_{0};
73   std::map<std::string, std::string> options_;
74   LogHandlerConfig config_;
75 };
76
77 /**
78  * A LogHandlerFactory to create TestLogHandler objects.
79  */
80 class TestLogHandlerFactory : public LogHandlerFactory {
81  public:
82   explicit TestLogHandlerFactory(StringPiece type) : type_{type.str()} {}
83
84   StringPiece getType() const override {
85     return type_;
86   }
87
88   std::shared_ptr<LogHandler> createHandler(const Options& options) override;
89
90   std::shared_ptr<LogHandler> updateHandler(
91       const std::shared_ptr<LogHandler>& existingHandler,
92       const Options& options) override;
93
94  private:
95   std::string type_;
96 };
97
98 } // namespace folly