| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- //
- // stdout_logger.cpp
- // logger
- //
- // Created by Sam Jaffe on 10/2/15.
- //
- //
- #include <iostream>
- #include <stdexcept>
- #include "logger.hpp"
- #include "default_logger_binding.hpp"
- #include "properties.hpp"
- namespace logging {
-
- namespace {
- std::string validate_or_throw(logging::properties const& props) {
- if (props.type != properties::OBJECT) {
- throw std::logic_error{"expected properties to be a map"};
- }
- auto it = props.obj.find("target");
- if (it == props.obj.end()) {
- throw std::logic_error{"expected a console target entry"};
- } else if (it->second.type != properties::STRING) {
- throw std::logic_error{"expected properties[\"target\"] to be a string"};
- }
- return it->second.value;
- }
- }
-
- class console_logger : public logger_impl {
- public:
- static std::unique_ptr<logger_impl> create(properties const& props);
-
- console_logger(std::ostream& os);
-
- void write(log_level level, std::string const& msg) override;
-
- void flush() override;
- private:
- std::ostream& out_;
- };
-
- std::unique_ptr<logger_impl> console_logger::create(properties const& props) {
- const std::string target = validate_or_throw(props);
- if (target == "SYSTEM_OUT") {
- return std::unique_ptr<logger_impl>(new console_logger(std::cout));
- } else if (target == "SYSTEM_ERR") {
- return std::unique_ptr<logger_impl>(new console_logger(std::cerr));
- } else {
- throw std::logic_error{target + " is not a valid console"};
- }
- }
-
- console_logger::console_logger(std::ostream& os) : out_(os) {}
-
- void console_logger::write(log_level level, std::string const& msg) {
- out_ << msg;
- }
-
- void console_logger::flush() {
- out_.flush();
- }
-
- namespace {
- bool _ = default_logger_impl::register_impl("Console", console_logger::create);
- }
- }
|