1// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
2// Distributed under the MIT License (http://opensource.org/licenses/MIT)
3
4#pragma once
5
6#include <spdlog/common.h>
7#include <spdlog/sinks/base_sink.h>
8#include <spdlog/details/null_mutex.h>
9#ifdef _WIN32
10# include <spdlog/details/udp_client-windows.h>
11#else
12# include <spdlog/details/udp_client.h>
13#endif
14
15#include <mutex>
16#include <string>
17#include <chrono>
18#include <functional>
19
20// Simple udp client sink
21// Sends formatted log via udp
22
23namespace spdlog {
24namespace sinks {
25
26struct udp_sink_config
27{
28 std::string server_host;
29 uint16_t server_port;
30
31 udp_sink_config(std::string host, uint16_t port)
32 : server_host{std::move(host)}
33 , server_port{port}
34 {}
35};
36
37template<typename Mutex>
38class udp_sink : public spdlog::sinks::base_sink<Mutex>
39{
40public:
41 // host can be hostname or ip address
42 explicit udp_sink(udp_sink_config sink_config)
43 : client_{sink_config.server_host, sink_config.server_port}
44 {}
45
46 ~udp_sink() override = default;
47
48protected:
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 client_.send(formatted.data(), formatted.size());
54 }
55
56 void flush_() override {}
57 details::udp_client client_;
58};
59
60using udp_sink_mt = udp_sink<std::mutex>;
61using udp_sink_st = udp_sink<spdlog::details::null_mutex>;
62
63} // namespace sinks
64
65//
66// factory functions
67//
68template<typename Factory = spdlog::synchronous_factory>
69inline std::shared_ptr<logger> udp_logger_mt(const std::string &logger_name, sinks::udp_sink_config skin_config)
70{
71 return Factory::template create<sinks::udp_sink_mt>(logger_name, skin_config);
72}
73
74} // namespace spdlog
75