From 7e5c8049ef028d4552ce329aa3dd89e3f58dbecc Mon Sep 17 00:00:00 2001 From: dyf Date: Wed, 11 Sep 2024 18:31:45 +0800 Subject: [PATCH] fix/issue-3101: fix the issue of mdc ignores SPDLOG_NO_TLS --- include/spdlog/mdc.h | 28 ++++++++++++++++++-------- include/spdlog/pattern_formatter-inl.h | 12 +++++------ 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/include/spdlog/mdc.h b/include/spdlog/mdc.h index 41f0c1f3..80933afc 100644 --- a/include/spdlog/mdc.h +++ b/include/spdlog/mdc.h @@ -21,25 +21,37 @@ public: using mdc_map_t = std::map; static void put(const std::string &key, const std::string &value) { - get_context()[key] = value; + auto pcontext = get_context(); + if (pcontext) { (*pcontext)[key] = value; } } static std::string get(const std::string &key) { - auto &context = get_context(); - auto it = context.find(key); - if (it != context.end()) { + auto pcontext = get_context(); + if (!pcontext) { return ""; } + auto it = pcontext->find(key); + if (it != pcontext->end()) { return it->second; } return ""; } - static void remove(const std::string &key) { get_context().erase(key); } + static void remove(const std::string &key) { + auto pcontext = get_context(); + if (pcontext) { pcontext->erase(key);} + } - static void clear() { get_context().clear(); } + static void clear() { + auto pcontext = get_context(); + if (pcontext) { pcontext->clear(); } + } - static mdc_map_t &get_context() { + static mdc_map_t *get_context() { +#if defined(SPDLOG_NO_TLS) + return nullptr; +#else static thread_local mdc_map_t context; - return context; + return &context; +#endif } }; diff --git a/include/spdlog/pattern_formatter-inl.h b/include/spdlog/pattern_formatter-inl.h index 756e5941..b3fa0c9e 100644 --- a/include/spdlog/pattern_formatter-inl.h +++ b/include/spdlog/pattern_formatter-inl.h @@ -793,12 +793,12 @@ public: : flag_formatter(padinfo) {} void format(const details::log_msg &, const std::tm &, memory_buf_t &dest) override { - auto &mdc_map = mdc::get_context(); - if (mdc_map.empty()) { + auto pmdc_map = mdc::get_context(); + if (!pmdc_map || pmdc_map->empty()) { ScopedPadder p(0, padinfo_, dest); return; } else { - format_mdc(mdc_map, dest); + format_mdc(*pmdc_map, dest); } } @@ -902,10 +902,10 @@ public: } // add mdc if present - auto &mdc_map = mdc::get_context(); - if (!mdc_map.empty()) { + auto pmdc_map = mdc::get_context(); + if (pmdc_map && !pmdc_map->empty()) { dest.push_back('['); - mdc_formatter_.format_mdc(mdc_map, dest); + mdc_formatter_.format_mdc(*pmdc_map, dest); dest.push_back(']'); dest.push_back(' '); }