From 1bb1f05d73abc99f5c245052c997cd0bda2a31d6 Mon Sep 17 00:00:00 2001 From: Sandor Magyar Date: Tue, 18 Oct 2022 20:13:17 -0400 Subject: [PATCH] Adjust MongoCXX instance handling in mongo_sink Changes suggested by @gabime on #2519 --- include/spdlog/sinks/mongo_sink.h | 28 +++++++++------------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/include/spdlog/sinks/mongo_sink.h b/include/spdlog/sinks/mongo_sink.h index ab8a5b4d..b8928d67 100644 --- a/include/spdlog/sinks/mongo_sink.h +++ b/include/spdlog/sinks/mongo_sink.h @@ -30,26 +30,18 @@ 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", - bool create_instance = true) + mongo_sink(const std::string &db_name, const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017") + try : mongo_sink(std::make_shared(), db_name, collection_name, uri) {} + catch (...) {} // Re-throws exception + + mongo_sink(const std::shared_ptr &instance, const std::string &db_name, const std::string &collection_name, const std::string &uri = "mongodb://localhost:27017") + : instance_(instance) + , db_name_(db_name) + , coll_name_(collection_name) { 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; } catch (const std::exception&) { @@ -82,13 +74,11 @@ protected: void flush_() override {} private: - static std::shared_ptr instance_; + std::shared_ptr instance_; std::string db_name_; std::string coll_name_; std::unique_ptr client_ = nullptr; }; -template<> -std::shared_ptr mongo_sink::instance_{}; #include "spdlog/details/null_mutex.h" #include