From 3c30f77d31857106fec9f5c7eff431ade5a5023d Mon Sep 17 00:00:00 2001 From: gabime Date: Wed, 17 Jul 2019 18:05:01 +0300 Subject: [PATCH] limit default error handler to 1 message/second to avoid flood --- include/spdlog/logger-inl.h | 20 ++++++++++++++++++-- include/spdlog/logger.h | 4 ++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/include/spdlog/logger-inl.h b/include/spdlog/logger-inl.h index 0f7b485d..9f125dcc 100644 --- a/include/spdlog/logger-inl.h +++ b/include/spdlog/logger-inl.h @@ -10,6 +10,8 @@ #include "spdlog/sinks/sink.h" #include "spdlog/details/pattern_formatter.h" +#include + namespace spdlog { // public methods @@ -203,18 +205,32 @@ SPDLOG_INLINE bool logger::should_flush_(const details::log_msg &msg) return (msg.level >= flush_level) && (msg.level != level::off); } + SPDLOG_INLINE void logger::err_handler_(const std::string &msg) { + if (custom_err_handler_) { custom_err_handler_(msg); } else { - auto tm_time = details::os::localtime(); + using std::chrono::system_clock; + static std::mutex mutex; + static std::chrono::system_clock::time_point last_report_time; + static size_t err_counter = 0; + std::lock_guard lk{mutex}; + auto now = system_clock::now(); + err_counter++; + if(now - last_report_time < std::chrono::seconds(1)) + { + return; + } + last_report_time = now; + auto tm_time = details::os::localtime(system_clock::to_time_t(now)); char date_buf[64]; std::strftime(date_buf, sizeof(date_buf), "%Y-%m-%d %H:%M:%S", &tm_time); - fmt::print(stderr, "[*** LOG ERROR ***] [{}] [{}] {}\n", date_buf, name(), msg); + fprintf(stderr, "[*** LOG ERROR #%04zu ***] [%s] [%s] {%s}\n", err_counter, date_buf, name().c_str(), msg.c_str()); } } } // namespace spdlog diff --git a/include/spdlog/logger.h b/include/spdlog/logger.h index 7576c8ef..af121b76 100644 --- a/include/spdlog/logger.h +++ b/include/spdlog/logger.h @@ -317,8 +317,8 @@ protected: virtual void flush_(); bool should_flush_(const details::log_msg &msg); - // default error handler. - // print the error to stderr with the max rate of 1 message/minute. + // handle errors during logging. + // default handler prints the error to stderr at max rate of 1 message/sec. void err_handler_(const std::string &msg); };