StreamHandlerFactory.cpp 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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/StreamHandlerFactory.h>
  17. #include <folly/Conv.h>
  18. #include <folly/logging/FileWriterFactory.h>
  19. #include <folly/logging/StandardLogHandler.h>
  20. #include <folly/logging/StandardLogHandlerFactory.h>
  21. namespace folly {
  22. class StreamHandlerFactory::WriterFactory
  23. : public StandardLogHandlerFactory::WriterFactory {
  24. public:
  25. bool processOption(StringPiece name, StringPiece value) override {
  26. if (name == "stream") {
  27. stream_ = value.str();
  28. return true;
  29. }
  30. return fileWriterFactory_.processOption(name, value);
  31. }
  32. std::shared_ptr<LogWriter> createWriter() override {
  33. // Get the output file to use
  34. File outputFile;
  35. if (stream_.empty()) {
  36. throw std::invalid_argument(
  37. "no stream name specified for stream handler");
  38. } else if (stream_ == "stderr") {
  39. outputFile = File{STDERR_FILENO, /* ownsFd */ false};
  40. } else if (stream_ == "stdout") {
  41. outputFile = File{STDOUT_FILENO, /* ownsFd */ false};
  42. } else {
  43. throw std::invalid_argument(to<std::string>(
  44. "unknown stream \"",
  45. stream_,
  46. "\": expected one of stdout or stderr"));
  47. }
  48. return fileWriterFactory_.createWriter(std::move(outputFile));
  49. }
  50. std::string stream_;
  51. FileWriterFactory fileWriterFactory_;
  52. };
  53. std::shared_ptr<LogHandler> StreamHandlerFactory::createHandler(
  54. const Options& options) {
  55. WriterFactory writerFactory;
  56. return StandardLogHandlerFactory::createHandler(
  57. getType(), &writerFactory, options);
  58. }
  59. } // namespace folly