76 lines
2.1 KiB
C
Raw Normal View History

2021-07-08 07:07:27 -07:00
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
#include <spdlog/common.h>
#include <spdlog/details/null_mutex.h>
2024-02-04 13:43:17 +01:00
#include <spdlog/sinks/base_sink.h>
2021-07-08 07:07:27 -07:00
#ifdef _WIN32
2024-02-04 13:43:17 +01:00
#include <spdlog/details/tcp_client-windows.h>
2021-07-08 07:07:27 -07:00
#else
2024-02-04 13:43:17 +01:00
#include <spdlog/details/tcp_client.h>
2021-07-08 07:07:27 -07:00
#endif
#include <chrono>
#include <functional>
2024-02-04 13:43:17 +01:00
#include <mutex>
#include <string>
2021-07-08 07:07:27 -07:00
#pragma once
// Simple tcp client sink
// Connects to remote address and send the formatted log.
// Will attempt to reconnect if connection drops.
2024-02-04 13:43:17 +01:00
// If more complicated behaviour is needed (i.e get responses), you can inherit it and override the
// sink_it_ method.
2021-07-08 07:07:27 -07:00
namespace spdlog {
namespace sinks {
2024-02-04 13:43:17 +01:00
struct tcp_sink_config {
2021-07-08 07:07:27 -07:00
std::string server_host;
int server_port;
2024-02-04 13:43:17 +01:00
bool lazy_connect = false; // if true connect on first log call instead of on construction
2021-07-08 07:07:27 -07:00
tcp_sink_config(std::string host, int port)
2024-02-04 13:43:17 +01:00
: server_host{std::move(host)},
server_port{port} {}
2021-07-08 07:07:27 -07:00
};
2024-02-04 13:43:17 +01:00
template <typename Mutex>
class tcp_sink : public spdlog::sinks::base_sink<Mutex> {
2021-07-08 07:07:27 -07:00
public:
// connect to tcp host/port or throw if failed
// host can be hostname or ip address
explicit tcp_sink(tcp_sink_config sink_config)
2024-02-04 13:43:17 +01:00
: config_{std::move(sink_config)} {
if (!config_.lazy_connect) {
2021-07-08 07:07:27 -07:00
this->client_.connect(config_.server_host, config_.server_port);
}
}
~tcp_sink() override = default;
protected:
2024-02-04 13:43:17 +01:00
void sink_it_(const spdlog::details::log_msg &msg) override {
2021-07-08 07:07:27 -07:00
spdlog::memory_buf_t formatted;
spdlog::sinks::base_sink<Mutex>::formatter_->format(msg, formatted);
2024-02-04 13:43:17 +01:00
if (!client_.is_connected()) {
2021-07-08 07:07:27 -07:00
client_.connect(config_.server_host, config_.server_port);
}
client_.send(formatted.data(), formatted.size());
}
void flush_() override {}
tcp_sink_config config_;
details::tcp_client client_;
};
using tcp_sink_mt = tcp_sink<std::mutex>;
using tcp_sink_st = tcp_sink<spdlog::details::null_mutex>;
2024-02-04 13:43:17 +01:00
} // namespace sinks
} // namespace spdlog