tcp_sink.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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/tcp_client-windows.h>
  9. #else
  10. # include <spdlog/details/tcp_client.h>
  11. #endif
  12. #include <mutex>
  13. #include <string>
  14. #include <chrono>
  15. #include <functional>
  16. #pragma once
  17. // Simple tcp client sink
  18. // Connects to remote address and send the formatted log.
  19. // Will attempt to reconnect if connection drops.
  20. // If more complicated behaviour is needed (i.e get responses), you can inherit it and override the sink_it_ method.
  21. namespace spdlog {
  22. namespace sinks {
  23. struct tcp_sink_config
  24. {
  25. std::string server_host;
  26. int server_port;
  27. bool lazy_connect = false; // if true connect on first log call instead of on construction
  28. tcp_sink_config(std::string host, int port)
  29. : server_host{std::move(host)}
  30. , server_port{port}
  31. {}
  32. };
  33. template<typename Mutex>
  34. class tcp_sink : public spdlog::sinks::base_sink<Mutex>
  35. {
  36. public:
  37. // connect to tcp host/port or throw if failed
  38. // host can be hostname or ip address
  39. explicit tcp_sink(tcp_sink_config sink_config)
  40. : config_{std::move(sink_config)}
  41. {
  42. if (!config_.lazy_connect)
  43. {
  44. this->client_.connect(config_.server_host, config_.server_port);
  45. }
  46. }
  47. ~tcp_sink() override = default;
  48. protected:
  49. void sink_it_(const spdlog::details::log_msg &msg) override
  50. {
  51. spdlog::memory_buf_t formatted;
  52. spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
  53. if (!client_.is_connected())
  54. {
  55. client_.connect(config_.server_host, config_.server_port);
  56. }
  57. client_.send(formatted.data(), formatted.size());
  58. }
  59. void flush_() override {}
  60. tcp_sink_config config_;
  61. details::tcp_client client_;
  62. };
  63. using tcp_sink_mt = tcp_sink<std::mutex>;
  64. using tcp_sink_st = tcp_sink<spdlog::details::null_mutex>;
  65. } // namespace sinks
  66. } // namespace spdlog