mirror of
https://github.com/gabime/spdlog.git
synced 2025-09-29 01:29:35 +08:00
Added mdc from pull #2907
This commit is contained in:
@@ -7,7 +7,6 @@
|
||||
#include <array>
|
||||
#include <cctype>
|
||||
#include <chrono>
|
||||
#include <cstring>
|
||||
#include <ctime>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
@@ -17,6 +16,7 @@
|
||||
#include "spdlog/details/fmt_helper.h"
|
||||
#include "spdlog/details/log_msg.h"
|
||||
#include "spdlog/details/os.h"
|
||||
#include <spdlog/mdc.h>
|
||||
#include "spdlog/fmt/fmt.h"
|
||||
#include "spdlog/formatter.h"
|
||||
|
||||
@@ -811,7 +811,6 @@ public:
|
||||
dest.push_back(']');
|
||||
dest.push_back(' ');
|
||||
}
|
||||
// fmt_helper::append_string_view(msg.msg(), dest);
|
||||
fmt_helper::append_string_view(msg.payload, dest);
|
||||
}
|
||||
|
||||
@@ -820,6 +819,44 @@ private:
|
||||
memory_buf_t cached_datetime_;
|
||||
};
|
||||
|
||||
// Class for formatting Mapped Diagnostic Context (MDC) in log messages.
|
||||
// Example: [logger-name] [info] [mdc_key_1:mdc_value_1 mdc_key_2:mdc_value_2] some message
|
||||
template <typename ScopedPadder>
|
||||
class mdc_formatter : public flag_formatter {
|
||||
public:
|
||||
explicit mdc_formatter(padding_info padinfo)
|
||||
: 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()) {
|
||||
ScopedPadder p(0, padinfo_, dest);
|
||||
return;
|
||||
} else {
|
||||
auto last_element = --mdc_map.end();
|
||||
for (auto it = mdc_map.begin(); it != mdc_map.end(); ++it) {
|
||||
auto &pair = *it;
|
||||
const auto &key = pair.first;
|
||||
const auto &value = pair.second;
|
||||
size_t content_size = key.size() + value.size() + 1; // 1 for ':'
|
||||
|
||||
if (it != last_element) {
|
||||
content_size++; // 1 for ' '
|
||||
}
|
||||
|
||||
ScopedPadder p(content_size, padinfo_, dest);
|
||||
fmt_helper::append_string_view(key, dest);
|
||||
fmt_helper::append_string_view(":", dest);
|
||||
fmt_helper::append_string_view(value, dest);
|
||||
if (it != last_element) {
|
||||
fmt_helper::append_string_view(" ", dest);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} // namespace details
|
||||
|
||||
pattern_formatter::pattern_formatter(std::string pattern,
|
||||
@@ -1096,6 +1133,10 @@ void pattern_formatter::handle_flag_(char flag, details::padding_info padding) {
|
||||
formatters_.push_back(std::make_unique<details::elapsed_formatter<Padder, std::chrono::seconds>>(padding));
|
||||
break;
|
||||
|
||||
case ('&'):
|
||||
formatters_.push_back(std::make_unique<details::mdc_formatter<Padder>>(padding));
|
||||
break;
|
||||
|
||||
default: // Unknown flag appears as is
|
||||
auto unknown_flag = std::make_unique<details::aggregate_formatter>();
|
||||
|
||||
|
Reference in New Issue
Block a user