Added a function to add callbacks that are called when a logger is registered (#2883)

* Added a function to add callbacks that are called when a logger is registered

* Fix non captured registration 2 not being properly tested for

* Replace std::list by std::vector

* Remove const refs to shared pointers

* Fix missing header
This commit is contained in:
Jonathan Vannier
2023-09-25 17:49:04 +02:00
committed by GitHub
parent 0a53eafe18
commit b6eeb7364c
5 changed files with 72 additions and 0 deletions

View File

@@ -259,6 +259,22 @@ SPDLOG_INLINE void registry::register_logger_(std::shared_ptr<logger> new_logger
auto logger_name = new_logger->name();
throw_if_exists_(logger_name);
loggers_[logger_name] = std::move(new_logger);
const auto& logger = loggers_[logger_name];
for (const auto& on_registration_callback : on_registration_callbacks_) {
on_registration_callback(logger);
}
}
SPDLOG_INLINE void registry::add_on_registration_callback(
const std::function<void(std::shared_ptr<logger>)>& callback) {
std::lock_guard<std::mutex> lock(logger_map_mutex_);
on_registration_callbacks_.push_back(callback);
}
SPDLOG_INLINE void registry::drop_all_on_registration_callbacks() {
std::lock_guard<std::mutex> lock(logger_map_mutex_);
on_registration_callbacks_.clear();
}
} // namespace details

View File

@@ -17,6 +17,7 @@
#include <mutex>
#include <string>
#include <unordered_map>
#include <vector>
namespace spdlog {
class logger;
@@ -92,6 +93,10 @@ public:
void apply_logger_env_levels(std::shared_ptr<logger> new_logger);
void add_on_registration_callback(const std::function<void(std::shared_ptr<logger>)>& callback);
void drop_all_on_registration_callbacks();
private:
registry();
~registry();
@@ -112,6 +117,7 @@ private:
std::shared_ptr<logger> default_logger_;
bool automatic_registration_ = true;
size_t backtrace_n_messages_ = 0;
std::vector<std::function<void(std::shared_ptr<logger>)>> on_registration_callbacks_;
};
} // namespace details