diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index f49bdc00..4c77c711 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -125,6 +125,15 @@ public: 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 void trace(format_string_t fmt, Args &&...args) { log(level::trace, fmt, std::forward(args)...); diff --git a/include/spdlog/sinks/relay_sink.h b/include/spdlog/sinks/relay_sink.h new file mode 100644 index 00000000..1c17df09 --- /dev/null +++ b/include/spdlog/sinks/relay_sink.h @@ -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 +#include + +namespace spdlog { +namespace sinks { + +template +class relay_sink : public base_sink { +public: + relay_sink(const std::shared_ptr& 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 m_logger; +}; + +using relay_sink_mt = relay_sink; +using relay_sink_st = relay_sink; + +} // namespace sinks +} // namespace spdlog diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8300887a..899b149d 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -34,6 +34,7 @@ set(SPDLOG_UTESTS_SOURCES test_eventlog.cpp test_pattern_formatter.cpp test_async.cpp + test_relay_sink.cpp test_registry.cpp test_macros.cpp utils.cpp diff --git a/tests/test_relay_sink.cpp b/tests/test_relay_sink.cpp new file mode 100644 index 00000000..69b754d1 --- /dev/null +++ b/tests/test_relay_sink.cpp @@ -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(); + auto remote_logger = std::make_shared("remote", test_sink); + auto relay_sink = std::make_shared(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); +}