callback_sink.h 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #include <spdlog/details/null_mutex.h>
  5. #include <spdlog/sinks/base_sink.h>
  6. #include <spdlog/details/synchronous_factory.h>
  7. #include <mutex>
  8. #include <string>
  9. namespace spdlog {
  10. // callbacks type
  11. typedef std::function<void(const details::log_msg &msg)> custom_log_callback;
  12. namespace sinks {
  13. /*
  14. * Trivial callback sink, gets a callback function and calls it on each log
  15. */
  16. template<typename Mutex>
  17. class callback_sink final : public base_sink<Mutex>
  18. {
  19. public:
  20. explicit callback_sink(const custom_log_callback &callback)
  21. : callback_{callback}
  22. {}
  23. protected:
  24. void sink_it_(const details::log_msg &msg) override
  25. {
  26. callback_(msg);
  27. }
  28. void flush_() override{};
  29. private:
  30. custom_log_callback callback_;
  31. };
  32. using callback_sink_mt = callback_sink<std::mutex>;
  33. using callback_sink_st = callback_sink<details::null_mutex>;
  34. } // namespace sinks
  35. //
  36. // factory functions
  37. //
  38. template<typename Factory = spdlog::synchronous_factory>
  39. inline std::shared_ptr<logger> callback_logger_mt(const std::string &logger_name, const custom_log_callback &callback)
  40. {
  41. return Factory::template create<sinks::callback_sink_mt>(logger_name, callback);
  42. }
  43. template<typename Factory = spdlog::synchronous_factory>
  44. inline std::shared_ptr<logger> callback_logger_st(const std::string &logger_name, const custom_log_callback &callback)
  45. {
  46. return Factory::template create<sinks::callback_sink_st>(logger_name, callback);
  47. }
  48. } // namespace spdlog