diff options
author | Sandor Magyar <SMagyar@aphysci.com> | 2022-10-18 00:32:08 +0300 |
---|---|---|
committer | Sandor Magyar <SMagyar@aphysci.com> | 2022-10-18 00:32:08 +0300 |
commit | a3c47cc6823d017056b4790db88769fc6f6f40de (patch) | |
tree | 44b8a64a0c6208379396dc5400ed9bcbe38d8f9f | |
parent | 0145223be1c3b115e562603881af2832505fe496 (diff) |
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.
-rw-r--r-- | include/spdlog/sinks/mongo_sink.h | 20 |
1 files 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 <bsoncxx/view_or_value.hpp> #include <mongocxx/client.hpp> +#include <mongocxx/exception/logic_error.hpp> #include <mongocxx/instance.hpp> #include <mongocxx/uri.hpp> @@ -29,10 +30,23 @@ template<typename Mutex> class mongo_sink : public base_sink<Mutex> { 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<mongocxx::instance>(); + } + 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::client>(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<mongocxx::instance> instance_; std::string db_name_; std::string coll_name_; std::unique_ptr<mongocxx::client> client_ = nullptr; }; template<> -mongocxx::instance mongo_sink<std::mutex>::instance_{}; +std::shared_ptr<mongocxx::instance> mongo_sink<std::mutex>::instance_{}; #include "spdlog/details/null_mutex.h" #include <mutex> |