callback_sink.h 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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/details/synchronous_factory.h>
  6. #include <spdlog/sinks/base_sink.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. public:
  19. explicit callback_sink(const custom_log_callback &callback)
  20. : callback_{callback} {}
  21. protected:
  22. void sink_it_(const details::log_msg &msg) override { callback_(msg); }
  23. void flush_() override{};
  24. private:
  25. custom_log_callback callback_;
  26. };
  27. using callback_sink_mt = callback_sink<std::mutex>;
  28. using callback_sink_st = callback_sink<details::null_mutex>;
  29. } // namespace sinks
  30. //
  31. // factory functions
  32. //
  33. template <typename Factory = spdlog::synchronous_factory>
  34. inline std::shared_ptr<logger> callback_logger_mt(const std::string &logger_name,
  35. const custom_log_callback &callback) {
  36. return Factory::template create<sinks::callback_sink_mt>(logger_name, callback);
  37. }
  38. template <typename Factory = spdlog::synchronous_factory>
  39. inline std::shared_ptr<logger> callback_logger_st(const std::string &logger_name,
  40. const custom_log_callback &callback) {
  41. return Factory::template create<sinks::callback_sink_st>(logger_name, callback);
  42. }
  43. } // namespace spdlog