Files
Library/tests/standalone/Log/Sinks.cpp
T
faumarayandClaude Fable 5 c74a02a5a5 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>
2026-06-13 00:11:13 +03:00

184 lines
6.1 KiB
C++

#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));
}
};