mdc.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
  2. // Distributed under the MIT License (http://opensource.org/licenses/MIT)
  3. #pragma once
  4. #if defined(SPDLOG_NO_TLS)
  5. #error "This header requires thread local storage support, but SPDLOG_NO_TLS is defined."
  6. #endif
  7. #include <map>
  8. #include <string>
  9. #include <spdlog/common.h>
  10. // MDC is a simple map of key->string values stored in thread local storage whose content will be
  11. // printed by the loggers. Note: Not supported in async mode (thread local storage - so the async
  12. // 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]
  17. // [mdc_key_1:mdc_value_1] Hello, World!
  18. namespace spdlog {
  19. class SPDLOG_API mdc {
  20. public:
  21. using mdc_map_t = std::map<std::string, std::string>;
  22. static void put(const std::string &key, const std::string &value) {
  23. get_context()[key] = value;
  24. }
  25. static std::string get(const std::string &key) {
  26. auto &context = get_context();
  27. auto it = context.find(key);
  28. if (it != context.end()) {
  29. return it->second;
  30. }
  31. return "";
  32. }
  33. static void remove(const std::string &key) { get_context().erase(key); }
  34. static void clear() { get_context().clear(); }
  35. static mdc_map_t &get_context() {
  36. static thread_local mdc_map_t context;
  37. return context;
  38. }
  39. };
  40. } // namespace spdlog