File indexing completed on 2025-12-17 10:29:03
0001
0002
0003
0004 #pragma once
0005
0006 #include <spdlog/common.h>
0007 #include <spdlog/details/null_mutex.h>
0008 #include <spdlog/sinks/base_sink.h>
0009 #ifdef _WIN32
0010 #include <spdlog/details/tcp_client-windows.h>
0011 #else
0012 #include <spdlog/details/tcp_client.h>
0013 #endif
0014
0015 #include <chrono>
0016 #include <functional>
0017 #include <mutex>
0018 #include <string>
0019
0020 #pragma once
0021
0022
0023
0024
0025
0026
0027
0028 namespace spdlog {
0029 namespace sinks {
0030
0031 struct tcp_sink_config {
0032 std::string server_host;
0033 int server_port;
0034 bool lazy_connect = false;
0035
0036 tcp_sink_config(std::string host, int port)
0037 : server_host{std::move(host)},
0038 server_port{port} {}
0039 };
0040
0041 template <typename Mutex>
0042 class tcp_sink : public spdlog::sinks::base_sink<Mutex> {
0043 public:
0044
0045
0046
0047 explicit tcp_sink(tcp_sink_config sink_config)
0048 : config_{std::move(sink_config)} {
0049 if (!config_.lazy_connect) {
0050 this->client_.connect(config_.server_host, config_.server_port);
0051 }
0052 }
0053
0054 ~tcp_sink() override = default;
0055
0056 protected:
0057 void sink_it_(const spdlog::details::log_msg &msg) override {
0058 spdlog::memory_buf_t formatted;
0059 spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
0060 if (!client_.is_connected()) {
0061 client_.connect(config_.server_host, config_.server_port);
0062 }
0063 client_.send(formatted.data(), formatted.size());
0064 }
0065
0066 void flush_() override {}
0067 tcp_sink_config config_;
0068 details::tcp_client client_;
0069 };
0070
0071 using tcp_sink_mt = tcp_sink<std::mutex>;
0072 using tcp_sink_st = tcp_sink<spdlog::details::null_mutex>;
0073
0074 }
0075 }