Overhaul Logging and Configuration; integrate the log facade library-wide

Void::Log facade (header-only, macro-free):
- Leveled function templates trace/debug/info/warn/error/fatal(module,
  fmt, args...) with lazy formatting - a disabled call is one relaxed
  atomic load, no allocation, no formatting.
- Global min level + per-module overrides (can raise or lower); empty
  sink/Disabled level = logging fully off; set_sink remains the splice
  point for external logging libraries.

Void::Logging::Logger - async by default, one class for both modes:
- Mode::Async (default): lock-free MPSC queue + logger-owned worker
  delivering batches via on_flush outside any lock; Immediate/Buffered
  give synchronous behavior via constructor arg or set_mode at runtime.
- Bounded queue with OverflowPolicy{Block, DropNewest, DropOldest};
  flush() (now virtual) blocks until everything submitted is delivered;
  base destructor only stops/joins the worker, never touches virtuals.
- Fixed a wakeup race: stale park token + fresh release overflowed the
  binary semaphore; wakeup is a counting semaphore (spurious wakes are
  absorbed by the worker loop).

New sinks and formatters:
- RotatingFileLogger (size-based rotation, max-files cap), NullLogger,
  CallbackLogger, MultiLogger (tee via new Logger::relay), SyslogLogger.
- Formatter interface: PatternFormatter ({time}/{level}/{scopes}/...),
  JsonLinesFormatter, LogfmtFormatter; installable on Console/File/
  Rotating sinks. Console/File sinks now default to Async.
- Logging::from_config builds the whole sink tree from Config keys;
  apply_facade_config drives facade levels.

Configuration:
- Typed get_as<T>/get_or_as<T> (numbers, bool spellings, enums by name,
  chrono durations), dotted keys, subtree(), sorted keys().
- New sources: from_env_prefix (APP_LOG__LEVEL -> log.level), from_ini
  (sections as prefixes), from_json (objects/arrays flattened),
  from_args (--key=value / --key value / --flag).
- Bind.hpp: reflection bind<T>(cfg, prefix) fills aggregates; defaults
  in the struct are the schema; nested aggregates, optional, vector.
- Watch.hpp: ConfigWatch reloads on change with per-key diff; parse
  failures keep the previous config.

System: new FileSystem::FileWatcher - debounced polling watcher (stable
mtime+size across N polls), callbacks off-thread, deletion events;
shared groundwork for plugin hot-reload.

Sweep: all internal Void::Log::log call sites migrated to the leveled
API ("Umbrella.Feature" labels); Plugin loader now logs load/reload.

918 tests green (28 new), stable across 30 consecutive runs, ASan+UBSan
clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-13 00:11:13 +03:00
1 parent 8a6065539a
commit c74a02a5a5
43 files changed
+3889 -236

No files matched your search

+198
View File
@@ -0,0 +1,198 @@
#include <Void/Log/Logger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <string>
#include <thread>
#include <vector>
using Void::Logging::CallbackLogger;
using Void::Logging::Entry;
using Void::Logging::Level;
using Void::Logging::Mode;
using Void::Logging::OverflowPolicy;
// ── basics ────────────────────────────────────────────────────────────────────
Void::Testing::Test async_is_the_default_mode()
{
CallbackLogger log{[](const Entry&) {}};
Void::Testing::expect(log.mode() == Mode::Async);
}
Void::Testing::Test async_flush_delivers_everything_submitted()
{
std::atomic<int> delivered{0};
CallbackLogger log{[&](const Entry&) { ++delivered; }};
for (int i = 0; i < 100; ++i) {
log.info("entry");
}
log.flush();
Void::Testing::expect_eq(delivered.load(), 100);
}
Void::Testing::Test async_entries_arrive_in_order()
{
std::vector<std::string> messages;
CallbackLogger log{
[&](const Entry& e) { messages.push_back(e.message); }};
log.info("one");
log.info("two");
log.info("three");
log.flush();
Void::Testing::expect_eq(messages.size(), std::size_t{3});
Void::Testing::expect_eq(messages[0], std::string{"one"});
Void::Testing::expect_eq(messages[1], std::string{"two"});
Void::Testing::expect_eq(messages[2], std::string{"three"});
}
Void::Testing::Test async_level_filter_applies()
{
std::atomic<int> delivered{0};
CallbackLogger log{[&](const Entry&) { ++delivered; }};
log.set_level(Level::Warning);
log.debug("dropped");
log.warning("kept");
log.flush();
Void::Testing::expect_eq(delivered.load(), 1);
}
Void::Testing::Test destructor_flushes_via_derived_contract()
{
std::atomic<int> delivered{0};
{
CallbackLogger log{[&](const Entry&) { ++delivered; }};
for (int i = 0; i < 32; ++i) {
log.info("entry");
}
// No explicit flush — CallbackLogger's destructor must flush.
}
Void::Testing::expect_eq(delivered.load(), 32);
}
// ── mode switching (same class, no decorators) ────────────────────────────────
Void::Testing::Test switch_async_to_immediate_makes_calls_synchronous()
{
std::atomic<int> delivered{0};
std::thread::id write_thread{};
CallbackLogger log{[&](const Entry&) {
++delivered;
write_thread = std::this_thread::get_id();
}};
log.info("async one");
log.set_mode(Mode::Immediate); // drains pending first
Void::Testing::expect_eq(delivered.load(), 1);
log.info("sync two");
// Immediate: delivered inline on this thread, no flush needed.
Void::Testing::expect_eq(delivered.load(), 2);
Void::Testing::expect(write_thread == std::this_thread::get_id());
}
Void::Testing::Test switch_immediate_to_async_round_trip()
{
std::atomic<int> delivered{0};
CallbackLogger log{[&](const Entry&) { ++delivered; },
Mode::Immediate};
log.info("sync");
Void::Testing::expect_eq(delivered.load(), 1);
log.set_mode(Mode::Async);
log.info("queued");
log.flush();
Void::Testing::expect_eq(delivered.load(), 2);
}
Void::Testing::Test async_writes_happen_on_worker_thread()
{
std::thread::id write_thread{};
CallbackLogger log{[&](const Entry&) {
write_thread = std::this_thread::get_id();
}};
log.info("from main");
log.flush();
Void::Testing::expect(write_thread != std::this_thread::get_id());
}
// ── overflow policies ─────────────────────────────────────────────────────────
Void::Testing::Test block_policy_loses_nothing_under_pressure()
{
std::atomic<int> delivered{0};
{
// Tiny capacity + slow-ish sink forces producers to block.
CallbackLogger log{[&](const Entry&) { ++delivered; }, Mode::Async,
4, OverflowPolicy::Block};
for (int i = 0; i < 500; ++i) {
log.info("pressure");
}
log.flush();
}
Void::Testing::expect_eq(delivered.load(), 500);
}
Void::Testing::Test drop_newest_policy_bounds_pending()
{
std::atomic<bool> release{false};
std::atomic<int> delivered{0};
{
CallbackLogger log{[&](const Entry&) {
// Stall the worker so the queue stays full.
release.wait(false);
++delivered;
},
Mode::Async, 2, OverflowPolicy::DropNewest};
for (int i = 0; i < 100; ++i) {
log.info("burst");
}
release = true;
release.notify_all();
log.flush();
}
// Far fewer than 100 must have arrived; none blocked the producer.
Void::Testing::expect(delivered.load() < 100);
Void::Testing::expect(delivered.load() >= 1);
}
// ── multi-producer stress ─────────────────────────────────────────────────────
// @tag stress, concurrency
Void::Testing::Test async_multi_producer_no_loss()
{
constexpr int producers = 8;
constexpr int per_producer = 50'000;
std::atomic<long long> delivered{0};
{
CallbackLogger log{[&](const Entry&) { ++delivered; }, Mode::Async,
1024, OverflowPolicy::Block};
log.set_level(Level::Trace);
std::vector<std::thread> threads;
threads.reserve(producers);
for (int p = 0; p < producers; ++p) {
threads.emplace_back([&log] {
for (int i = 0; i < per_producer; ++i) {
log.info("stress");
}
});
}
for (auto& t : threads) {
t.join();
}
log.flush();
}
Void::Testing::expect_eq(
delivered.load(),
static_cast<long long>(producers) * per_producer);
}
+100
View File
@@ -0,0 +1,100 @@
#include <Void/Data/Json.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <string>
using Void::Logging::Entry;
using Void::Logging::JsonLinesFormatter;
using Void::Logging::Level;
using Void::Logging::LogfmtFormatter;
using Void::Logging::PatternFormatter;
namespace
{
Entry make_entry()
{
Entry e;
e.level = Level::Warning;
e.message = "disk almost full";
e.scopes = {"sys", "disk"};
return e;
}
} // namespace
// ── PatternFormatter ──────────────────────────────────────────────────────────
Void::Testing::Test pattern_default_renders_level_and_message()
{
PatternFormatter fmt;
const auto line = fmt.format(make_entry());
Void::Testing::expect(line.find("[Warning]") != std::string::npos);
Void::Testing::expect(line.find("disk almost full") !=
std::string::npos);
Void::Testing::expect(line.find("sys.disk") != std::string::npos);
}
Void::Testing::Test pattern_custom_layout()
{
PatternFormatter fmt{"{level}|{message}"};
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"Warning|disk almost full"});
}
Void::Testing::Test pattern_unknown_placeholder_stays_literal()
{
PatternFormatter fmt{"{nope} {message}"};
Void::Testing::expect_eq(fmt.format(make_entry()),
std::string{"{nope} disk almost full"});
}
Void::Testing::Test pattern_time_is_iso8601()
{
PatternFormatter fmt{"{time}"};
const auto line = fmt.format(make_entry());
// "2026-06-12T10:30:00.123Z"
Void::Testing::expect_eq(line.size(), std::size_t{24});
Void::Testing::expect_eq(line[10], 'T');
Void::Testing::expect_eq(line.back(), 'Z');
}
// ── JsonLinesFormatter ────────────────────────────────────────────────────────
Void::Testing::Test jsonlines_produces_valid_json_with_fields()
{
JsonLinesFormatter fmt;
const auto line = fmt.format(make_entry());
const auto parsed = Void::Json::parse(line);
Void::Testing::expect(parsed.has_value());
Void::Testing::expect_eq((*parsed)["level"].as_string(),
std::string{"Warning"});
Void::Testing::expect_eq((*parsed)["message"].as_string(),
std::string{"disk almost full"});
Void::Testing::expect_eq((*parsed)["scopes"].as_array().size(),
std::size_t{2});
}
// ── LogfmtFormatter ───────────────────────────────────────────────────────────
Void::Testing::Test logfmt_renders_key_value_pairs()
{
LogfmtFormatter fmt;
const auto line = fmt.format(make_entry());
Void::Testing::expect(line.find("level=Warning") != std::string::npos);
Void::Testing::expect(line.find("msg=\"disk almost full\"") !=
std::string::npos);
Void::Testing::expect(line.find("scopes=sys.disk") !=
std::string::npos);
}
Void::Testing::Test logfmt_escapes_quotes_in_message()
{
Entry e = make_entry();
e.message = R"(said "hi")";
LogfmtFormatter fmt;
const auto line = fmt.format(e);
Void::Testing::expect(line.find(R"(msg="said \"hi\"")") !=
std::string::npos);
}
+105
View File
@@ -0,0 +1,105 @@
#include <Void/Configuration/Config.hpp>
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <fstream>
#include <string>
using Void::Configuration::Config;
Void::Testing::Test from_config_defaults_to_console()
{
Config cfg; // empty: console sink, trace level, async
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
Void::Testing::expect((*logger)->mode() ==
Void::Logging::Mode::Async);
}
Void::Testing::Test from_config_builds_multi_sink_tree()
{
Void::FileSystem::TempDir tmp{"void_fromcfg"};
Config cfg;
cfg.set("log.sinks", "console, file");
cfg.set("log.file.path", (tmp.path() / "a.log").string());
cfg.set("log.level", "warning");
cfg.set("log.async", "false");
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
Void::Testing::expect((*logger)->mode() ==
Void::Logging::Mode::Immediate);
Void::Testing::expect((*logger)->level() ==
Void::Logging::Level::Warning);
(*logger)->warning("to both sinks");
(*logger)->flush();
std::ifstream f(tmp.path() / "a.log");
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("to both sinks") !=
std::string::npos);
}
Void::Testing::Test from_config_json_format_applies()
{
Void::FileSystem::TempDir tmp{"void_fromcfg"};
Config cfg;
cfg.set("log.sinks", "file");
cfg.set("log.file.path", (tmp.path() / "j.log").string());
cfg.set("log.format", "json");
cfg.set("log.async", "false");
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
(*logger)->info("structured");
(*logger)->flush();
std::ifstream f(tmp.path() / "j.log");
std::string line;
std::getline(f, line);
Void::Testing::expect(line.find("\"message\":\"structured\"") !=
std::string::npos);
}
Void::Testing::Test from_config_missing_file_path_is_error()
{
Config cfg;
cfg.set("log.sinks", "file");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
Void::Testing::Test from_config_unknown_sink_is_error()
{
Config cfg;
cfg.set("log.sinks", "carrier-pigeon");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
Void::Testing::Test apply_facade_config_sets_levels()
{
struct Reset {
~Reset()
{
Void::Log::set_min_level(Void::Log::Level::Trace);
Void::Log::clear_module_level("Fsm");
}
} reset;
Config cfg;
cfg.set("log.level", "error");
cfg.set("log.module_levels.Fsm", "trace");
Void::Logging::apply_facade_config(cfg);
Void::Log::set_sink([](auto, auto, auto) {});
Void::Testing::expect(
!Void::Log::enabled(Void::Log::Level::Info, "Other"));
Void::Testing::expect(
Void::Log::enabled(Void::Log::Level::Trace, "Fsm"));
Void::Log::set_sink({});
}
+124 -2
View File
@@ -7,9 +7,15 @@
#include <thread>
#include <vector>
// Reset the global sink between tests via a scoped RAII guard.
// Reset the global facade state between tests via a scoped RAII guard.
struct SinkGuard {
~SinkGuard() { Void::Log::set_sink({}); }
~SinkGuard()
{
Void::Log::set_sink({});
Void::Log::set_min_level(Void::Log::Level::Trace);
Void::Log::clear_module_level("Filtered");
Void::Log::clear_module_level("Verbose");
}
};
Void::Testing::Test no_sink_is_silent()
@@ -105,3 +111,119 @@ Void::Testing::Test all_levels_are_forwarded()
Void::Testing::expect_eq(calls, 6);
}
// ── leveled helpers & lazy formatting ─────────────────────────────────────────
Void::Testing::Test leveled_helpers_format_arguments()
{
SinkGuard guard;
std::string got;
Void::Log::Level got_level{};
Void::Log::set_sink([&](Void::Log::Level l, auto, std::string_view msg) {
got_level = l;
got = msg;
});
Void::Log::warn("m", "answer = {}", 42);
Void::Testing::expect(got_level == Void::Log::Level::Warning);
Void::Testing::expect_eq(got, std::string{"answer = 42"});
}
namespace
{
// A format argument whose formatting is observable — proves laziness.
struct FormatProbe {
int* format_count;
};
} // namespace
template <>
struct std::formatter<FormatProbe> : std::formatter<int> {
template <class Ctx>
auto format(const FormatProbe& p, Ctx& ctx) const
{
++*p.format_count;
return std::formatter<int>::format(0, ctx);
}
};
Void::Testing::Test disabled_calls_do_not_format()
{
SinkGuard guard;
int formatted = 0;
// No sink: nothing may be formatted.
Void::Log::debug("m", "{}", FormatProbe{&formatted});
Void::Testing::expect_eq(formatted, 0);
// Sink present but level below the global minimum: still nothing.
int calls = 0;
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
Void::Log::set_min_level(Void::Log::Level::Error);
Void::Log::debug("m", "{}", FormatProbe{&formatted});
Void::Testing::expect_eq(formatted, 0);
Void::Testing::expect_eq(calls, 0);
// Passing the gate formats exactly once.
Void::Log::error("m", "{}", FormatProbe{&formatted});
Void::Testing::expect_eq(formatted, 1);
Void::Testing::expect_eq(calls, 1);
}
// ── level filtering ───────────────────────────────────────────────────────────
Void::Testing::Test global_min_level_filters()
{
SinkGuard guard;
int calls = 0;
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
Void::Log::set_min_level(Void::Log::Level::Warning);
Void::Log::info("m", "dropped");
Void::Log::warn("m", "kept");
Void::Log::error("m", "kept");
Void::Testing::expect_eq(calls, 2);
}
Void::Testing::Test disabled_level_silences_everything()
{
SinkGuard guard;
int calls = 0;
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
Void::Log::set_min_level(Void::Log::Level::Disabled);
Void::Log::fatal("m", "still dropped");
Void::Testing::expect_eq(calls, 0);
}
Void::Testing::Test module_override_lowers_and_raises()
{
SinkGuard guard;
int calls = 0;
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
Void::Log::set_min_level(Void::Log::Level::Warning);
// Lower the threshold for one module only.
Void::Log::set_module_level("Verbose", Void::Log::Level::Trace);
Void::Log::debug("Verbose", "kept by override");
Void::Log::debug("Other", "dropped by global");
Void::Testing::expect_eq(calls, 1);
// Raise the threshold for one module above the global.
Void::Log::set_module_level("Filtered", Void::Log::Level::Fatal);
Void::Log::error("Filtered", "dropped by override");
Void::Log::error("Other", "kept by global");
Void::Testing::expect_eq(calls, 2);
}
Void::Testing::Test enabled_reflects_configuration()
{
SinkGuard guard;
Void::Testing::expect(
!Void::Log::enabled(Void::Log::Level::Fatal, "m")); // no sink
Void::Log::set_sink([](auto, auto, auto) {});
Void::Log::set_min_level(Void::Log::Level::Info);
Void::Testing::expect(Void::Log::enabled(Void::Log::Level::Info, "m"));
Void::Testing::expect(!Void::Log::enabled(Void::Log::Level::Debug, "m"));
}
+183
View File
@@ -0,0 +1,183 @@
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Fixture.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <fstream>
#include <memory>
#include <sstream>
#include <string>
using namespace Void::Logging;
// ── NullLogger / CallbackLogger ───────────────────────────────────────────────
Void::Testing::Test null_logger_swallows_everything()
{
NullLogger log;
log.fatal("into the void");
log.flush();
Void::Testing::expect(true); // reached without crashing
}
Void::Testing::Test callback_logger_receives_entry_fields()
{
Entry got;
CallbackLogger log{[&](const Entry& e) { got = e; },
Mode::Immediate};
log.warning("payload");
Void::Testing::expect(got.level == Level::Warning);
Void::Testing::expect_eq(got.message, std::string{"payload"});
}
// ── MultiLogger ───────────────────────────────────────────────────────────────
Void::Testing::Test multi_logger_fans_out_to_all_children()
{
int a = 0;
int b = 0;
MultiLogger multi;
multi.add(std::make_shared<CallbackLogger>(
[&](const Entry&) { ++a; }, Mode::Immediate));
multi.add(std::make_shared<CallbackLogger>(
[&](const Entry&) { ++b; }, Mode::Immediate));
multi.info("to both");
Void::Testing::expect_eq(a, 1);
Void::Testing::expect_eq(b, 1);
Void::Testing::expect_eq(multi.child_count(), std::size_t{2});
}
Void::Testing::Test multi_logger_children_keep_own_levels()
{
int verbose_count = 0;
int errors_only = 0;
auto verbose = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++verbose_count; }, Mode::Immediate);
auto strict = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++errors_only; }, Mode::Immediate);
strict->set_level(Level::Error);
MultiLogger multi;
multi.add(verbose);
multi.add(strict);
multi.info("info");
multi.error("error");
Void::Testing::expect_eq(verbose_count, 2);
Void::Testing::expect_eq(errors_only, 1);
}
Void::Testing::Test multi_logger_relays_async_children_with_flush()
{
int delivered = 0;
auto async_child = std::make_shared<CallbackLogger>(
[&](const Entry&) { ++delivered; }); // Async by default
MultiLogger multi;
multi.add(async_child);
multi.info("queued in child");
multi.flush(); // flushes children too
Void::Testing::expect_eq(delivered, 1);
}
// ── ConsoleLogger + Formatter ─────────────────────────────────────────────────
Void::Testing::Test console_logger_uses_installed_formatter()
{
std::ostringstream out;
{
ConsoleLogger log{out, Mode::Immediate};
log.set_formatter(
std::make_shared<PatternFormatter>("{level}>{message}"));
log.info("custom format");
}
Void::Testing::expect_eq(out.str(),
std::string{"Info>custom format\n"});
}
// ── RotatingFileLogger ────────────────────────────────────────────────────────
class RotatingFileLoggerTests : public Void::Testing::Fixture
{
public:
std::filesystem::path dir;
std::filesystem::path file;
void setup() override
{
dir = std::filesystem::temp_directory_path() /
"void_rotating_test";
std::filesystem::remove_all(dir);
std::filesystem::create_directories(dir);
file = dir / "app.log";
}
void teardown() override { std::filesystem::remove_all(dir); }
static std::string slurp(const std::filesystem::path& p)
{
std::ifstream f(p);
return {std::istreambuf_iterator<char>(f), {}};
}
Void::Testing::Test writes_and_flushes()
{
{
RotatingFileLogger log{file};
log.info("rotating hello");
}
Void::Testing::expect(slurp(file).find("rotating hello") !=
std::string::npos);
}
Void::Testing::Test rotates_when_size_exceeded()
{
{
RotatingFileLogger::Options opt;
opt.max_bytes = 256;
opt.max_files = 3;
opt.mode = Mode::Immediate;
RotatingFileLogger log{file, opt};
for (int i = 0; i < 40; ++i) {
log.info("a reasonably long line to fill the file " +
std::to_string(i));
}
}
Void::Testing::expect(std::filesystem::exists(file));
auto rotated = file;
rotated += ".1";
Void::Testing::expect(std::filesystem::exists(rotated));
// The bound holds: no file beyond .3
auto beyond = file;
beyond += ".4";
Void::Testing::expect(!std::filesystem::exists(beyond));
}
Void::Testing::Test open_factory_rejects_bad_path()
{
auto r = RotatingFileLogger::open(
"/this/path/does/not/exist/app.log");
Void::Testing::expect(!r.has_value());
}
Void::Testing::Test async_rotation_under_load()
{
{
RotatingFileLogger::Options opt;
opt.max_bytes = 512;
opt.max_files = 2;
RotatingFileLogger log{file, opt}; // Async default
for (int i = 0; i < 200; ++i) {
log.info("async rotation line " + std::to_string(i));
}
log.flush();
}
Void::Testing::expect(std::filesystem::exists(file));
}
};