From 51bcff820e40a6d26c684284509a9fcf27b10c0a Mon Sep 17 00:00:00 2001 From: afshinpir Date: Sat, 25 Feb 2023 13:37:33 +0330 Subject: [PATCH] Added `apply_logger_env_levels` (#2649) This method applies levels which is set by environment variable `SPDLOG_LEVEL` to the a single controller. Usefull for loading configuration into manually created loggers. --- include/spdlog/details/registry-inl.h | 8 ++++++++ include/spdlog/details/registry.h | 2 ++ include/spdlog/spdlog-inl.h | 5 +++++ include/spdlog/spdlog.h | 9 +++++++++ 4 files changed, 24 insertions(+) diff --git a/include/spdlog/details/registry-inl.h b/include/spdlog/details/registry-inl.h index e6ecc9b0..323a5c13 100644 --- a/include/spdlog/details/registry-inl.h +++ b/include/spdlog/details/registry-inl.h @@ -287,6 +287,14 @@ SPDLOG_INLINE registry ®istry::instance() return s_instance; } +SPDLOG_INLINE void registry::apply_logger_env_levels(std::shared_ptr new_logger) +{ + std::lock_guard lock(logger_map_mutex_); + auto it = log_levels_.find(new_logger->name()); + auto new_level = it != log_levels_.end() ? it->second : global_log_level_; + new_logger->set_level(new_level); +} + SPDLOG_INLINE void registry::throw_if_exists_(const std::string &logger_name) { if (loggers_.find(logger_name) != loggers_.end()) diff --git a/include/spdlog/details/registry.h b/include/spdlog/details/registry.h index 6a4a5abc..4666fa29 100644 --- a/include/spdlog/details/registry.h +++ b/include/spdlog/details/registry.h @@ -91,6 +91,8 @@ public: static registry &instance(); + void apply_logger_env_levels(std::shared_ptr new_logger); + private: registry(); ~registry(); diff --git a/include/spdlog/spdlog-inl.h b/include/spdlog/spdlog-inl.h index 708399c1..22ea22bb 100644 --- a/include/spdlog/spdlog-inl.h +++ b/include/spdlog/spdlog-inl.h @@ -117,4 +117,9 @@ SPDLOG_INLINE void set_default_logger(std::shared_ptr default_lo details::registry::instance().set_default_logger(std::move(default_logger)); } +SPDLOG_INLINE void apply_logger_env_levels(std::shared_ptr logger) +{ + details::registry::instance().apply_logger_env_levels(std::move(logger)); +} + } // namespace spdlog diff --git a/include/spdlog/spdlog.h b/include/spdlog/spdlog.h index ee83e8de..6b7b221a 100644 --- a/include/spdlog/spdlog.h +++ b/include/spdlog/spdlog.h @@ -131,6 +131,15 @@ SPDLOG_API spdlog::logger *default_logger_raw(); SPDLOG_API void set_default_logger(std::shared_ptr default_logger); +// Initialize logger level based on environment configs. +// +// Useful for applying SPDLOG_LEVEL to manually created loggers. +// +// Example: +// auto mylogger = std::make_shared("mylogger", ...); +// spdlog::apply_logger_env_levels(mylogger); +SPDLOG_API void apply_logger_env_levels(std::shared_ptr logger); + template inline void log(source_loc source, level::level_enum lvl, format_string_t fmt, Args &&... args) {