From a3c47cc6823d017056b4790db88769fc6f6f40de Mon Sep 17 00:00:00 2001 From: Sandor Magyar Date: Mon, 17 Oct 2022 17:32:08 -0400 Subject: [PATCH] Don't force Mongo sink to own MongoCXX instance There can only be one instance in the whole program, so programs that use the Mongo sink and also separately use MongoCXX may have problems if the Mongo sink owns the instance. MongoCXX recommends that the main application manage its own instance so configuration parameters can be passed to the constructor: http://mongocxx.org/api/current/classmongocxx_1_1instance.html However, this commit is not a breaking change. If no instance has been created at construction time, the Mongo sink will still create and own the instance. --- include/spdlog/sinks/mongo_sink.h | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/include/spdlog/sinks/mongo_sink.h b/include/spdlog/sinks/mongo_sink.h index 1338983c..ab8a5b4d 100644 --- a/include/spdlog/sinks/mongo_sink.h +++ b/include/spdlog/sinks/mongo_sink.h @@ -20,6 +20,7 @@ #include #include +#include #include #include @@ -29,10 +30,23 @@ template class mongo_sink : public base_sink { public: - mongo_sink(const std::string &db_name, const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017") + mongo_sink(const std::string &db_name, const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017", + bool create_instance = true) { try { + if (create_instance && !instance_) + { + try + { + instance_ = std::make_shared(); + } + catch (const mongocxx::logic_error&) + { + // A MongoCXX instance already exists, so this object doesn't need to own it + instance_ = nullptr; + } + } client_ = spdlog::details::make_unique(mongocxx::uri{uri}); db_name_ = db_name; coll_name_ = collection_name; @@ -68,13 +82,13 @@ protected: void flush_() override {} private: - static mongocxx::instance instance_; + static std::shared_ptr instance_; std::string db_name_; std::string coll_name_; std::unique_ptr client_ = nullptr; }; template<> -mongocxx::instance mongo_sink::instance_{}; +std::shared_ptr mongo_sink::instance_{}; #include "spdlog/details/null_mutex.h" #include