Added relay_sink.

This commit is contained in:
Richard Musil 2024-02-18 15:14:18 +01:00
parent 134f9194bb
commit 2b110a8bca
4 changed files with 64 additions and 0 deletions

View File

@ -125,6 +125,15 @@ public:
void log(level::level_enum lvl, string_view_t msg) { log(source_loc{}, lvl, msg); } void log(level::level_enum lvl, string_view_t msg) { log(source_loc{}, lvl, msg); }
void log_raw(const details::log_msg &log_msg) {
bool log_enabled = should_log(log_msg.level);
bool traceback_enabled = tracer_.enabled();
if (!log_enabled && !traceback_enabled) {
return;
}
log_it_(log_msg, log_enabled, traceback_enabled);
}
template <typename... Args> template <typename... Args>
void trace(format_string_t<Args...> fmt, Args &&...args) { void trace(format_string_t<Args...> fmt, Args &&...args) {
log(level::trace, fmt, std::forward<Args>(args)...); log(level::trace, fmt, std::forward<Args>(args)...);

View File

@ -0,0 +1,35 @@
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
#pragma once
//
// Sink to wrap another logger. This is usefull when consolidating multiple application components
// with built-in loggers into one app wide logger.
//
#include <spdlog/sinks/base_sink.h>
#include <spdlog/logger.h>
namespace spdlog {
namespace sinks {
template <typename Mutex>
class relay_sink : public base_sink<Mutex> {
public:
relay_sink(const std::shared_ptr<spdlog::logger>& logger)
: m_logger{logger} {}
protected:
void sink_it_(const spdlog::details::log_msg& msg) override { m_logger->log_raw(msg); };
void flush_() override{};
private:
std::shared_ptr<spdlog::logger> m_logger;
};
using relay_sink_mt = relay_sink<std::mutex>;
using relay_sink_st = relay_sink<spdlog::details::null_mutex>;
} // namespace sinks
} // namespace spdlog

View File

@ -34,6 +34,7 @@ set(SPDLOG_UTESTS_SOURCES
test_eventlog.cpp test_eventlog.cpp
test_pattern_formatter.cpp test_pattern_formatter.cpp
test_async.cpp test_async.cpp
test_relay_sink.cpp
test_registry.cpp test_registry.cpp
test_macros.cpp test_macros.cpp
utils.cpp utils.cpp

19
tests/test_relay_sink.cpp Normal file
View File

@ -0,0 +1,19 @@
#include "includes.h"
#include "spdlog/sinks/relay_sink.h"
#include "spdlog/logger.h"
#include "test_sink.h"
TEST_CASE("relay_sink_test1", "[relay_sink]") {
using spdlog::sinks::relay_sink_st;
using spdlog::sinks::test_sink_mt;
auto test_sink = std::make_shared<test_sink_mt>();
auto remote_logger = std::make_shared<spdlog::logger>("remote", test_sink);
auto relay_sink = std::make_shared<relay_sink_st>(remote_logger);
for (int i = 0; i < 10; i++) {
relay_sink->log(spdlog::details::log_msg{"test", spdlog::level::info, "message1"});
}
REQUIRE(test_sink->msg_counter() == 10);
}