| 1 | // Copyright(c) 2015-present, Gabi Melman & spdlog contributors. |
| 2 | // Distributed under the MIT License (http://opensource.org/licenses/MIT) |
| 3 | |
| 4 | #pragma once |
| 5 | |
| 6 | #include <map> |
| 7 | #include <string> |
| 8 | |
| 9 | #include <spdlog/common.h> |
| 10 | |
| 11 | // MDC is a simple map of key->string values stored in thread local storage whose content will be printed by the loggers. |
| 12 | // Note: Not supported in async mode (thread local storage - so the async thread pool have different copy). |
| 13 | // |
| 14 | // Usage example: |
| 15 | // spdlog::mdc::put("mdc_key_1", "mdc_value_1"); |
| 16 | // spdlog::info("Hello, {}", "World!"); // => [2024-04-26 02:08:05.040] [info] [mdc_key_1:mdc_value_1] Hello, World! |
| 17 | |
| 18 | namespace spdlog { |
| 19 | class SPDLOG_API mdc { |
| 20 | public: |
| 21 | using mdc_map_t = std::map<std::string, std::string>; |
| 22 | |
| 23 | static void put(const std::string &key, const std::string &value) { |
| 24 | get_context()[key] = value; |
| 25 | } |
| 26 | |
| 27 | static std::string get(const std::string &key) { |
| 28 | auto &context = get_context(); |
| 29 | auto it = context.find(x: key); |
| 30 | if (it != context.end()) { |
| 31 | return it->second; |
| 32 | } |
| 33 | return "" ; |
| 34 | } |
| 35 | |
| 36 | static void remove(const std::string &key) { get_context().erase(x: key); } |
| 37 | |
| 38 | static void clear() { get_context().clear(); } |
| 39 | |
| 40 | static mdc_map_t &get_context() { |
| 41 | static thread_local mdc_map_t context; |
| 42 | return context; |
| 43 | } |
| 44 | }; |
| 45 | |
| 46 | } // namespace spdlog |
| 47 | |