diff --git a/include/spdlog/sinks/lambda_sink.h b/include/spdlog/sinks/lambda_sink.h new file mode 100644 index 00000000..ad07e529 --- /dev/null +++ b/include/spdlog/sinks/lambda_sink.h @@ -0,0 +1,64 @@ +// Copyright(c) 2015-present, Gabi Melman, mguludag and spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +// +// Custom sink for your own lambda functions or functors +// + +#include "spdlog/common.h" +#include "spdlog/details/log_msg.h" +#include "spdlog/details/synchronous_factory.h" +#include "spdlog/sinks/base_sink.h" + +#include + +// +// lambda_sink class +// +namespace spdlog { +namespace sinks { +template +class lambda_sink : public base_sink +{ +public: + explicit lambda_sink(const std::function& f) : f_(f) { } + + ~lambda_sink() { flush_(); } + +protected: + void sink_it_(const details::log_msg &msg) override + { + memory_buf_t formatted; + base_sink::formatter_->format(msg, formatted); + f_(formatted.data(), formatted.size()); + } + + void flush_() override {} + +private: + std::function f_; +}; + +#include "spdlog/details/null_mutex.h" +#include +using lambda_sink_mt = lambda_sink; +using lambda_sink_st = lambda_sink; +} // namespace sinks + +// +// Factory functions +// +template +inline std::shared_ptr +lambda_logger_mt(const std::string &logger_name, const std::function& f) { + return Factory::template create(logger_name, f); +} + +template +inline std::shared_ptr +lambda_logger_st(const std::string &logger_name, const std::function& f) { + return Factory::template create(logger_name, f); +} +} // namespace spdlog