logging: split FileHandlerFactory into two classes
[folly.git] / folly / experimental / logging / FileWriterFactory.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/FileWriterFactory.h>
17
18 #include <folly/Conv.h>
19 #include <folly/File.h>
20 #include <folly/experimental/logging/AsyncFileWriter.h>
21 #include <folly/experimental/logging/ImmediateFileWriter.h>
22
23 using std::make_shared;
24 using std::string;
25
26 namespace folly {
27
28 bool FileWriterFactory::processOption(StringPiece name, StringPiece value) {
29   if (name == "async") {
30     async_ = to<bool>(value);
31     return true;
32   } else if (name == "max_buffer_size") {
33     auto size = to<size_t>(value);
34     if (size == 0) {
35       throw std::invalid_argument(to<string>("must be a positive integer"));
36     }
37     maxBufferSize_ = size;
38     return true;
39   } else {
40     return false;
41   }
42 }
43
44 std::shared_ptr<LogWriter> FileWriterFactory::createWriter(File file) {
45   // Determine whether we should use ImmediateFileWriter or AsyncFileWriter
46   if (async_) {
47     auto asyncWriter = make_shared<AsyncFileWriter>(std::move(file));
48     if (maxBufferSize_.hasValue()) {
49       asyncWriter->setMaxBufferSize(maxBufferSize_.value());
50     }
51     return asyncWriter;
52   } else {
53     if (maxBufferSize_.hasValue()) {
54       throw std::invalid_argument(to<string>(
55           "the \"max_buffer_size\" option is only valid for async file "
56           "handlers"));
57     }
58     return make_shared<ImmediateFileWriter>(std::move(file));
59   }
60 }
61
62 } // namespace folly