logman 0.1.0
Modern C++23 header-only logging manager wrapping spdlog with channels, listeners, and structured events
Loading...
Searching...
No Matches
json_formatter.hpp
Go to the documentation of this file.
1#pragma once
2
6
10
11#include <nlohmann/json.hpp>
12#include <spdlog/details/fmt_helper.h>
13#include <spdlog/details/log_msg.h>
14#include <spdlog/formatter.h>
15#include <spdlog/pattern_formatter.h>
16
17#include <memory>
18#include <string>
19
20namespace logman {
21
26class JsonFormatter final : public spdlog::formatter {
27public:
28 JsonFormatter() : message_formatter_("%v", spdlog::pattern_time_type::local, std::string{}) {}
29
30 void format(const spdlog::details::log_msg& msg, spdlog::memory_buf_t& dest) override {
31 spdlog::memory_buf_t message_buf;
32 message_formatter_.format(msg, message_buf);
33 const LogEvent event =
34 detail::make_log_event(msg, std::string_view(message_buf.data(), message_buf.size()));
35
36 const nlohmann::json j = event;
37 const std::string out = j.dump();
38 spdlog::details::fmt_helper::append_string_view(out, dest);
39 dest.push_back('\n');
40 }
41
42 [[nodiscard]] std::unique_ptr<spdlog::formatter> clone() const override {
43 return std::make_unique<JsonFormatter>();
44 }
45
46private:
47 spdlog::pattern_formatter message_formatter_;
48};
49
50} // namespace logman
spdlog formatter that builds a LogEvent from the record, dumps it as compact JSON via to_json,...
Definition json_formatter.hpp:26
ListenerSink — spdlog sink that dispatches each log record to registered listener callbacks as LogEve...
Plain-old-data structure describing one log record.
nlohmann/json adapter for LogEvent.
One log record, captured by ListenerSink and (optionally) emitted as JSON by JsonFormatter.
Definition log_event.hpp:16