udp_sink.h 1.8 KB

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