FileWriterFactory.cpp 1.9 KB

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