mdc.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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 printed by the loggers.
  11. // Note: Not supported in async mode (thread local storage - so the async thread pool have different copy).
  12. //
  13. // Usage example:
  14. // spdlog::mdc::put("mdc_key_1", "mdc_value_1");
  15. // spdlog::info("Hello, {}", "World!"); // => [2024-04-26 02:08:05.040] [info] [mdc_key_1:mdc_value_1] Hello, World!
  16. namespace spdlog {
  17. class SPDLOG_API mdc {
  18. public:
  19. using mdc_map_t = std::map<std::string, std::string>;
  20. static void put(const std::string &key, const std::string &value) {
  21. get_context()[key] = value;
  22. }
  23. static std::string get(const std::string &key) {
  24. auto &context = get_context();
  25. auto it = context.find(key);
  26. if (it != context.end()) {
  27. return it->second;
  28. }
  29. return "";
  30. }
  31. static void remove(const std::string &key) { get_context().erase(key); }
  32. static void clear() { get_context().clear(); }
  33. static mdc_map_t &get_context() {
  34. static thread_local mdc_map_t context;
  35. return context;
  36. }
  37. };
  38. } // namespace spdlog