mdc.h 1.3 KB

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