Logging: colors, configurable/custom pattern tokens, split + history sinks

Pattern formatting (PatternFormatter):
- Token spec grammar {token:[align][width][,color]} — align <,>,^,
  std::format-style width, color a name or "auto" (= the level's color).
- Custom tokens via register_token(name, fn); unknown {name} resolves
  against registered renderers, then Entry::fields by key, else stays
  literal — so structured fields print as {request_id:>8}.
- Color model: AnsiColor + ColorPolicy{enabled, level_colors,
  token_colors} (ColorPolicy::defaults()); only PatternFormatter
  colorizes (never file/JSON/logfmt). ConsoleLogger now renders its
  default line through a colored PatternFormatter and exposes
  set_color_policy (honors Stacktrace::Color::g_color_enabled).

Structured fields:
- Entry gains a fields vector; Logging::FieldScope (RAII, thread-local)
  attaches key/values to every entry on the thread, snapshotted like
  scopes. JsonLines/logfmt include them.

New file sinks (async by default):
- Detail::RollingFile factors size+max-files rotation; RotatingFileLogger
  now delegates to it.
- SplitFileLogger: per-level files (<dir>/<level>.log) plus an optional
  combined <dir>/all.log.
- HistoryLogger: always-on, never-level-filtered durable JSON-lines
  audit trail over a rolling file.
- from_config gains split/history sinks and a log.color toggle.

22 new tests (pattern width/align/custom-token/field, color on/off + name
parsing, FieldScope nesting, split routing + combined, history JSON +
rotation, from_config split/history). 987 green; module build clean
under -Werror.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 00:24:31 +03:00
1 parent ff6960a2af
commit 6b5f61f00a
22 files changed
+1384 -233

No files matched your search

+60
View File
@@ -0,0 +1,60 @@
#include <Void/Log/Field.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
#include <vector>
using namespace Void::Logging;
Void::Testing::Test field_scope_attaches_to_entries()
{
std::vector<Entry> captured;
CallbackLogger log{[&](const Entry& e) { captured.push_back(e); },
Mode::Immediate};
{
FieldScope svc{"service", "billing"};
log.info("inside scope");
}
log.info("outside scope");
Void::Testing::expect_eq(captured.size(), std::size_t{2});
Void::Testing::expect_eq(captured[0].fields.size(), std::size_t{1});
Void::Testing::expect_eq(captured[0].fields[0].first,
std::string{"service"});
Void::Testing::expect_eq(captured[0].fields[0].second,
std::string{"billing"});
Void::Testing::expect(captured[1].fields.empty());
}
Void::Testing::Test field_scope_nests()
{
std::vector<Entry> captured;
CallbackLogger log{[&](const Entry& e) { captured.push_back(e); },
Mode::Immediate};
FieldScope a{"a", "1"};
{
FieldScope b{{{"b", "2"}, {"c", "3"}}};
log.info("two scopes");
}
log.info("one scope");
Void::Testing::expect_eq(captured[0].fields.size(), std::size_t{3});
Void::Testing::expect_eq(captured[1].fields.size(), std::size_t{1});
}
Void::Testing::Test field_scope_feeds_pattern_token()
{
std::string rendered;
PatternFormatter fmt{"[{request_id}] {message}"};
CallbackLogger log{[&](const Entry& e) { rendered = fmt.format(e); },
Mode::Immediate};
FieldScope req{"request_id", "r-42"};
log.warning("processing");
Void::Testing::expect_eq(rendered, std::string{"[r-42] processing"});
}
+142
View File
@@ -0,0 +1,142 @@
#include <Void/Data/Json.hpp>
#include <Void/Log/Field.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Fixture.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <fstream>
#include <string>
using namespace Void::Logging;
namespace
{
std::string slurp(const std::filesystem::path& p)
{
std::ifstream f(p);
return {std::istreambuf_iterator<char>(f), {}};
}
} // namespace
class SplitFileLoggerTests : public Void::Testing::Fixture
{
public:
std::filesystem::path dir;
void setup() override
{
dir = std::filesystem::temp_directory_path() / "void_split_test";
std::filesystem::remove_all(dir);
}
void teardown() override { std::filesystem::remove_all(dir); }
Void::Testing::Test routes_by_level()
{
{
SplitFileLogger log{dir,
{.mode = Void::Logging::Mode::Immediate}};
log.info("an info line");
log.error("an error line");
}
Void::Testing::expect(
slurp(dir / "info.log").find("an info line") !=
std::string::npos);
Void::Testing::expect(
slurp(dir / "error.log").find("an error line") !=
std::string::npos);
// error.log must NOT contain the info line.
Void::Testing::expect(
slurp(dir / "error.log").find("an info line") ==
std::string::npos);
}
Void::Testing::Test combined_has_all_levels()
{
{
SplitFileLogger log{dir,
{.mode = Void::Logging::Mode::Immediate}};
log.info("info one");
log.error("error one");
}
const auto all = slurp(dir / "all.log");
Void::Testing::expect(all.find("info one") != std::string::npos);
Void::Testing::expect(all.find("error one") != std::string::npos);
}
Void::Testing::Test combined_can_be_disabled()
{
{
SplitFileLogger log{dir,
{.combined = false,
.mode = Void::Logging::Mode::Immediate}};
log.info("solo");
}
Void::Testing::expect(!std::filesystem::exists(dir / "all.log"));
Void::Testing::expect(std::filesystem::exists(dir / "info.log"));
}
};
class HistoryLoggerTests : public Void::Testing::Fixture
{
public:
std::filesystem::path dir;
std::filesystem::path path;
void setup() override
{
dir = std::filesystem::temp_directory_path() / "void_hist_test";
std::filesystem::remove_all(dir);
std::filesystem::create_directories(dir);
path = dir / "history.jsonl";
}
void teardown() override { std::filesystem::remove_all(dir); }
Void::Testing::Test writes_jsonlines()
{
{
HistoryLogger log{path,
{.mode = Void::Logging::Mode::Immediate}};
log.info("audit me");
}
std::ifstream f(path);
std::string line;
std::getline(f, line);
const auto parsed = Void::Json::parse(line);
Void::Testing::expect(parsed.has_value());
Void::Testing::expect_eq((*parsed)["message"].as_string(),
std::string{"audit me"});
}
Void::Testing::Test captures_below_default_min_level()
{
{
HistoryLogger log{path,
{.mode = Void::Logging::Mode::Immediate}};
log.trace("low level but kept");
}
Void::Testing::expect(slurp(path).find("low level but kept") !=
std::string::npos);
}
Void::Testing::Test rotates_on_size()
{
{
HistoryLogger log{path,
{.max_bytes = 256,
.max_files = 3,
.mode = Void::Logging::Mode::Immediate}};
for (int i = 0; i < 60; ++i) {
log.info("a fairly long history line number " +
std::to_string(i));
}
}
auto rotated = path;
rotated += ".1";
Void::Testing::expect(std::filesystem::exists(rotated));
}
};
+25
View File
@@ -46,6 +46,31 @@ Void::Testing::Test from_config_builds_multi_sink_tree()
std::string::npos);
}
Void::Testing::Test from_config_split_and_history_sinks()
{
Void::FileSystem::TempDir tmp{"void_fromcfg"};
Config cfg;
cfg.set("log.sinks", "split, history");
cfg.set("log.split.dir", (tmp.path() / "split").string());
cfg.set("log.history.path", (tmp.path() / "history.jsonl").string());
cfg.set("log.async", "false");
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
(*logger)->error("split me");
(*logger)->flush();
std::ifstream err(tmp.path() / "split" / "error.log");
std::string err_content((std::istreambuf_iterator<char>(err)), {});
Void::Testing::expect(err_content.find("split me") !=
std::string::npos);
std::ifstream hist(tmp.path() / "history.jsonl");
std::string hist_content((std::istreambuf_iterator<char>(hist)), {});
Void::Testing::expect(hist_content.find("split me") !=
std::string::npos);
}
Void::Testing::Test from_config_json_format_applies()
{
Void::FileSystem::TempDir tmp{"void_fromcfg"};
+137
View File
@@ -0,0 +1,137 @@
#include <Void/Log/Field.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
using Void::Logging::AnsiColor;
using Void::Logging::ColorPolicy;
using Void::Logging::Entry;
using Void::Logging::Level;
using Void::Logging::PatternFormatter;
namespace
{
Entry make_entry()
{
Entry e;
e.level = Level::Warning;
e.message = "disk full";
e.fields = {{"service", "ingest"}, {"request_id", "abc123"}};
return e;
}
} // namespace
// ── width / alignment
// ─────────────────────────────────────────────────────────
Void::Testing::Test pattern_left_pad_width()
{
PatternFormatter fmt{"[{level:<10}]"};
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"[Warning ]"});
}
Void::Testing::Test pattern_right_pad_width()
{
PatternFormatter fmt{"[{level:>10}]"};
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"[ Warning]"});
}
Void::Testing::Test pattern_center_pad_width()
{
PatternFormatter fmt{"[{level:^9}]"};
// "Warning" is 7 chars, width 9 → 1 left, 1 right
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"[ Warning ]"});
}
Void::Testing::Test pattern_width_smaller_than_text_is_noop()
{
PatternFormatter fmt{"{level:<3}"};
Void::Testing::expect_eq(fmt.format(make_entry()), std::string{"Warning"});
}
// ── custom tokens & fields
// ────────────────────────────────────────────────────
Void::Testing::Test pattern_reads_structured_field()
{
PatternFormatter fmt{"{service}/{request_id}: {message}"};
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"ingest/abc123: disk full"});
}
Void::Testing::Test pattern_unknown_token_stays_literal()
{
PatternFormatter fmt{"{nope} {message}"};
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"{nope} disk full"});
}
Void::Testing::Test pattern_custom_token_registered()
{
PatternFormatter fmt{"<{shout}> {message}"};
fmt.register_token("shout", [](const Entry& e) {
std::string up = e.message;
for (auto& c : up) {
c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}
return up;
});
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"<DISK FULL> disk full"});
}
Void::Testing::Test pattern_field_with_alignment()
{
PatternFormatter fmt{"{service:>8}"};
Void::Testing::expect_eq(fmt.format(make_entry()), std::string{" ingest"});
}
// ── color
// ─────────────────────────────────────────────────────────────────────
Void::Testing::Test pattern_no_color_by_default()
{
PatternFormatter fmt{"{level:,auto} {message}"};
// Policy disabled by default → no escape codes.
const auto out = fmt.format(make_entry());
Void::Testing::expect(out.find('\x1b') == std::string::npos);
Void::Testing::expect_eq(out, std::string{"Warning disk full"});
}
Void::Testing::Test pattern_auto_color_uses_level_color()
{
PatternFormatter fmt{"{level:,auto}"};
fmt.set_color_policy(ColorPolicy::defaults());
const auto out = fmt.format(make_entry());
// Warning → bright yellow (93), wrapped + reset, text intact.
Void::Testing::expect(out.find("\x1b[93m") != std::string::npos);
Void::Testing::expect(out.find("Warning") != std::string::npos);
Void::Testing::expect(out.find("\x1b[0m") != std::string::npos);
}
Void::Testing::Test pattern_fixed_color()
{
PatternFormatter fmt{"{message:,cyan}"};
ColorPolicy p;
p.enabled = true;
fmt.set_color_policy(p);
const auto out = fmt.format(make_entry());
Void::Testing::expect(out.find("\x1b[36m") != std::string::npos);
Void::Testing::expect(out.find("disk full") != std::string::npos);
}
Void::Testing::Test color_name_parsing()
{
Void::Testing::expect(Void::Logging::parse_color("red") == AnsiColor::Red);
Void::Testing::expect(Void::Logging::parse_color("bright_magenta") ==
AnsiColor::BrightMagenta);
Void::Testing::expect(Void::Logging::parse_color("dim") ==
AnsiColor::BrightBlack);
Void::Testing::expect(Void::Logging::parse_color("notacolor") ==
AnsiColor::Default);
}