tcp_sink.h 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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/tcp_client-windows.h>
  9. #else
  10. #include <spdlog/details/tcp_client.h>
  11. #endif
  12. #include <chrono>
  13. #include <functional>
  14. #include <mutex>
  15. #include <string>
  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
  21. // sink_it_ method.
  22. namespace spdlog {
  23. namespace sinks {
  24. struct tcp_sink_config {
  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. template <typename Mutex>
  33. class tcp_sink : public spdlog::sinks::base_sink<Mutex> {
  34. public:
  35. // connect to tcp host/port or throw if failed
  36. // host can be hostname or ip address
  37. explicit tcp_sink(tcp_sink_config sink_config)
  38. : config_{std::move(sink_config)} {
  39. if (!config_.lazy_connect) {
  40. this->client_.connect(config_.server_host, config_.server_port);
  41. }
  42. }
  43. ~tcp_sink() override = default;
  44. protected:
  45. void sink_it_(const spdlog::details::log_msg &msg) override {
  46. spdlog::memory_buf_t formatted;
  47. spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
  48. if (!client_.is_connected()) {
  49. client_.connect(config_.server_host, config_.server_port);
  50. }
  51. client_.send(formatted.data(), formatted.size());
  52. }
  53. void flush_() override {}
  54. tcp_sink_config config_;
  55. details::tcp_client client_;
  56. };
  57. using tcp_sink_mt = tcp_sink<std::mutex>;
  58. using tcp_sink_st = tcp_sink<spdlog::details::null_mutex>;
  59. } // namespace sinks
  60. } // namespace spdlog