console_logger.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. //
  2. // stdout_logger.cpp
  3. // logger
  4. //
  5. // Created by Sam Jaffe on 10/2/15.
  6. //
  7. //
  8. #include <iostream>
  9. #include <stdexcept>
  10. #include "logger.hpp"
  11. #include "default_logger_binding.hpp"
  12. #include "properties.hpp"
  13. namespace logging {
  14. namespace {
  15. std::string validate_or_throw(logging::properties const& props) {
  16. if (props.type != properties::OBJECT) {
  17. throw std::logic_error{"expected properties to be a map"};
  18. }
  19. auto it = props.obj.find("target");
  20. if (it == props.obj.end()) {
  21. throw std::logic_error{"expected a console target entry"};
  22. } else if (it->second.type != properties::STRING) {
  23. throw std::logic_error{"expected properties[\"target\"] to be a string"};
  24. }
  25. return it->second.value;
  26. }
  27. }
  28. class console_logger : public logger_impl {
  29. public:
  30. static std::unique_ptr<logger_impl> create(properties const& props);
  31. console_logger(std::ostream& os);
  32. void write(log_level level, std::string const& msg) override;
  33. void flush() override;
  34. private:
  35. std::ostream& out_;
  36. };
  37. std::unique_ptr<logger_impl> console_logger::create(properties const& props) {
  38. const std::string target = validate_or_throw(props);
  39. if (target == "SYSTEM_OUT") {
  40. return std::unique_ptr<logger_impl>(new console_logger(std::cout));
  41. } else if (target == "SYSTEM_ERR") {
  42. return std::unique_ptr<logger_impl>(new console_logger(std::cerr));
  43. } else {
  44. throw std::logic_error{target + " is not a valid console"};
  45. }
  46. }
  47. console_logger::console_logger(std::ostream& os) : out_(os) {}
  48. void console_logger::write(log_level level, std::string const& msg) {
  49. out_ << msg;
  50. }
  51. void console_logger::flush() {
  52. out_.flush();
  53. }
  54. namespace {
  55. bool _ = default_logger_impl::register_impl("Console", console_logger::create);
  56. }
  57. }