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