udp_sink.h 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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/common.h>
  5. #include <spdlog/sinks/base_sink.h>
  6. #include <spdlog/details/null_mutex.h>
  7. #ifdef _WIN32
  8. # include <spdlog/details/udp_client-windows.h>
  9. #else
  10. # include <spdlog/details/udp_client.h>
  11. #endif
  12. #include <mutex>
  13. #include <string>
  14. #include <chrono>
  15. #include <functional>
  16. // Simple udp client sink
  17. // Sends formatted log via udp
  18. namespace spdlog {
  19. namespace sinks {
  20. struct udp_sink_config
  21. {
  22. std::string server_host;
  23. uint16_t server_port;
  24. udp_sink_config(std::string host, uint16_t port)
  25. : server_host{std::move(host)}
  26. , server_port{port}
  27. {}
  28. };
  29. template<typename Mutex>
  30. class udp_sink : public spdlog::sinks::base_sink<Mutex>
  31. {
  32. public:
  33. // host can be hostname or ip address
  34. explicit udp_sink(udp_sink_config sink_config)
  35. : client_{sink_config.server_host, sink_config.server_port}
  36. {}
  37. ~udp_sink() override = default;
  38. protected:
  39. void sink_it_(const spdlog::details::log_msg &msg) override
  40. {
  41. spdlog::memory_buf_t formatted;
  42. spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
  43. client_.send(formatted.data(), formatted.size());
  44. }
  45. void flush_() override {}
  46. details::udp_client client_;
  47. };
  48. using udp_sink_mt = udp_sink<std::mutex>;
  49. using udp_sink_st = udp_sink<spdlog::details::null_mutex>;
  50. } // namespace sinks
  51. //
  52. // factory functions
  53. //
  54. template<typename Factory = spdlog::synchronous_factory>
  55. inline std::shared_ptr<logger> udp_logger_mt(const std::string &logger_name, sinks::udp_sink_config skin_config)
  56. {
  57. return Factory::template create<sinks::udp_sink_mt>(logger_name, skin_config);
  58. }
  59. } // namespace spdlog