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

+1
View File
@@ -132,6 +132,7 @@ Void::Testing::Test log_adapter_routes_to_void_logging()
Void::Log::log(Void::Log::Level::Warning, "TestModule", "a warning");
Void::Log::set_sink({});
logger.flush(); // ConsoleLogger is async by default
const auto text = out.str();
Void::Testing::expect(text.find("hello from Void::Log") !=
+86
View File
@@ -0,0 +1,86 @@
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <optional>
#include <string>
#include <vector>
#ifdef VOID_HAS_CONFIG_REFLECTION
using Void::Configuration::Config;
namespace
{
enum class Sink { Console, File };
struct FileSettings {
std::string path = "default.log";
int max_files = 3;
};
struct LogSettings {
std::string level = "info";
bool async = true;
Sink sink = Sink::Console;
std::chrono::milliseconds flush_every{250};
FileSettings file;
std::optional<int> sample_rate;
std::vector<std::string> tags;
};
} // namespace
Void::Testing::Test bind_fills_present_keys_keeps_defaults()
{
Config cfg;
cfg.set("log.level", "debug");
cfg.set("log.file.path", "/var/log/app.log");
cfg.set("log.flush_every", "1s");
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
Void::Testing::expect(s.has_value());
Void::Testing::expect_eq(s->level, std::string{"debug"});
Void::Testing::expect(s->async); // default kept
Void::Testing::expect_eq(s->file.path, std::string{"/var/log/app.log"});
Void::Testing::expect_eq(s->file.max_files, 3); // nested default kept
Void::Testing::expect(s->flush_every ==
std::chrono::milliseconds{1000});
}
Void::Testing::Test bind_enum_optional_vector()
{
Config cfg;
cfg.set("log.sink", "File");
cfg.set("log.sample_rate", "10");
cfg.set("log.tags.0", "alpha");
cfg.set("log.tags.1", "beta");
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
Void::Testing::expect(s.has_value());
Void::Testing::expect(s->sink == Sink::File);
Void::Testing::expect(s->sample_rate.has_value());
Void::Testing::expect_eq(*s->sample_rate, 10);
Void::Testing::expect_eq(s->tags.size(), std::size_t{2});
Void::Testing::expect_eq(s->tags[1], std::string{"beta"});
}
Void::Testing::Test bind_reports_conversion_errors()
{
Config cfg;
cfg.set("log.async", "not-a-bool");
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
Void::Testing::expect(!s.has_value());
}
Void::Testing::Test bind_empty_prefix_binds_root_keys()
{
Config cfg;
cfg.set("path", "root.log");
const auto s = Void::Configuration::bind<FileSettings>(cfg);
Void::Testing::expect(s.has_value());
Void::Testing::expect_eq(s->path, std::string{"root.log"});
}
#endif // VOID_HAS_CONFIG_REFLECTION
+112
View File
@@ -0,0 +1,112 @@
#include <Void/Configuration/Config.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <cstdlib>
#include <string>
using Void::Configuration::Config;
// ── from_env_prefix ───────────────────────────────────────────────────────────
Void::Testing::Test env_prefix_strips_and_normalizes()
{
::setenv("VOIDTEST_LOG__LEVEL", "debug", 1);
::setenv("VOIDTEST_PORT", "9000", 1);
::setenv("UNRELATED_KEY", "x", 1);
const auto cfg = Config::from_env_prefix("VOIDTEST_");
Void::Testing::expect(cfg.get_or("log.level") ==
"debug");
Void::Testing::expect(cfg.get_or("port") ==
"9000");
Void::Testing::expect(!cfg.contains("unrelated_key"));
::unsetenv("VOIDTEST_LOG__LEVEL");
::unsetenv("VOIDTEST_PORT");
::unsetenv("UNRELATED_KEY");
}
// ── from_ini_text ─────────────────────────────────────────────────────────────
Void::Testing::Test ini_sections_become_prefixes()
{
const auto cfg = Config::from_ini_text(
"global_key = 1\n"
"[log]\n"
"level = warn\n"
"[net]\n"
"port = 4242\n");
Void::Testing::expect(cfg.has_value());
Void::Testing::expect(cfg->get_or("global_key") ==
"1");
Void::Testing::expect(cfg->get_or("log.level") ==
"warn");
Void::Testing::expect_eq(*cfg->get_as<int>("net.port"), 4242);
}
Void::Testing::Test ini_parse_error_surfaces()
{
const auto cfg = Config::from_ini_text("[unterminated\nkey=1\n");
Void::Testing::expect(!cfg.has_value());
}
// ── from_json_text ────────────────────────────────────────────────────────────
Void::Testing::Test json_objects_flatten_to_dotted_keys()
{
const auto cfg = Config::from_json_text(R"({
"log": {"level": "error", "async": true},
"servers": [{"host": "a"}, {"host": "b"}],
"ratio": 0.5,
"count": 3
})");
Void::Testing::expect(cfg.has_value());
Void::Testing::expect(cfg->get_or("log.level") ==
"error");
Void::Testing::expect(*cfg->get_as<bool>("log.async"));
Void::Testing::expect(cfg->get_or("servers.0.host") ==
"a");
Void::Testing::expect(cfg->get_or("servers.1.host") ==
"b");
Void::Testing::expect_eq(*cfg->get_as<double>("ratio"), 0.5);
Void::Testing::expect(cfg->get_or("count") ==
"3"); // integral form
}
Void::Testing::Test json_parse_error_surfaces()
{
Void::Testing::expect(!Config::from_json_text("{nope").has_value());
}
// ── from_args ─────────────────────────────────────────────────────────────────
Void::Testing::Test args_equals_space_and_flag_forms()
{
const char* argv[] = {"prog", "--log.level=debug",
"--net.port", "8080",
"--verbose", "positional",
"--trailing-flag"};
const auto cfg = Config::from_args(7, argv);
Void::Testing::expect(cfg.get_or("log.level") ==
"debug");
Void::Testing::expect(cfg.get_or("net.port") ==
"8080");
Void::Testing::expect(cfg.get_or("verbose") ==
"positional");
Void::Testing::expect(cfg.get_or("trailing-flag") ==
"true");
}
// ── overlay precedence ────────────────────────────────────────────────────────
Void::Testing::Test overlay_last_wins_across_sources()
{
auto base = Config::from_ini_text("[log]\nlevel = info\n");
Void::Testing::expect(base.has_value());
const char* argv[] = {"prog", "--log.level=trace"};
base->overlay(Config::from_args(2, argv));
Void::Testing::expect(base->get_or("log.level") ==
"trace");
}
+104
View File
@@ -0,0 +1,104 @@
#include <Void/Configuration/Config.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <string>
using Void::Configuration::Config;
namespace
{
enum class Color { Red, Green, Blue };
Config sample()
{
Config cfg;
cfg.set("port", "8080");
cfg.set("ratio", "0.25");
cfg.set("verbose", "TRUE");
cfg.set("quiet", "off");
cfg.set("color", "Green");
cfg.set("timeout", "250ms");
cfg.set("interval", "2m");
cfg.set("negative", "-42");
cfg.set("junk", "12abc");
return cfg;
}
} // namespace
Void::Testing::Test typed_int_and_double()
{
const auto cfg = sample();
Void::Testing::expect_eq(*cfg.get_as<int>("port"), 8080);
Void::Testing::expect_eq(*cfg.get_as<double>("ratio"), 0.25);
Void::Testing::expect_eq(*cfg.get_as<long>("negative"), -42L);
}
Void::Testing::Test typed_bool_spellings()
{
const auto cfg = sample();
Void::Testing::expect(*cfg.get_as<bool>("verbose"));
Void::Testing::expect(!*cfg.get_as<bool>("quiet"));
}
Void::Testing::Test typed_enum_by_name()
{
const auto cfg = sample();
const auto color = cfg.get_as<Color>("color");
Void::Testing::expect(color.has_value());
Void::Testing::expect(*color == Color::Green);
}
Void::Testing::Test typed_durations()
{
using namespace std::chrono;
const auto cfg = sample();
Void::Testing::expect(*cfg.get_as<milliseconds>("timeout") ==
milliseconds{250});
Void::Testing::expect(*cfg.get_as<seconds>("interval") ==
seconds{120});
}
Void::Testing::Test typed_errors_are_reported()
{
const auto cfg = sample();
Void::Testing::expect(!cfg.get_as<int>("junk").has_value());
Void::Testing::expect(!cfg.get_as<int>("missing").has_value());
Void::Testing::expect(!cfg.get_as<bool>("port").has_value());
Void::Testing::expect(!cfg.get_as<Color>("verbose").has_value());
}
Void::Testing::Test typed_get_or_as_fallback()
{
const auto cfg = sample();
Void::Testing::expect_eq(cfg.get_or_as<int>("port", 1), 8080);
Void::Testing::expect_eq(cfg.get_or_as<int>("missing", 7), 7);
}
Void::Testing::Test subtree_strips_prefix()
{
Config cfg;
cfg.set("log.level", "debug");
cfg.set("log.file.path", "/tmp/a.log");
cfg.set("net.port", "1");
const auto log = cfg.subtree("log");
Void::Testing::expect_eq(log.size(), std::size_t{2});
Void::Testing::expect(log.get_or("level") ==
"debug");
Void::Testing::expect(log.get_or("file.path") ==
"/tmp/a.log");
Void::Testing::expect(!log.contains("net.port"));
}
Void::Testing::Test keys_are_sorted()
{
Config cfg;
cfg.set("b", "2");
cfg.set("a", "1");
const auto keys = cfg.keys();
Void::Testing::expect_eq(keys.size(), std::size_t{2});
Void::Testing::expect_eq(keys[0], std::string{"a"});
Void::Testing::expect_eq(keys[1], std::string{"b"});
}
+116
View File
@@ -0,0 +1,116 @@
#include <Void/Configuration/Watch.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <mutex>
#include <string>
#include <vector>
using Void::Configuration::Config;
using Void::Configuration::ConfigWatch;
namespace
{
Void::FileSystem::FileWatcherOptions manual_poll()
{
return {.poll_interval = std::chrono::milliseconds{60'000},
.debounce_polls = 2};
}
int bump = 0;
void write(const std::filesystem::path& p, std::string_view text)
{
auto r = Void::FileSystem::write_file(p, text);
Void::Testing::expect(r.has_value());
const auto now = std::filesystem::file_time_type::clock::now();
std::filesystem::last_write_time(
p, now + std::chrono::milliseconds{(++bump) * 10});
}
} // namespace
Void::Testing::Test config_watch_reloads_and_diffs()
{
Void::FileSystem::TempDir tmp{"void_cfgwatch"};
const auto file = tmp.path() / "app.ini";
write(file, "[log]\nlevel = info\nkeep = 1\n");
std::mutex mu;
std::vector<std::string> last_changed;
std::string last_level;
auto watch = ConfigWatch::ini(
file,
[&](const Config& cfg, const std::vector<std::string>& changed) {
std::lock_guard lock(mu);
last_changed = changed;
last_level = cfg.get_or("log.level");
},
manual_poll());
Void::Testing::expect(watch.current().get_or("log.level") ==
"info");
write(file, "[log]\nlevel = debug\nkeep = 1\nadded = x\n");
watch.poll_now();
watch.poll_now(); // debounce satisfied -> reload + callback
std::lock_guard lock(mu);
Void::Testing::expect_eq(last_level, std::string{"debug"});
Void::Testing::expect_eq(last_changed.size(), std::size_t{2});
Void::Testing::expect_eq(last_changed[0], std::string{"log.added"});
Void::Testing::expect_eq(last_changed[1], std::string{"log.level"});
Void::Testing::expect(watch.current().get_or("log.level") ==
"debug");
}
Void::Testing::Test config_watch_keeps_old_config_on_parse_error()
{
Void::FileSystem::TempDir tmp{"void_cfgwatch"};
const auto file = tmp.path() / "app.ini";
write(file, "[log]\nlevel = info\n");
std::atomic<int> reloads{0};
auto watch = ConfigWatch::ini(
file,
[&](const Config&, const std::vector<std::string>&) {
++reloads;
},
manual_poll());
write(file, "[broken\nlevel=zzz\n"); // malformed section
watch.poll_now();
watch.poll_now();
Void::Testing::expect_eq(reloads.load(), 0);
Void::Testing::expect(watch.current().get_or("log.level") ==
"info");
}
Void::Testing::Test config_watch_deletion_keeps_last_config()
{
Void::FileSystem::TempDir tmp{"void_cfgwatch"};
const auto file = tmp.path() / "app.ini";
write(file, "[log]\nlevel = info\n");
std::atomic<int> reloads{0};
auto watch = ConfigWatch::ini(
file,
[&](const Config&, const std::vector<std::string>&) {
++reloads;
},
manual_poll());
std::filesystem::remove(file);
watch.poll_now();
watch.poll_now();
Void::Testing::expect_eq(reloads.load(), 0);
Void::Testing::expect(watch.current().get_or("log.level") ==
"info");
}
+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));
}
};
+136
View File
@@ -0,0 +1,136 @@
#include <Void/System/FileWatcher.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/TempDir.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <filesystem>
#include <thread>
using Void::FileSystem::FileWatcher;
namespace
{
// Long poll interval so only explicit poll_now() rounds matter.
FileWatcher::Options manual_poll()
{
return {.poll_interval = std::chrono::milliseconds{60'000},
.debounce_polls = 2};
}
int write_counter = 0;
void write(const std::filesystem::path& p, std::string_view text)
{
auto r = Void::FileSystem::write_file(p, text);
Void::Testing::expect(r.has_value());
// Nudge mtime forward — coarse filesystem timestamps could
// otherwise hide consecutive writes from the watcher.
const auto now = std::filesystem::file_time_type::clock::now();
std::filesystem::last_write_time(
p, now + std::chrono::milliseconds{(++write_counter) * 10});
}
} // namespace
Void::Testing::Test watcher_fires_after_debounce()
{
Void::FileSystem::TempDir tmp{"void_watch"};
const auto file = tmp.path() / "config.txt";
write(file, "v1");
std::atomic<int> fired{0};
FileWatcher watcher{manual_poll()};
watcher.watch(file, [&](const FileWatcher::Event& e) {
Void::Testing::expect(e.exists);
++fired;
});
write(file, "v2-with-different-size");
watcher.poll_now(); // change observed, stability count = 1
Void::Testing::expect_eq(fired.load(), 0);
watcher.poll_now(); // stable for 2 polls -> fires
Void::Testing::expect_eq(fired.load(), 1);
watcher.poll_now(); // no further change -> no further events
Void::Testing::expect_eq(fired.load(), 1);
}
Void::Testing::Test watcher_debounce_restarts_while_changing()
{
Void::FileSystem::TempDir tmp{"void_watch"};
const auto file = tmp.path() / "config.txt";
write(file, "v1");
std::atomic<int> fired{0};
FileWatcher watcher{manual_poll()};
watcher.watch(file, [&](const FileWatcher::Event&) { ++fired; });
write(file, "second version");
watcher.poll_now();
write(file, "third version, longer again");
watcher.poll_now(); // still changing -> debounce restarts
Void::Testing::expect_eq(fired.load(), 0);
watcher.poll_now();
Void::Testing::expect_eq(fired.load(), 1);
}
Void::Testing::Test watcher_reports_deletion()
{
Void::FileSystem::TempDir tmp{"void_watch"};
const auto file = tmp.path() / "config.txt";
write(file, "v1");
std::atomic<int> gone{0};
FileWatcher watcher{manual_poll()};
watcher.watch(file, [&](const FileWatcher::Event& e) {
if (!e.exists) {
++gone;
}
});
std::filesystem::remove(file);
watcher.poll_now();
watcher.poll_now();
Void::Testing::expect_eq(gone.load(), 1);
}
Void::Testing::Test watcher_unwatch_stops_events()
{
Void::FileSystem::TempDir tmp{"void_watch"};
const auto file = tmp.path() / "config.txt";
write(file, "v1");
std::atomic<int> fired{0};
FileWatcher watcher{manual_poll()};
watcher.watch(file, [&](const FileWatcher::Event&) { ++fired; });
Void::Testing::expect_eq(watcher.watch_count(), std::size_t{1});
watcher.unwatch(file);
Void::Testing::expect_eq(watcher.watch_count(), std::size_t{0});
write(file, "changed");
watcher.poll_now();
watcher.poll_now();
Void::Testing::expect_eq(fired.load(), 0);
}
// @tag integration
Void::Testing::Test watcher_background_thread_fires_on_its_own()
{
Void::FileSystem::TempDir tmp{"void_watch"};
const auto file = tmp.path() / "config.txt";
write(file, "v1");
std::atomic<int> fired{0};
FileWatcher watcher{
{.poll_interval = std::chrono::milliseconds{10},
.debounce_polls = 2}};
watcher.watch(file, [&](const FileWatcher::Event&) { ++fired; });
write(file, "v2 changed contents");
for (int i = 0; i < 200 && fired.load() == 0; ++i) {
std::this_thread::sleep_for(std::chrono::milliseconds{5});
}
Void::Testing::expect_eq(fired.load(), 1);
}