diff --git a/CLAUDE.md b/CLAUDE.md index 3a1ac34..7f7bec6 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -105,19 +105,33 @@ Comment metadata (immediately preceding the function): The sweep in `cmake/VoidTesting.cmake` auto-applies the scan to every executable that transitively links `Void::Testing`. To opt a target out, set the `VOID_TESTING_NO_AUTO_SCAN` property; to opt in explicitly (e.g. for a target that doesn't link `Void::Testing` directly), call `void_add_tests()`. -### Logging module +### Logging -`Void::Logging::Logger` is an abstract base class. Derive from it to create a sink: +Two layers, both in the `Log` module: -1. **Override `write(const Entry&)`** — called per-entry in Immediate mode and by the default `on_flush` fallback. -2. **Optionally override `on_flush(std::span)`** — for batch/vectored I/O (e.g. file sinks). -3. **Call `flush()` in your derived destructor** — the base destructor does not flush because calling a pure virtual from `~Logger` is UB. Any unflushed entries remaining after your destructor are silently dropped. +**`Void::Log` facade** (`Log/Log.hpp`, header-only — usable from any module with zero link deps). Leveled function templates `Log::trace/debug/info/warn/error/fatal("Module.Feature", fmt, args...)` format lazily — with no sink installed a call is one relaxed atomic load and zero allocation. `set_sink(fn)` routes everything to any callable (this is the hook for external logging libraries; `LoggingAdapter.hpp` bridges to `Void::Logging`). `set_min_level` + `set_module_level` filter before formatting. **No macros** — this codebase forbids macro APIs; behavior toggles are runtime options. -Key design points: -- Virtual extension points (`write`, `on_flush`) are called **outside** the internal mutex, so derived classes can do blocking I/O or acquire their own locks freely. -- `Level::Disabled` suppresses all output. Levels are ordered: `Trace < Debug < Info < Warning < Error < Fatal`. -- `push_scope(name)` returns a `[[nodiscard]]` RAII `ScopedContext` that emits `ScopeEnter`/`ScopeExit` entries and annotates all entries logged in that thread with a breadcrumb. `scope(name)` emits the boundary pair immediately without touching the scope stack. -- `make_preset(level, prefix)` returns a `Preset` — a non-owning callable that bakes in a level and optional prefix. Presets must not outlive their logger. +**`Void::Logging::Logger`** — abstract sink base class, **async by default**: entries go through a lock-free MPSC queue to a logger-owned worker thread that delivers batches via `on_flush`. `Mode::Immediate`/`Buffered` make the same class synchronous (constructor arg or `set_mode` — no separate async/sync classes). Async capacity + `OverflowPolicy{Block,DropNewest,DropOldest}` bound the queue. `flush()` blocks until everything submitted before the call is delivered; it is virtual so composite sinks propagate it. + +Deriving a sink: +1. **Override `write(const Entry&)`** — called per-entry (worker thread in Async mode). +2. **Optionally override `on_flush(std::span)`** — for batch I/O. +3. **Call `flush()` in your derived destructor** — the base destructor only stops/joins the worker (calling a pure virtual from `~Logger` is UB); entries left after your destructor are silently dropped. + +Shipped sinks: `ConsoleLogger` (colors via Stacktrace), `FileLogger`, `RotatingFileLogger` (size rotation, max files), `NullLogger`, `CallbackLogger`, `MultiLogger` (tee; uses `Logger::relay`), `SyslogLogger` (POSIX). Sinks accept a `Formatter` (`PatternFormatter` with `{time}/{level}/{scopes}/{message}/...` placeholders, `JsonLinesFormatter`, `LogfmtFormatter`). + +`Logging::from_config(cfg)` builds the whole tree from `Configuration::Config` keys (`log.sinks`, `log.level`, `log.format`, `log.async`, ...); `apply_facade_config` sets facade levels. + +Other key points: +- Virtual extension points are called **outside** any internal lock. +- `Level::Disabled` suppresses all output. `Trace < Debug < ... < Fatal`. +- `push_scope(name)` returns a RAII `ScopedContext` (breadcrumbs in `Entry::scopes`); `scope(name)` emits a boundary pair without touching the stack. +- `make_preset(level, prefix)` returns a non-owning `Preset` callable. +- Stop logging from other threads before destroying a logger. + +### Configuration module + +`Configuration::Config`: flat string store with dotted keys. Sources (overlay-composable, last wins): `from_env`, `from_env_prefix("APP_")` (`__`→`.`, lowercased), `from_file` (KEY=VALUE), `from_ini`, `from_json` (flattened), `from_args` (`--key=value`). Typed access `get_as` / `get_or_as` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind(cfg, prefix)` fills an aggregate via P2996 (defaults = schema). `Watch.hpp`: `ConfigWatch` reloads a file on change with per-key diff (debounced polling via `FileSystem::FileWatcher` in `System`). ## Code style diff --git a/include/Void/Async/ThreadPool.hpp b/include/Void/Async/ThreadPool.hpp index a98b602..922f362 100644 --- a/include/Void/Async/ThreadPool.hpp +++ b/include/Void/Async/ThreadPool.hpp @@ -26,15 +26,12 @@ namespace Void::Concurrency for (std::size_t i = 0; i < count; ++i) { workers_.emplace_back([this] { worker_loop(); }); } - Void::Log::log( - Void::Log::Level::Debug, "Concurrency", - std::format("ThreadPool: started with {} threads", count)); + Void::Log::debug("Concurrency", "ThreadPool: started with {} threads", count); } ~ThreadPool() { - Void::Log::log(Void::Log::Level::Debug, "Concurrency", - "ThreadPool: stopping"); + Void::Log::debug("Concurrency", "ThreadPool: stopping"); { std::unique_lock lock{mu_}; stop_ = true; diff --git a/include/Void/Configuration/Bind.hpp b/include/Void/Configuration/Bind.hpp new file mode 100644 index 0000000..415e66d --- /dev/null +++ b/include/Void/Configuration/Bind.hpp @@ -0,0 +1,168 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#if __has_include() +#include +#define VOID_HAS_CONFIG_REFLECTION 1 +#endif + +// ── Reflection config binding +// ───────────────────────────────────────────────── Fill an aggregate struct +// from a Config using P2996 reflection: each data member binds to the dotted +// key matching its name (under an optional prefix); nested aggregates extend +// the prefix. The default-initialized member values double as the schema's +// defaults — a missing key keeps the default, a present key that fails +// conversion is an error. +// +// struct LogSettings { +// std::string level = "info"; +// bool async = true; +// std::chrono::milliseconds flush_every{250}; +// }; +// auto s = Void::Configuration::bind(cfg, "log"); +// +// Supported member types: everything Config::get_as accepts (string, +// bool, arithmetic, enums, chrono durations), std::optional, +// std::vector (keys "name.0", "name.1", ...), nested aggregates. + +namespace Void::Configuration +{ + +#ifdef VOID_HAS_CONFIG_REFLECTION + + namespace BindDetail + { + template struct IsOptional : std::false_type { + }; + template + struct IsOptional> : std::true_type { + }; + + template struct IsVector : std::false_type { + }; + template struct IsVector> : std::true_type { + }; + + template struct IsDuration : std::false_type { + }; + template + struct IsDuration> : std::true_type { + }; + + template + concept Leaf = std::is_same_v || + std::is_same_v || std::is_arithmetic_v || + std::is_enum_v || IsDuration::value; + + template + concept BindableAggregate = + std::is_aggregate_v && !std::is_array_v && + std::is_default_constructible_v; + + [[nodiscard]] inline std::string join(std::string_view prefix, + std::string_view name) + { + if (prefix.empty()) { + return std::string{name}; + } + return std::string{prefix} + "." + std::string{name}; + } + + template + Void::Result::Result + bind_into(const Config& cfg, std::string_view prefix) + { + T out{}; + std::optional failure; + + static constexpr auto members = + std::define_static_array(std::meta::nonstatic_data_members_of( + ^^T, std::meta::access_context::current())); + + template for (constexpr auto m : members) + { + if (!failure) { + constexpr auto name = std::meta::identifier_of(m); + using MT = [:std::meta::type_of(m):]; + const auto key = join(prefix, name); + + if constexpr (BindableAggregate && !Leaf) { + auto nested = bind_into(cfg, key); + if (!nested.has_value()) { + failure = std::move(nested).error(); + } else { + out.[:m:] = std::move(*nested); + } + } else if constexpr (IsOptional::value) { + using U = typename MT::value_type; + if (cfg.contains(key)) { + auto v = cfg.get_as(key); + if (!v.has_value()) { + failure = std::move(v).error(); + } else { + out.[:m:] = std::move(*v); + } + } + } else if constexpr (IsVector::value) { + using U = typename MT::value_type; + MT items; + for (std::size_t i = 0;; ++i) { + const auto item_key = key + "." + std::to_string(i); + if (!cfg.contains(item_key)) { + break; + } + auto v = cfg.get_as(item_key); + if (!v.has_value()) { + failure = std::move(v).error(); + break; + } + items.push_back(std::move(*v)); + } + if (!failure && !items.empty()) { + out.[:m:] = std::move(items); + } + } else { + static_assert(Leaf, + "member type not bindable from Config"); + if (cfg.contains(key)) { + auto v = cfg.get_as(key); + if (!v.has_value()) { + failure = std::move(v).error(); + } else { + out.[:m:] = std::move(*v); + } + } + // absent key: keep the default member value + } + } + } + + if (failure) { + return Void::Result::fail(std::move(*failure)); + } + return Void::Result::ok(std::move(out)); + } + } // namespace BindDetail + + /// Bind cfg's keys under `prefix` into a default-constructed T. + template + [[nodiscard]] Void::Result::Result + bind(const Config& cfg, std::string_view prefix = {}) + { + return BindDetail::bind_into(cfg, prefix); + } + +#endif // VOID_HAS_CONFIG_REFLECTION + +} // namespace Void::Configuration diff --git a/include/Void/Configuration/Config.hpp b/include/Void/Configuration/Config.hpp index 724df79..7b8621e 100644 --- a/include/Void/Configuration/Config.hpp +++ b/include/Void/Configuration/Config.hpp @@ -1,30 +1,53 @@ #pragma once #include +#include +#include +#include #include #include #include #include +#include +#include +#include +#include +#include #include #include +#include #include #include #include +#include #include +#include + +#if defined(__unix__) || defined(__APPLE__) +extern char** environ; // NOLINT +#define VOID_CONFIG_HAS_ENVIRON 1 +#endif namespace Void::Configuration { -/// Layered key-value configuration store. +/// Layered key-value configuration store with dotted nested keys. /// -/// Values are plain strings. Layers are applied via overlay(): the last -/// overlay wins on key conflicts. Typical usage: +/// Values are plain strings; typed access via get_as(). Layers are +/// applied via overlay(): the last overlay wins on key conflicts. +/// Typical usage: /// -/// auto cfg = Config::from_env({"DB_HOST", "DB_PORT"}); -/// if (auto r = Config::from_file(".env"); r.has_value()) -/// cfg.overlay(*r); // file values override env -/// cfg.set("DB_PORT", "5433"); // explicit override wins everything +/// auto cfg = Config::from_env_prefix("MYAPP_"); // MYAPP_LOG__LEVEL → log.level +/// if (auto r = Config::from_ini("app.ini"); r.has_value()) +/// cfg.overlay(*r); // ini overrides env +/// cfg.overlay(Config::from_args(argc, argv)); // --log.level=debug wins +/// auto level = cfg.get_or("log.level", "info"); +/// auto retries = cfg.get_as("net.retries"); // Result +/// +/// Sources: from_env / from_env_prefix (environment), from_file +/// (KEY=VALUE), from_ini (sections become key prefixes), from_json +/// (nested objects flatten into dotted keys), from_args (--key=value). class Config { public: @@ -40,9 +63,7 @@ class Config for (auto key : keys) { if (auto r = get_env(key); r.has_value()) { cfg.values_.emplace(std::string{key}, std::move(*r)); - Void::Log::log( - Void::Log::Level::Debug, "Configuration", - std::format("from_env: loaded '{}'", key)); + Void::Log::debug("Configuration", "from_env: loaded '{}'", key); } } return cfg; @@ -76,10 +97,8 @@ class Config } auto eq = sv.find('='); if (eq == std::string_view::npos) { - Void::Log::log( - Void::Log::Level::Warning, "Configuration", - std::format("from_file: '{}' line {}: missing '='", - path.string(), lineno)); + Void::Log::warn("Configuration", "from_file: '{}' line {}: missing '='", + path.string(), lineno); continue; } auto key = sv.substr(0, eq); @@ -89,10 +108,8 @@ class Config auto val = sv.substr(eq + 1); cfg.values_.emplace(std::string{key}, std::string{val}); } - Void::Log::log( - Void::Log::Level::Debug, "Configuration", - std::format("from_file: loaded {} keys from '{}'", - cfg.values_.size(), path.string())); + Void::Log::debug("Configuration", "from_file: loaded {} keys from '{}'", + cfg.values_.size(), path.string()); return Void::Result::ok(std::move(cfg)); } @@ -136,8 +153,373 @@ class Config } [[nodiscard]] bool empty() const noexcept { return values_.empty(); } + // ═════════════════════════════════════════════════════════════════ + // Additional sources + // ═════════════════════════════════════════════════════════════════ + + /// Scan the whole environment for variables starting with `prefix`. + /// The prefix is stripped, `__` becomes `.`, and the key is + /// lowercased: MYAPP_LOG__LEVEL=debug → log.level=debug. + [[nodiscard]] static Config from_env_prefix(std::string_view prefix) + { + Config cfg; +#ifdef VOID_CONFIG_HAS_ENVIRON + for (char** env = environ; *env != nullptr; ++env) { + const std::string_view kv{*env}; + const auto eq = kv.find('='); + if (eq == std::string_view::npos || + !kv.starts_with(prefix)) { + continue; + } + auto raw_key = kv.substr(prefix.size(), eq - prefix.size()); + std::string key; + key.reserve(raw_key.size()); + for (std::size_t i = 0; i < raw_key.size(); ++i) { + if (raw_key[i] == '_' && i + 1 < raw_key.size() && + raw_key[i + 1] == '_') { + key += '.'; + ++i; + } + else { + key += static_cast(std::tolower( + static_cast(raw_key[i]))); + } + } + cfg.values_.emplace(std::move(key), + std::string{kv.substr(eq + 1)}); + } + Void::Log::debug("Configuration", + "from_env_prefix('{}'): {} keys", prefix, + cfg.size()); +#else + (void)prefix; +#endif + return cfg; + } + + /// Parse an INI file: `[section]` + `key = value` becomes + /// "section.key"; pairs before any section keep their bare key. + [[nodiscard]] static Void::Result::Result + from_ini(const std::filesystem::path& path) + { + auto text = Void::FileSystem::read_file(path); + if (!text.has_value()) { + return Void::Result::fail( + std::format("Configuration::Config::from_ini: {}", + text.error().message())); + } + return from_ini_text(*text); + } + + [[nodiscard]] static Void::Result::Result + from_ini_text(std::string_view text) + { + Void::Ini::IniFile ini; + if (auto err = Void::Ini::IniFile::parse(ini, text); + err.has_value()) { + return Void::Result::fail(std::format( + "Configuration::Config::from_ini: line {}: {}", + err->line, err->message)); + } + Config cfg; + for (const auto& name : ini.sections()) { + const auto* section = ini.section(name); + if (section == nullptr) { + continue; + } + for (const auto& [key, value] : *section) { + auto full = + name.empty() ? key : name + "." + key; + cfg.values_.insert_or_assign(std::move(full), value); + } + } + return Void::Result::ok(std::move(cfg)); + } + + /// Parse a JSON file; nested objects flatten into dotted keys, + /// arrays into numeric segments ("servers.0.host"). Scalars are + /// stored in their canonical string form. + [[nodiscard]] static Void::Result::Result + from_json(const std::filesystem::path& path) + { + auto text = Void::FileSystem::read_file(path); + if (!text.has_value()) { + return Void::Result::fail( + std::format("Configuration::Config::from_json: {}", + text.error().message())); + } + return from_json_text(*text); + } + + [[nodiscard]] static Void::Result::Result + from_json_text(std::string_view text) + { + auto parsed = Void::Json::parse(text); + if (!parsed.has_value()) { + return Void::Result::fail(std::format( + "Configuration::Config::from_json: line {} col {}: {}", + parsed.error().line, parsed.error().col, + parsed.error().message)); + } + Config cfg; + flatten_json(cfg, "", *parsed); + return Void::Result::ok(std::move(cfg)); + } + + /// Collect `--key=value`, `--key value` and bare `--flag` + /// (stored as "true") arguments. Non-option arguments are ignored. + [[nodiscard]] static Config from_args(int argc, + const char* const* argv) + { + Config cfg; + for (int i = 1; i < argc; ++i) { + const std::string_view arg{argv[i]}; + if (!arg.starts_with("--") || arg.size() <= 2) { + continue; + } + const auto body = arg.substr(2); + if (const auto eq = body.find('='); + eq != std::string_view::npos) { + cfg.values_.insert_or_assign( + std::string{body.substr(0, eq)}, + std::string{body.substr(eq + 1)}); + } + else if (i + 1 < argc && + std::string_view{argv[i + 1]}.substr(0, 2) != + "--") { + cfg.values_.insert_or_assign(std::string{body}, + std::string{argv[i + 1]}); + ++i; + } + else { + cfg.values_.insert_or_assign(std::string{body}, + "true"); + } + } + return cfg; + } + + // ═════════════════════════════════════════════════════════════════ + // Typed access + // ═════════════════════════════════════════════════════════════════ + + /// Look up and convert. Supported T: integral and floating types, + /// bool ("true/false/1/0/yes/no/on/off", case-insensitive), enums + /// (by enumerator name, reflection builds), std::string, and + /// std::chrono durations ("250ms", "10s", "5m", "1h", "500us", + /// "30ns" — converted to T, rejecting lossy narrowing). + template + [[nodiscard]] Void::Result::Result + get_as(std::string_view key) const + { + const auto it = values_.find(std::string{key}); + if (it == values_.end()) { + return Void::Result::fail(std::format( + "Configuration::Config::get_as: key '{}' not found", + key)); + } + return convert(key, it->second); + } + + /// Typed lookup with fallback for missing keys. Conversion errors + /// on a *present* key still surface the fallback but are logged. + template + [[nodiscard]] T get_or_as(std::string_view key, T fallback) const + { + auto r = get_as(key); + if (r.has_value()) { + return std::move(*r); + } + return fallback; + } + + // ═════════════════════════════════════════════════════════════════ + // Key enumeration / subtrees + // ═════════════════════════════════════════════════════════════════ + + /// All keys, sorted. + [[nodiscard]] std::vector keys() const + { + std::vector out; + out.reserve(values_.size()); + for (const auto& [k, _] : values_) { + out.push_back(k); + } + std::sort(out.begin(), out.end()); + return out; + } + + /// A new Config holding every key under "prefix." with the prefix + /// stripped: subtree("log") of {log.level, log.file.path} yields + /// {level, file.path}. + [[nodiscard]] Config subtree(std::string_view prefix) const + { + Config out; + const auto full = std::string{prefix} + "."; + for (const auto& [k, v] : values_) { + if (k.starts_with(full)) { + out.values_.emplace(k.substr(full.size()), v); + } + } + return out; + } + + [[nodiscard]] bool contains(std::string_view key) const + { + return values_.contains(std::string{key}); + } + private: + static void flatten_json(Config& cfg, const std::string& prefix, + const Void::Json::Value& v) + { + using Void::Json::Value; + if (v.is_object()) { + for (const auto& [k, child] : v.as_object()) { + flatten_json( + cfg, prefix.empty() ? k : prefix + "." + k, child); + } + } + else if (v.is_array()) { + std::size_t i = 0; + for (const auto& child : v.as_array()) { + flatten_json(cfg, prefix + "." + std::to_string(i), + child); + ++i; + } + } + else if (v.is_string()) { + cfg.values_.insert_or_assign(prefix, v.as_string()); + } + else if (v.is_bool()) { + cfg.values_.insert_or_assign(prefix, + v.as_bool() ? "true" : "false"); + } + else if (v.is_number()) { + const double d = v.as_number(); + if (d == static_cast(static_cast(d))) { + cfg.values_.insert_or_assign( + prefix, + std::to_string(static_cast(d))); + } + else { + cfg.values_.insert_or_assign(prefix, + std::format("{}", d)); + } + } + // null: key omitted + } + + template + struct IsDuration : std::false_type {}; + template + struct IsDuration> + : std::true_type {}; + + template + static Void::Result::Result + convert(std::string_view key, const std::string& raw) + { + auto fail = [&](std::string_view what) { + return Void::Result::fail(std::format( + "Configuration::Config::get_as: key '{}': {} ('{}')", + key, what, raw)); + }; + + if constexpr (std::is_same_v) { + return Void::Result::ok(raw); + } + else if constexpr (std::is_same_v) { + std::string lower; + lower.reserve(raw.size()); + for (const char c : raw) { + lower += static_cast( + std::tolower(static_cast(c))); + } + if (lower == "true" || lower == "1" || lower == "yes" || + lower == "on") { + return Void::Result::ok(true); + } + if (lower == "false" || lower == "0" || lower == "no" || + lower == "off") { + return Void::Result::ok(false); + } + return fail("not a boolean"); + } + else if constexpr (std::is_enum_v) { +#ifdef VOID_HAS_ENUM_REFLECTION + if (auto e = Void::Detail::enum_parse(raw); + e.has_value()) { + return Void::Result::ok(*e); + } + return fail("no such enumerator"); +#else + return fail("enum parsing requires reflection"); +#endif + } + else if constexpr (IsDuration::value) { + auto parsed = parse_duration(raw); + if (!parsed.has_value()) { + return fail("not a duration (use e.g. 250ms, 10s, 5m)"); + } + return Void::Result::ok( + std::chrono::duration_cast(*parsed)); + } + else if constexpr (std::is_arithmetic_v) { + T value{}; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, value); + if (ec != std::errc{} || ptr != end) { + return fail("not a number"); + } + return Void::Result::ok(value); + } + else { + static_assert(std::is_same_v, + "unsupported get_as type"); + } + } + + static std::optional + parse_duration(const std::string& raw) + { + double number = 0; + const char* begin = raw.data(); + const char* end = raw.data() + raw.size(); + const auto [ptr, ec] = std::from_chars(begin, end, number); + if (ec != std::errc{} || ptr == begin) { + return std::nullopt; + } + const std::string_view suffix{ptr, end}; + using namespace std::chrono; + const auto as_ns = [&](auto unit) { + return std::optional{duration_cast( + duration{ + number})}; + }; + if (suffix == "ns") { + return as_ns(nanoseconds{}); + } + if (suffix == "us") { + return as_ns(microseconds{}); + } + if (suffix == "ms") { + return as_ns(milliseconds{}); + } + if (suffix == "s" || suffix.empty()) { + return as_ns(seconds{}); + } + if (suffix == "m") { + return as_ns(minutes{}); + } + if (suffix == "h") { + return as_ns(hours{}); + } + return std::nullopt; + } + std::unordered_map values_; }; diff --git a/include/Void/Configuration/Watch.hpp b/include/Void/Configuration/Watch.hpp new file mode 100644 index 0000000..e1748dc --- /dev/null +++ b/include/Void/Configuration/Watch.hpp @@ -0,0 +1,159 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace Void::Configuration +{ + /// Watches a configuration file and reloads it on change (debounced, + /// see FileSystem::FileWatcher). RAII: destroying the watch stops it. + /// + /// The callback receives the freshly loaded Config plus the sorted + /// list of keys whose values changed (added, removed, or modified) + /// relative to the previous load. A load failure keeps the previous + /// configuration and logs a warning — the callback is not invoked. + /// + /// Callbacks run on the watcher thread. + class ConfigWatch + { + public: + + using Loader = + std::function( + const std::filesystem::path&)>; + using OnReload = std::function& changed)>; + + ConfigWatch(std::filesystem::path path, Loader loader, + OnReload on_reload, + FileSystem::FileWatcherOptions options = {}) + : m_path(std::move(path)), m_loader(std::move(loader)), + m_on_reload(std::move(on_reload)), m_watcher(options) + { + if (auto initial = m_loader(m_path); initial.has_value()) { + m_current = std::move(*initial); + } + m_watcher.watch( + m_path, [this](const FileSystem::FileWatcher::Event& e) { + on_event(e); + }); + } + + /// Convenience factories for the built-in formats. + [[nodiscard]] static ConfigWatch + ini(std::filesystem::path path, OnReload on_reload, + FileSystem::FileWatcherOptions options = {}) + { + return ConfigWatch{std::move(path), + [](const std::filesystem::path& p) { + return Config::from_ini(p); + }, + std::move(on_reload), options}; + } + + [[nodiscard]] static ConfigWatch + json(std::filesystem::path path, OnReload on_reload, + FileSystem::FileWatcherOptions options = {}) + { + return ConfigWatch{std::move(path), + [](const std::filesystem::path& p) { + return Config::from_json(p); + }, + std::move(on_reload), options}; + } + + [[nodiscard]] static ConfigWatch + key_value(std::filesystem::path path, OnReload on_reload, + FileSystem::FileWatcherOptions options = {}) + { + return ConfigWatch{std::move(path), + [](const std::filesystem::path& p) { + return Config::from_file(p); + }, + std::move(on_reload), options}; + } + + /// The most recently loaded configuration (thread-safe copy). + [[nodiscard]] Config current() const + { + std::lock_guard lock(m_mutex); + return m_current; + } + + /// Force a poll round (mainly for tests). + void poll_now() { m_watcher.poll_now(); } + + private: + + void on_event(const FileSystem::FileWatcher::Event& event) + { + if (!event.exists) { + Void::Log::warn("Configuration.Watch", + "'{}' disappeared; keeping last config", + m_path.string()); + return; + } + auto loaded = m_loader(m_path); + if (!loaded.has_value()) { + Void::Log::warn( + "Configuration.Watch", + "reload of '{}' failed: {}; keeping last config", + m_path.string(), loaded.error().message()); + return; + } + + std::vector changed; + Config snapshot; + { + std::lock_guard lock(m_mutex); + changed = diff(m_current, *loaded); + m_current = std::move(*loaded); + snapshot = m_current; + } + Void::Log::info("Configuration.Watch", + "reloaded '{}' ({} keys changed)", + m_path.string(), changed.size()); + if (m_on_reload) { + m_on_reload(snapshot, changed); + } + } + + [[nodiscard]] static std::vector + diff(const Config& before, const Config& after) + { + std::vector changed; + for (const auto& key : after.keys()) { + const auto old_val = before.get(key); + if (!old_val.has_value() || *old_val != after.get_or(key)) { + changed.push_back(key); + } + } + for (const auto& key : before.keys()) { + if (!after.contains(key)) { + changed.push_back(key); + } + } + std::sort(changed.begin(), changed.end()); + return changed; + } + + std::filesystem::path m_path; + Loader m_loader; + OnReload m_on_reload; + mutable std::mutex m_mutex; + Config m_current; + FileSystem::FileWatcher m_watcher; // last: stops first on dtor + }; + +} // namespace Void::Configuration diff --git a/include/Void/Log/ConsoleLogger.hpp b/include/Void/Log/ConsoleLogger.hpp index 58f0d69..f5099b8 100644 --- a/include/Void/Log/ConsoleLogger.hpp +++ b/include/Void/Log/ConsoleLogger.hpp @@ -1,29 +1,33 @@ #pragma once +#include #include #include +#include namespace Void::Logging { /// Logger sink that writes formatted entries to a std::ostream. /// - /// Defaults to Mode::Immediate (each entry written as soon as it is - /// submitted) and to std::cerr if no stream is supplied. + /// Defaults to Mode::Async (entries delivered by the logger's worker + /// thread) and to std::cerr if no stream is supplied. Pass + /// Mode::Immediate for synchronous inline writes. /// /// When the Stacktrace module is present (VOID_HAS_STACKTRACE), each /// level prefix is colorized via Void::Stacktrace::Color helpers and /// honors Void::Stacktrace::Color::g_color_enabled. Without Stacktrace - /// the output is uncolored. + /// the output is uncolored. An installed Formatter replaces the + /// default "[Level] message" rendering (colors included). class ConsoleLogger final : public Logger { public: explicit ConsoleLogger(std::ostream& out, - Mode mode = Mode::Immediate, - std::size_t capacity = 0); + Mode mode = Mode::Async, + std::size_t capacity = 512); - /// Convenience constructor — writes to std::cerr in Immediate mode. + /// Convenience constructor — writes to std::cerr. ConsoleLogger(); ~ConsoleLogger() noexcept override; @@ -33,6 +37,12 @@ namespace Void::Logging ConsoleLogger(ConsoleLogger&&) = delete; ConsoleLogger& operator=(ConsoleLogger&&) = delete; + /// Install a formatter. Call before logging starts. + void set_formatter(std::shared_ptr formatter) + { + m_formatter = std::move(formatter); + } + protected: void write(const Entry& entry) override; @@ -40,6 +50,7 @@ namespace Void::Logging private: std::ostream& m_out; + std::shared_ptr m_formatter; }; } // namespace Void::Logging diff --git a/include/Void/Log/FileLogger.hpp b/include/Void/Log/FileLogger.hpp index 8d5464e..7f7bc94 100644 --- a/include/Void/Log/FileLogger.hpp +++ b/include/Void/Log/FileLogger.hpp @@ -1,8 +1,9 @@ #pragma once -#include #include #include +#include +#include #include #include @@ -13,9 +14,10 @@ namespace Void::Logging { /// Logger sink that appends formatted entries to a file on disk. /// - /// Defaults to Mode::Buffered with capacity 64 — entries are batched - /// via on_flush() and written using std::ofstream::flush() at the end - /// of every batch. The destructor flushes any remaining entries. + /// Defaults to Mode::Async — entries are queued lock-free and written + /// in batches by the logger's worker thread (one ofstream flush per + /// batch). The destructor flushes any remaining entries. Pass + /// Mode::Immediate/Buffered to opt out of the worker thread. /// /// Two construction paths: /// - `FileLogger::open(path)` returns @@ -30,8 +32,8 @@ namespace Void::Logging public: explicit FileLogger(const std::filesystem::path& path, - Mode mode = Mode::Buffered, - std::size_t capacity = 64); + Mode mode = Mode::Async, + std::size_t capacity = 512); ~FileLogger() noexcept override; @@ -45,8 +47,15 @@ namespace Void::Logging [[nodiscard]] static Void::Result:: Result, Void::Result::Error> open(const std::filesystem::path& path, - Mode mode = Mode::Buffered, - std::size_t capacity = 64); + Mode mode = Mode::Async, + std::size_t capacity = 512); + + /// Install a formatter replacing the default "[Level] message" + /// rendering. Call before logging starts. + void set_formatter(std::shared_ptr formatter) + { + m_formatter = std::move(formatter); + } protected: @@ -55,8 +64,11 @@ namespace Void::Logging private: + void append(const Entry& entry); + std::filesystem::path m_path; std::ofstream m_file; + std::shared_ptr m_formatter; }; } // namespace Void::Logging diff --git a/include/Void/Log/Formatter.hpp b/include/Void/Log/Formatter.hpp new file mode 100644 index 0000000..60cbf58 --- /dev/null +++ b/include/Void/Log/Formatter.hpp @@ -0,0 +1,103 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include + +namespace Void::Logging +{ + /// Renders one Entry into a single output line (no trailing newline — + /// the sink appends its own record separator). + /// + /// Formatters must be safe to share between sinks: format() is const + /// and implementations hold no mutable state. + class Formatter + { + public: + + virtual ~Formatter() = default; + + [[nodiscard]] virtual std::string + format(const Entry& entry) const = 0; + }; + + /// Placeholder-based text formatter. + /// + /// Supported placeholders inside the pattern string: + /// {time} — ISO-8601 UTC timestamp with milliseconds + /// {level} — level name (Trace, Debug, ...) + /// {thread} — producing thread id + /// {scopes} — "a.b.c " breadcrumb of the scope stack (empty if none) + /// {message} — the message text + /// {file} — source file basename + /// {line} — source line + /// {kind} — Message / ScopeEnter / ScopeExit + /// Everything else is copied verbatim. Unknown {names} stay literal. + /// + /// Default pattern: "{time} [{level}] {scopes}{message}" + class PatternFormatter final : public Formatter + { + public: + + explicit PatternFormatter( + std::string pattern = "{time} [{level}] {scopes}{message}"); + + [[nodiscard]] std::string format(const Entry& entry) const override; + + private: + + enum class Token { + Literal, + Time, + LevelName, + Thread, + Scopes, + Message, + File, + Line, + Kind + }; + + struct Segment { + Token token; + std::string literal; // only for Token::Literal + }; + + std::vector m_segments; + }; + + /// One compact JSON object per entry: + /// {"time":"...","level":"Info","thread":"...","scopes":[...], + /// "message":"...","file":"...","line":N} + class JsonLinesFormatter final : public Formatter + { + public: + + [[nodiscard]] std::string format(const Entry& entry) const override; + }; + + /// logfmt: time=... level=... thread=... msg="..." (scopes/file/line + /// included when present). + class LogfmtFormatter final : public Formatter + { + public: + + [[nodiscard]] std::string format(const Entry& entry) const override; + }; + + namespace FormatDetail + { + /// ISO-8601 UTC with milliseconds, e.g. "2026-06-12T10:30:00.123Z". + [[nodiscard]] std::string + iso8601(std::chrono::system_clock::time_point tp); + + /// Dotted scope breadcrumb ("net.tls"); empty when no scopes. + [[nodiscard]] std::string + scope_breadcrumb(const std::vector& scopes); + } // namespace FormatDetail + +} // namespace Void::Logging diff --git a/include/Void/Log/FromConfig.hpp b/include/Void/Log/FromConfig.hpp new file mode 100644 index 0000000..7b1d072 --- /dev/null +++ b/include/Void/Log/FromConfig.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include + +namespace Void::Logging +{ + /// Build a complete logger tree from configuration keys (all under + /// `prefix`, default "log"): + /// + /// log.level = trace|debug|info|warning|error|fatal|disabled + /// log.sinks = console,file,rotating,syslog (comma list; + /// default "console") + /// log.format = default|pattern|json|logfmt + /// log.pattern = "{time} [{level}] {scopes}{message}" + /// (used when format = pattern) + /// log.async = true|false (default true) + /// log.capacity = 512 (async queue bound) + /// log.overflow = block|drop_newest|drop_oldest + /// log.console.stream = stderr|stdout (default stderr) + /// log.file.path = app.log (required for "file") + /// log.rotating.path = app.log (required for "rotating") + /// log.rotating.max_kb = 1024 + /// log.rotating.max_files = 5 + /// log.syslog.identity = myapp (required for "syslog") + /// + /// One sink yields that sink directly; several are wrapped in a + /// MultiLogger; an empty sink list yields a NullLogger. + [[nodiscard]] Void::Result::Result, + Void::Result::Error> + from_config(const Configuration::Config& cfg, + std::string_view prefix = "log"); + + /// Apply `.level` and `.module_levels.*` to the + /// Void::Log facade (global min level + per-module overrides). Does + /// not install a sink. + void apply_facade_config(const Configuration::Config& cfg, + std::string_view prefix = "log"); + +} // namespace Void::Logging diff --git a/include/Void/Log/Log.hpp b/include/Void/Log/Log.hpp index ba144c5..505c498 100644 --- a/include/Void/Log/Log.hpp +++ b/include/Void/Log/Log.hpp @@ -1,10 +1,32 @@ #pragma once +#include +#include #include #include #include +#include #include +#include #include +// ── Void::Log — the emission facade +// ─────────────────────────────────────────── Header-only so every module +// (including INTERFACE libraries) can log with zero link dependencies. The full +// sink framework lives in Void::Logging (Logger.hpp); bridge with +// Void/Log/LoggingAdapter.hpp. +// +// Integration contract: +// * No sink installed (the default) — every call is a single relaxed +// atomic load; format arguments are NOT formatted. This is the +// "no logging at all" path. +// * set_sink(...) routes everything to any callable — your own logging +// library plugs in here. +// * set_min_level(Level::Disabled) silences without removing the sink. +// * Per-module overrides: set_module_level("Fsm", Level::Trace). +// +// The API is deliberately macro-free: leveled function templates take a +// std::format_string and only format after the level/sink gate passes. + namespace Void::Log { @@ -14,27 +36,35 @@ namespace Void::Log Info, Warning, Error, - Fatal + Fatal, + Disabled }; /// Signature for any log consumer. Three arguments: /// level — severity of the event - /// module — short library-internal label (e.g. "FileSystem", - /// "Concurrency") message — human-readable description - using Sink = std::function; + /// module — short library-internal label (e.g. "System.Process") + /// message — human-readable description + using Sink = std::function; namespace Detail { - struct SinkState { - Sink sink; - std::shared_mutex mutex; + struct State { + // Fast-path gates (checked before any locking or formatting). + std::atomic has_sink{false}; + std::atomic min_level{Level::Trace}; + std::atomic has_module_levels{false}; + + // Slow path. + Sink sink; + std::unordered_map module_levels; + std::shared_mutex mutex; }; - inline SinkState& sink_state() + inline State& state() { - static SinkState state; - return state; + static State s; + return s; } } // namespace Detail @@ -43,22 +73,131 @@ namespace Void::Log /// Thread-safe: the new sink is visible to all threads after this returns. inline void set_sink(Sink sink) { - auto& state = Detail::sink_state(); - std::unique_lock lock{state.mutex}; - state.sink = std::move(sink); + auto& s = Detail::state(); + std::unique_lock lock{s.mutex}; + s.sink = std::move(sink); + s.has_sink.store(static_cast(s.sink), std::memory_order_release); } - /// Emit one log event through the global sink. - /// No-op (zero allocation) if no sink is installed. - /// Thread-safe with respect to set_sink() and concurrent log() calls. + /// Global minimum level. Events below it are discarded before + /// formatting. Default: Trace (everything passes; the sink filters). + inline void set_min_level(Level level) noexcept + { + Detail::state().min_level.store(level, std::memory_order_relaxed); + } + + [[nodiscard]] inline Level min_level() noexcept + { + return Detail::state().min_level.load(std::memory_order_relaxed); + } + + /// Per-module minimum level override (exact label match). Overrides take + /// precedence over the global minimum — they can both raise and lower it. + inline void set_module_level(std::string_view module, Level level) + { + auto& s = Detail::state(); + std::unique_lock lock{s.mutex}; + s.module_levels.insert_or_assign(std::string{module}, level); + s.has_module_levels.store(true, std::memory_order_release); + } + + /// Remove a per-module override. + inline void clear_module_level(std::string_view module) + { + auto& s = Detail::state(); + std::unique_lock lock{s.mutex}; + s.module_levels.erase(std::string{module}); + s.has_module_levels.store(!s.module_levels.empty(), + std::memory_order_release); + } + + /// Would an event at `level` from `module` currently be emitted? + [[nodiscard]] inline bool enabled(Level level, std::string_view module) + { + auto& s = Detail::state(); + if (!s.has_sink.load(std::memory_order_relaxed)) { + return false; + } + if (level == Level::Disabled) { + return false; + } + if (s.has_module_levels.load(std::memory_order_acquire)) { + std::shared_lock lock{s.mutex}; + if (auto it = s.module_levels.find(std::string{module}); + it != s.module_levels.end()) { + return level >= it->second; + } + } + return level >= s.min_level.load(std::memory_order_relaxed); + } + + /// Emit one pre-formatted log event through the global sink. + /// No-op (zero allocation) when disabled. inline void log(Level level, std::string_view module, std::string_view message) { - auto& state = Detail::sink_state(); - std::shared_lock lock{state.mutex}; - if (state.sink) { - state.sink(level, module, message); + auto& s = Detail::state(); + if (!enabled(level, module)) { + return; + } + std::shared_lock lock{s.mutex}; + if (s.sink) { + s.sink(level, module, message); } } + /// Leveled, lazily-formatted emission: arguments are formatted only + /// after the level/sink gate passes. + template + void log(Level level, std::string_view module, + std::format_string fmt, Args&&... args) + { + if (!enabled(level, module)) { + return; + } + log(level, module, std::format(fmt, std::forward(args)...)); + } + + template + void trace(std::string_view module, std::format_string fmt, + Args&&... args) + { + log(Level::Trace, module, fmt, std::forward(args)...); + } + + template + void debug(std::string_view module, std::format_string fmt, + Args&&... args) + { + log(Level::Debug, module, fmt, std::forward(args)...); + } + + template + void info(std::string_view module, std::format_string fmt, + Args&&... args) + { + log(Level::Info, module, fmt, std::forward(args)...); + } + + template + void warn(std::string_view module, std::format_string fmt, + Args&&... args) + { + log(Level::Warning, module, fmt, std::forward(args)...); + } + + template + void error(std::string_view module, std::format_string fmt, + Args&&... args) + { + log(Level::Error, module, fmt, std::forward(args)...); + } + + template + void fatal(std::string_view module, std::format_string fmt, + Args&&... args) + { + log(Level::Fatal, module, fmt, std::forward(args)...); + } + } // namespace Void::Log diff --git a/include/Void/Log/Logger.hpp b/include/Void/Log/Logger.hpp index 189e6e8..ddfe1bf 100644 --- a/include/Void/Log/Logger.hpp +++ b/include/Void/Log/Logger.hpp @@ -1,42 +1,68 @@ #pragma once +#include #include #include +#include #include #include +#include #include #include #include +#include #include #include #include #include +#include #include #include namespace Void::Logging { - enum class Mode { Immediate, Buffered }; + /// Dispatch strategy. + /// Async — (default) entries are queued lock-free and delivered in + /// batches by a logger-owned worker thread. + /// Immediate — write() is called inline on the logging thread. + /// Buffered — entries accumulate and flush at capacity / on flush(). + enum class Mode { Async, Immediate, Buffered }; + + /// What happens in Async mode when pending entries reach capacity. + /// Block — (default) the logging thread waits for space; nothing + /// is ever lost. + /// DropNewest — the incoming entry is discarded. + /// DropOldest — the oldest pending entries are discarded by the worker + /// when it falls behind (soft bound: memory can briefly + /// exceed capacity until the next drain). + enum class OverflowPolicy { Block, DropNewest, DropOldest }; /// Abstract base class for all Void loggers. /// /// ## Responsibilities - /// - Level filtering (thread-safe) + /// - Level filtering (thread-safe, lock-free gate) /// - Entry construction: timestamp, thread_id, scope snapshot - /// - Immediate vs. Buffered dispatch (auto-flushes when buffer is full) - /// - Thread-safe submission — the internal mutex protects only the - /// buffer; virtual extension points are called *outside* the lock so - /// derived classes may perform blocking I/O or acquire their own - /// resources freely. + /// - Dispatch: Async (default, lock-free queue + owned worker thread + /// delivering batches), Immediate (inline), or Buffered (flush at + /// capacity). Switch at runtime with set_mode() — no separate + /// async/sync classes. + /// - Thread-safe submission — virtual extension points are called + /// *outside* any internal lock (from the worker thread in Async + /// mode) so derived classes may perform blocking I/O or acquire + /// their own resources freely. /// - Scoped context via per-thread RAII guards (Logger::ScopedContext) /// - Named scope logging: scope() emits ScopeEnter/ScopeExit entries /// - Logger presets via make_preset() — bake in a level (and optional /// message prefix) and later call with only the message/format args. /// - /// ## What this class deliberately does NOT do - /// - Spawn or manage threads / coroutines → use Void::Concurrency - /// - Open, close, or rotate files → use Void::Filesystem + /// ## Async mode notes + /// - capacity bounds the pending-entry queue; OverflowPolicy decides + /// what happens at the bound (Block by default — nothing is lost). + /// - flush() blocks until every entry submitted *before* the call has + /// been delivered. + /// - In Async mode write()/on_flush() run on the worker thread; sinks + /// need no additional synchronization of their own state. /// /// ## Deriving a logger /// 1. Override `write(const Entry&)` — called once per entry in @@ -47,7 +73,10 @@ namespace Void::Logging /// destructor runs. Calling a pure virtual from `~Logger` is /// undefined behaviour, so the base destructor does *not* flush; /// any unflushed entries that remain after your destructor will be - /// silently discarded. + /// silently discarded (the base destructor only stops and joins + /// the worker — it never invokes the virtuals). + /// 4. Stop logging from other threads before destroying the logger; + /// entries submitted concurrently with destruction are dropped. /// /// ## Example — minimal derived logger /// @code @@ -243,12 +272,19 @@ namespace Void::Logging // ========================================================================= // Lifetime // ========================================================================= - explicit Logger(Mode mode = Mode::Immediate, - std::size_t capacity = 512) noexcept; + /// @param mode Dispatch strategy; Async by default. + /// @param capacity Async: pending-queue bound (fixed for the + /// logger's lifetime). Buffered: auto-flush + /// threshold (adjustable). + /// @param policy Async overflow behaviour at capacity. + explicit Logger(Mode mode = Mode::Async, + std::size_t capacity = 512, + OverflowPolicy policy = + OverflowPolicy::Block) noexcept; - /// Does NOT flush remaining buffered entries — see class-level - /// note. - virtual ~Logger() noexcept = default; + /// Stops and joins the worker thread (Async). Does NOT flush + /// remaining entries — see class-level note. + virtual ~Logger() noexcept; Logger(const Logger&) = delete; Logger& operator=(const Logger&) = delete; @@ -264,23 +300,30 @@ namespace Void::Logging void set_level(Level level) noexcept; [[nodiscard]] Level level() const noexcept; - /// Switch between Immediate and Buffered mode. - /// If the buffer is non-empty when switching, it is flushed first. + /// Switch dispatch strategy at runtime (e.g. Async → Immediate + /// to make the logger synchronous). Pending entries are flushed + /// before the switch takes effect. void set_mode(Mode mode) noexcept; [[nodiscard]] Mode mode() const noexcept; /// Maximum number of entries held before an automatic flush - /// (Buffered mode only). + /// (Buffered mode only; the Async queue bound is fixed at + /// construction). void set_buffer_capacity(std::size_t n) noexcept; [[nodiscard]] std::size_t buffer_capacity() const noexcept; + [[nodiscard]] OverflowPolicy overflow_policy() const noexcept; + // ========================================================================= // Flush // ========================================================================= - /// Drain the buffer and deliver all pending entries via on_flush(). - /// No-op in Immediate mode. Thread-safe. - void flush(); + /// Deliver all pending entries. Async: blocks until everything + /// submitted before this call has been written. Buffered: drains + /// the buffer via on_flush(). Immediate: no-op. Thread-safe. + /// Virtual so composite sinks can propagate the flush to + /// children. + virtual void flush(); // ========================================================================= // Scoped context @@ -339,6 +382,12 @@ namespace Void::Logging std::source_location location = std::source_location::current()); + /// Route a fully-built Entry through this logger's level filter + /// and dispatch (queue / buffer / inline write). Meant for + /// composite sinks (e.g. MultiLogger) that fan entries out to + /// children without re-stamping timestamp/thread/scopes. + void relay(Entry entry); + void trace( std::string_view msg, std::source_location loc = std::source_location::current()); @@ -443,9 +492,25 @@ namespace Void::Logging private: - /// Build an Entry and route it to write() or the buffer. + /// Build an Entry and route it to the queue, write() or the + /// buffer depending on the active mode. void submit(Entry entry); + /// Async path: bounded enqueue honoring the overflow policy. + void async_submit(Entry entry); + + /// Start the worker thread on first use (Async mode). + void start_worker(); + + /// Wake the worker if it parked itself. + void wake_worker() noexcept; + + /// Worker: drain → on_flush batches → park when idle. + void worker_loop(); + + /// Async: block until everything submitted so far is written. + void drain_async(); + /// Emit a raw scope boundary entry; shared by push_scope and /// scope(). void emit_scope_boundary(Kind kind, @@ -453,12 +518,30 @@ namespace Void::Logging Level level, std::source_location loc); - Level m_level{Level::Trace}; - Mode m_mode; - std::size_t m_buffer_capacity; + std::atomic m_level{Level::Trace}; + std::atomic m_mode; + std::size_t m_async_capacity; + OverflowPolicy m_policy; mutable std::mutex m_mutex; - std::vector m_buffer; + std::vector m_buffer; // Buffered mode only + std::size_t m_buffer_capacity; + + // ── Async machinery ────────────────────────────────────────── + Void::Async::MpscQueue m_queue; + std::counting_semaphore<> m_space; // Block policy bound + // Counting (not binary): the worker's un-park path can leave a + // stale token behind, and a fresh release on top of it must + // not overflow. Extra tokens only cause spurious wakes, which + // the worker loop absorbs. + std::counting_semaphore<> m_wakeup{0}; + std::atomic m_sleeping{false}; + std::atomic m_stop{false}; + std::atomic m_worker_started{false}; + std::once_flag m_worker_once; + std::thread m_worker; + std::atomic m_submitted{0}; + std::atomic m_completed{0}; /// Per-thread scope stack. ScopedContext pushes/pops into this. static thread_local std::vector s_scope_stack; diff --git a/include/Void/Log/LoggingAdapter.hpp b/include/Void/Log/LoggingAdapter.hpp index 9fff183..d84ae19 100644 --- a/include/Void/Log/LoggingAdapter.hpp +++ b/include/Void/Log/LoggingAdapter.hpp @@ -41,6 +41,8 @@ namespace Void::Log return Void::Logging::Level::Error; case Level::Fatal: return Void::Logging::Level::Fatal; + case Level::Disabled: + return Void::Logging::Level::Disabled; } return Void::Logging::Level::Info; #endif diff --git a/include/Void/Log/RotatingFileLogger.hpp b/include/Void/Log/RotatingFileLogger.hpp new file mode 100644 index 0000000..7712033 --- /dev/null +++ b/include/Void/Log/RotatingFileLogger.hpp @@ -0,0 +1,82 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Logging +{ + /// File sink with size-based rotation. + /// + /// When the current file reaches `max_bytes` after a batch, files are + /// shifted (`app.log` → `app.log.1` → `app.log.2` …); at most + /// `max_files` rotated files are kept, the oldest is deleted. + /// + /// Defaults to Async dispatch — rotation and writes happen on the + /// worker thread. An optional Formatter overrides the default + /// "[Level] message" rendering; set it before logging starts. + struct RotatingFileOptions { + std::size_t max_bytes = 1024 * 1024; + std::size_t max_files = 5; + Mode mode = Mode::Async; + std::size_t capacity = 512; + OverflowPolicy policy = OverflowPolicy::Block; + }; + + class RotatingFileLogger final : public Logger + { + public: + + using Options = RotatingFileOptions; + + explicit RotatingFileLogger(const std::filesystem::path& path, + Options options = {}); + + ~RotatingFileLogger() noexcept override; + + RotatingFileLogger(const RotatingFileLogger&) = delete; + RotatingFileLogger& operator=(const RotatingFileLogger&) = delete; + RotatingFileLogger(RotatingFileLogger&&) = delete; + RotatingFileLogger& operator=(RotatingFileLogger&&) = delete; + + /// Non-throwing factory. + [[nodiscard]] static Void::Result:: + Result, Void::Result::Error> + open(const std::filesystem::path& path, Options options = {}); + + /// Install a formatter. Call before logging starts. + void set_formatter(std::shared_ptr formatter) + { + m_formatter = std::move(formatter); + } + + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return m_path; + } + + protected: + + void write(const Entry& entry) override; + void on_flush(std::span entries) override; + + private: + + void append(const Entry& entry); + void rotate_if_needed(); + + std::filesystem::path m_path; + Options m_options; + std::ofstream m_file; + std::size_t m_current_bytes{0}; + std::shared_ptr m_formatter; + }; + +} // namespace Void::Logging diff --git a/include/Void/Log/Sinks.hpp b/include/Void/Log/Sinks.hpp new file mode 100644 index 0000000..9aaba9f --- /dev/null +++ b/include/Void/Log/Sinks.hpp @@ -0,0 +1,114 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace Void::Logging +{ + /// Discards everything. Useful as a placeholder or for benchmarks. + class NullLogger final : public Logger + { + public: + + explicit NullLogger(Mode mode = Mode::Immediate) : Logger(mode) {} + + ~NullLogger() noexcept override { flush(); } + + protected: + + void write(const Entry&) override {} + }; + + /// Forwards every entry to a user callback. The simplest way to splice + /// an external logging library into the Logger framework. + class CallbackLogger final : public Logger + { + public: + + using Callback = std::function; + + explicit CallbackLogger( + Callback callback, + Mode mode = Mode::Async, + std::size_t capacity = 512, + OverflowPolicy policy = OverflowPolicy::Block) + : Logger(mode, capacity, policy), + m_callback(std::move(callback)) + { + } + + ~CallbackLogger() noexcept override { flush(); } + + protected: + + void write(const Entry& entry) override + { + if (m_callback) { + m_callback(entry); + } + } + + private: + + Callback m_callback; + }; + + /// Tee: relays every entry to each child logger. Children keep their + /// own modes, levels, and formatters. The MultiLogger itself defaults + /// to Immediate dispatch — the children already decide whether they + /// queue asynchronously, so double-queueing only adds latency. + class MultiLogger final : public Logger + { + public: + + explicit MultiLogger( + std::vector> children = {}, + Mode mode = Mode::Immediate) + : Logger(mode), m_children(std::move(children)) + { + } + + ~MultiLogger() noexcept override { flush(); } + + /// Add a child sink. Not thread-safe with concurrent logging — + /// assemble the tree before use. + void add(std::shared_ptr child) + { + if (child) { + m_children.push_back(std::move(child)); + } + } + + [[nodiscard]] std::size_t child_count() const noexcept + { + return m_children.size(); + } + + /// Flush own pending entries, then every child. + void flush() override + { + Logger::flush(); + for (const auto& child : m_children) { + child->flush(); + } + } + + protected: + + void write(const Entry& entry) override + { + for (const auto& child : m_children) { + child->relay(entry); + } + } + + private: + + std::vector> m_children; + }; + +} // namespace Void::Logging diff --git a/include/Void/Log/SyslogLogger.hpp b/include/Void/Log/SyslogLogger.hpp new file mode 100644 index 0000000..26aa4a5 --- /dev/null +++ b/include/Void/Log/SyslogLogger.hpp @@ -0,0 +1,44 @@ +#pragma once + +#if __has_include() +#define VOID_HAS_SYSLOG 1 + +#include + +#include + +namespace Void::Logging +{ + /// POSIX syslog(3) sink. Levels map onto syslog priorities + /// (Trace/Debug → LOG_DEBUG, Info → LOG_INFO, Warning → LOG_WARNING, + /// Error → LOG_ERR, Fatal → LOG_CRIT). + /// + /// Only one syslog identity exists per process (openlog is global), so + /// create at most one SyslogLogger at a time. + class SyslogLogger final : public Logger + { + public: + + explicit SyslogLogger(std::string identity, + Mode mode = Mode::Async, + std::size_t capacity = 512); + + ~SyslogLogger() noexcept override; + + SyslogLogger(const SyslogLogger&) = delete; + SyslogLogger& operator=(const SyslogLogger&) = delete; + SyslogLogger(SyslogLogger&&) = delete; + SyslogLogger& operator=(SyslogLogger&&) = delete; + + protected: + + void write(const Entry& entry) override; + + private: + + std::string m_identity; // must outlive openlog registration + }; + +} // namespace Void::Logging + +#endif // __has_include() diff --git a/include/Void/System/FileWatcher.hpp b/include/Void/System/FileWatcher.hpp new file mode 100644 index 0000000..fd4dbcc --- /dev/null +++ b/include/Void/System/FileWatcher.hpp @@ -0,0 +1,94 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Void::FileSystem +{ + /// Polling file watcher with debounce. + /// + /// One background thread polls every watched path's (mtime, size) at + /// `poll_interval`. After a change is observed, the callback fires only + /// once the metadata has been stable for `debounce_polls` consecutive + /// polls — this avoids reacting to half-written files (e.g. a .so or + /// config file still being copied). + /// + /// Callbacks run on the watcher thread; keep them short or hand off. + /// A path that disappears is reported once with `exists == false` and + /// again when it reappears (after debounce). + struct FileWatcherOptions { + std::chrono::milliseconds poll_interval{500}; + int debounce_polls = 2; + }; + + class FileWatcher + { + public: + + using Options = FileWatcherOptions; + + struct Event { + std::filesystem::path path; + bool exists; // false when the file vanished + }; + + using Callback = std::function; + + explicit FileWatcher(Options options = {}); + ~FileWatcher(); + + FileWatcher(const FileWatcher&) = delete; + FileWatcher& operator=(const FileWatcher&) = delete; + FileWatcher(FileWatcher&&) = delete; + FileWatcher& operator=(FileWatcher&&) = delete; + + /// Watch a path. Replaces any existing callback for it. + /// Thread-safe. + void watch(std::filesystem::path path, Callback callback); + + /// Stop watching a path. Thread-safe. + void unwatch(const std::filesystem::path& path); + + [[nodiscard]] std::size_t watch_count() const; + + /// Run one poll round immediately (test hook; also usable to + /// force a check without waiting out the interval). + void poll_now(); + + private: + + struct Signature { + bool exists = false; + std::filesystem::file_time_type mtime{}; + std::uintmax_t size = 0; + + bool operator==(const Signature&) const = default; + }; + + struct Entry { + Callback callback; + Signature accepted; // last state we reported (or initial) + Signature pending; // candidate new state being debounced + int stable_polls = 0; + bool dirty = false; // pending differs from accepted + }; + + static Signature stat(const std::filesystem::path& path); + void poll_round(); + void run(); + + Options m_options; + mutable std::mutex m_mutex; + std::condition_variable m_cv; + std::map m_watches; + bool m_stop = false; + std::thread m_thread; + }; + +} // namespace Void::FileSystem diff --git a/include/Void/System/Path.hpp b/include/Void/System/Path.hpp index b3d0d2f..d9712df 100644 --- a/include/Void/System/Path.hpp +++ b/include/Void/System/Path.hpp @@ -27,25 +27,21 @@ namespace Void::FileSystem { std::ifstream f{path, std::ios::binary}; if (!f.is_open()) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("read_file: cannot open '{}'", path.string())); + Void::Log::warn("FileSystem", "read_file: cannot open '{}'", path.string()); return Void::Result::fail(std::format( "FileSystem::read_file: cannot open '{}'", path.string())); } std::string content{std::istreambuf_iterator(f), std::istreambuf_iterator()}; if (f.bad()) { - Void::Log::log(Void::Log::Level::Warning, "FileSystem", - std::format("read_file: I/O error reading '{}'", - path.string())); + Void::Log::warn("FileSystem", "read_file: I/O error reading '{}'", + path.string()); return Void::Result::fail( std::format("FileSystem::read_file: I/O error reading '{}'", path.string())); } - Void::Log::log(Void::Log::Level::Debug, "FileSystem", - std::format("read_file: '{}' ({} bytes)", path.string(), - content.size())); + Void::Log::debug("FileSystem", "read_file: '{}' ({} bytes)", path.string(), + content.size()); return Void::Result::ok(std::move(content)); } @@ -58,18 +54,15 @@ namespace Void::FileSystem { std::ofstream f{path, std::ios::binary | std::ios::trunc}; if (!f.is_open()) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("write_file: cannot open '{}'", path.string())); + Void::Log::warn("FileSystem", "write_file: cannot open '{}'", path.string()); return Void::Result::fail(std::format( "FileSystem::write_file: cannot open '{}'", path.string())); } f.write(content.data(), static_cast(content.size())); f.flush(); if (!f.good()) { - Void::Log::log(Void::Log::Level::Warning, "FileSystem", - std::format("write_file: I/O error writing '{}'", - path.string())); + Void::Log::warn("FileSystem", "write_file: I/O error writing '{}'", + path.string()); return Void::Result::fail( std::format("FileSystem::write_file: I/O error writing '{}'", path.string())); @@ -99,17 +92,14 @@ namespace Void::FileSystem if (ec) { std::error_code ignore; std::filesystem::remove(staging, ignore); - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("atomic_write: rename failed for '{}': {}", - path.string(), ec.message())); + Void::Log::warn("FileSystem", "atomic_write: rename failed for '{}': {}", + path.string(), ec.message()); return Void::Result::fail(std::format( "FileSystem::atomic_write: rename failed for '{}': {}", path.string(), ec.message())); } - Void::Log::log(Void::Log::Level::Debug, "FileSystem", - std::format("atomic_write: '{}' committed ({} bytes)", - path.string(), content.size())); + Void::Log::debug("FileSystem", "atomic_write: '{}' committed ({} bytes)", + path.string(), content.size()); return {}; } @@ -124,17 +114,13 @@ namespace Void::FileSystem } std::filesystem::create_directories(path, ec); if (ec) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("ensure_directory: cannot create '{}': {}", - path.string(), ec.message())); + Void::Log::warn("FileSystem", "ensure_directory: cannot create '{}': {}", + path.string(), ec.message()); return Void::Result::fail(std::format( "FileSystem::ensure_directory: cannot create '{}': {}", path.string(), ec.message())); } - Void::Log::log( - Void::Log::Level::Debug, "FileSystem", - std::format("ensure_directory: created '{}'", path.string())); + Void::Log::debug("FileSystem", "ensure_directory: created '{}'", path.string()); return {}; } @@ -146,9 +132,8 @@ namespace Void::FileSystem std::error_code ec; std::filesystem::remove_all(path, ec); if (ec) { - Void::Log::log(Void::Log::Level::Warning, "FileSystem", - std::format("remove_path: cannot remove '{}': {}", - path.string(), ec.message())); + Void::Log::warn("FileSystem", "remove_path: cannot remove '{}': {}", + path.string(), ec.message()); return Void::Result::fail( std::format("FileSystem::remove_path: cannot remove '{}': {}", path.string(), ec.message())); diff --git a/include/Void/System/Query.hpp b/include/Void/System/Query.hpp index b4b7604..d004c9c 100644 --- a/include/Void/System/Query.hpp +++ b/include/Void/System/Query.hpp @@ -26,10 +26,8 @@ namespace Void::FileSystem std::error_code ec; auto sz = std::filesystem::file_size(path, ec); if (ec) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("file_size: cannot stat '{}': {}", path.string(), - ec.message())); + Void::Log::warn("FileSystem", "file_size: cannot stat '{}': {}", path.string(), + ec.message()); return Void::Result::fail( std::format("FileSystem::file_size: cannot stat '{}': {}", path.string(), ec.message())); @@ -45,10 +43,8 @@ namespace Void::FileSystem std::error_code ec; auto t = std::filesystem::last_write_time(path, ec); if (ec) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("last_modified: cannot stat '{}': {}", path.string(), - ec.message())); + Void::Log::warn("FileSystem", "last_modified: cannot stat '{}': {}", path.string(), + ec.message()); return Void::Result::fail( std::format("FileSystem::last_modified: cannot stat '{}': {}", path.string(), ec.message())); @@ -71,17 +67,14 @@ namespace Void::FileSystem entries.push_back(entry.path()); } if (ec) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("list_directory: cannot iterate '{}': {}", - path.string(), ec.message())); + Void::Log::warn("FileSystem", "list_directory: cannot iterate '{}': {}", + path.string(), ec.message()); return Void::Result::fail( std::format("FileSystem::list_directory: cannot iterate '{}': {}", path.string(), ec.message())); } - Void::Log::log(Void::Log::Level::Debug, "FileSystem", - std::format("list_directory: '{}' ({} entries)", - path.string(), entries.size())); + Void::Log::debug("FileSystem", "list_directory: '{}' ({} entries)", + path.string(), entries.size()); return Void::Result::ok(std::move(entries)); } @@ -96,17 +89,14 @@ namespace Void::FileSystem : std::filesystem::copy_options::none; std::filesystem::copy_file(src, dst, opts, ec); if (ec) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("copy_file: '{}' -> '{}': {}", src.string(), - dst.string(), ec.message())); + Void::Log::warn("FileSystem", "copy_file: '{}' -> '{}': {}", src.string(), + dst.string(), ec.message()); return Void::Result::fail( std::format("FileSystem::copy_file: '{}' -> '{}': {}", src.string(), dst.string(), ec.message())); } - Void::Log::log(Void::Log::Level::Debug, "FileSystem", - std::format("copy_file: '{}' -> '{}'", src.string(), - dst.string())); + Void::Log::debug("FileSystem", "copy_file: '{}' -> '{}'", src.string(), + dst.string()); return {}; } @@ -120,17 +110,14 @@ namespace Void::FileSystem std::filesystem::copy(src, dst, std::filesystem::copy_options::recursive, ec); if (ec) { - Void::Log::log( - Void::Log::Level::Warning, "FileSystem", - std::format("copy_dir: '{}' -> '{}': {}", src.string(), - dst.string(), ec.message())); + Void::Log::warn("FileSystem", "copy_dir: '{}' -> '{}': {}", src.string(), + dst.string(), ec.message()); return Void::Result::fail( std::format("FileSystem::copy_dir: '{}' -> '{}': {}", src.string(), dst.string(), ec.message())); } - Void::Log::log(Void::Log::Level::Debug, "FileSystem", - std::format("copy_dir: '{}' -> '{}'", src.string(), - dst.string())); + Void::Log::debug("FileSystem", "copy_dir: '{}' -> '{}'", src.string(), + dst.string()); return {}; } diff --git a/include/Void/System/TempDir.hpp b/include/Void/System/TempDir.hpp index 874ab1e..424f651 100644 --- a/include/Void/System/TempDir.hpp +++ b/include/Void/System/TempDir.hpp @@ -37,9 +37,7 @@ namespace Void::FileSystem ~TempDir() noexcept { if (!m_path.empty()) { - Void::Log::log( - Void::Log::Level::Debug, "FileSystem", - std::format("TempDir: removed '{}'", m_path.string())); + Void::Log::debug("FileSystem", "TempDir: removed '{}'", m_path.string()); std::error_code ignore; std::filesystem::remove_all(m_path, ignore); } @@ -113,9 +111,8 @@ namespace Void::FileSystem base / std::format("{}{:016x}", prefix, seed); std::error_code ec; if (std::filesystem::create_directory(candidate, ec)) { - Void::Log::log(Void::Log::Level::Debug, "FileSystem", - std::format("TempDir: created '{}'", - candidate.string())); + Void::Log::debug("FileSystem", "TempDir: created '{}'", + candidate.string()); return candidate; } } diff --git a/src/Configuration/module.cmake b/src/Configuration/module.cmake index ad6fbe3..bb07eea 100644 --- a/src/Configuration/module.cmake +++ b/src/Configuration/module.cmake @@ -1,3 +1,3 @@ void_add_module(Configuration - INTERNAL_DEPS Functional System + INTERNAL_DEPS Functional System Data ) diff --git a/src/Log/ConsoleLogger.cpp b/src/Log/ConsoleLogger.cpp index 48bfe3d..cd3f2df 100644 --- a/src/Log/ConsoleLogger.cpp +++ b/src/Log/ConsoleLogger.cpp @@ -89,7 +89,12 @@ namespace Void::Logging void ConsoleLogger::write(const Entry& entry) { - m_out << format_entry(entry); + if (m_formatter) { + m_out << m_formatter->format(entry) << '\n'; + } + else { + m_out << format_entry(entry); + } m_out.flush(); } diff --git a/src/Log/FileLogger.cpp b/src/Log/FileLogger.cpp index fefc425..5389234 100644 --- a/src/Log/FileLogger.cpp +++ b/src/Log/FileLogger.cpp @@ -13,14 +13,11 @@ namespace Void::Logging : Logger(mode, capacity), m_path(path), m_file(path, std::ios::app) { if (!m_file.is_open()) { - Void::Log::log( - Void::Log::Level::Warning, "Logging", - std::format("FileLogger: cannot open '{}'", path.string())); + Void::Log::warn("Logging", "FileLogger: cannot open '{}'", path.string()); throw std::runtime_error( std::format("FileLogger: cannot open '{}'", path.string())); } - Void::Log::log(Void::Log::Level::Debug, "Logging", - std::format("FileLogger: opened '{}'", path.string())); + Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string()); } Void::Result::Result, Void::Result::Error> @@ -39,24 +36,33 @@ namespace Void::Logging FileLogger::~FileLogger() noexcept { flush(); - Void::Log::log(Void::Log::Level::Debug, "Logging", - std::format("FileLogger: closed '{}'", - m_path.string())); + Void::Log::debug("Logging", "FileLogger: closed '{}'", + m_path.string()); } void FileLogger::write(const Entry& entry) { - m_file << std::format( - "[{}] {}\n", to_string(entry.level), entry.message); + append(entry); m_file.flush(); } void FileLogger::on_flush(std::span entries) { for (const auto& e : entries) { - m_file << std::format("[{}] {}\n", to_string(e.level), e.message); + append(e); } m_file.flush(); } + void FileLogger::append(const Entry& entry) + { + if (m_formatter) { + m_file << m_formatter->format(entry) << '\n'; + } + else { + m_file << std::format( + "[{}] {}\n", to_string(entry.level), entry.message); + } + } + } // namespace Void::Logging diff --git a/src/Log/Formatter.cpp b/src/Log/Formatter.cpp new file mode 100644 index 0000000..60f012f --- /dev/null +++ b/src/Log/Formatter.cpp @@ -0,0 +1,250 @@ +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Logging +{ + + namespace FormatDetail + { + + std::string iso8601(std::chrono::system_clock::time_point tp) + { + const auto ms = std::chrono::floor(tp); + return std::format("{:%FT%H:%M:%S}Z", ms); + } + + std::string scope_breadcrumb(const std::vector& scopes) + { + std::string out; + for (const auto& s : scopes) { + if (!out.empty()) { + out += '.'; + } + out += s; + } + return out; + } + + namespace + { + std::string thread_str(std::thread::id id) + { + std::ostringstream ss; + ss << id; + return ss.str(); + } + + std::string_view kind_str(Kind kind) + { + switch (kind) { + case Kind::Message: + return "Message"; + case Kind::ScopeEnter: + return "ScopeEnter"; + case Kind::ScopeExit: + return "ScopeExit"; + } + return "?"; + } + + std::string file_basename(const Entry& entry) + { + const char* file = entry.location.file_name(); + if (file == nullptr || *file == '\0') { + return {}; + } + return std::filesystem::path{file}.filename().string(); + } + } // namespace + + } // namespace FormatDetail + + // ============================================================================= + // PatternFormatter + // ============================================================================= + + PatternFormatter::PatternFormatter(std::string pattern) + { + using FormatDetail::scope_breadcrumb; + + std::string literal; + std::string_view rest{pattern}; + auto flush_literal = [&] { + if (!literal.empty()) { + m_segments.push_back({Token::Literal, std::move(literal)}); + literal = {}; + } + }; + + while (!rest.empty()) { + const auto open = rest.find('{'); + if (open == std::string_view::npos) { + literal += rest; + break; + } + literal += rest.substr(0, open); + rest.remove_prefix(open); + const auto close = rest.find('}'); + if (close == std::string_view::npos) { + literal += rest; + break; + } + const auto name = rest.substr(1, close - 1); + Token token = Token::Literal; + if (name == "time") { + token = Token::Time; + } else if (name == "level") { + token = Token::LevelName; + } else if (name == "thread") { + token = Token::Thread; + } else if (name == "scopes") { + token = Token::Scopes; + } else if (name == "message") { + token = Token::Message; + } else if (name == "file") { + token = Token::File; + } else if (name == "line") { + token = Token::Line; + } else if (name == "kind") { + token = Token::Kind; + } + + if (token == Token::Literal) { + // Unknown placeholder — keep it verbatim. + literal += rest.substr(0, close + 1); + } else { + flush_literal(); + m_segments.push_back({token, {}}); + } + rest.remove_prefix(close + 1); + } + flush_literal(); + } + + std::string PatternFormatter::format(const Entry& entry) const + { + std::string out; + for (const auto& seg : m_segments) { + switch (seg.token) { + case Token::Literal: + out += seg.literal; + break; + case Token::Time: + out += FormatDetail::iso8601(entry.timestamp); + break; + case Token::LevelName: + out += to_string(entry.level); + break; + case Token::Thread: + out += FormatDetail::thread_str(entry.thread_id); + break; + case Token::Scopes: + { + auto crumb = + FormatDetail::scope_breadcrumb(entry.scopes); + if (!crumb.empty()) { + out += crumb; + out += ' '; + } + break; + } + case Token::Message: + out += entry.message; + break; + case Token::File: + out += FormatDetail::file_basename(entry); + break; + case Token::Line: + out += std::to_string(entry.location.line()); + break; + case Token::Kind: + out += FormatDetail::kind_str(entry.kind); + break; + } + } + return out; + } + + // ============================================================================= + // JsonLinesFormatter + // ============================================================================= + + std::string JsonLinesFormatter::format(const Entry& entry) const + { + auto obj = Json::object(); + auto& o = obj.as_object(); + o.emplace_back("time", + Json::Value{FormatDetail::iso8601(entry.timestamp)}); + o.emplace_back("level", Json::Value{to_string(entry.level)}); + o.emplace_back("kind", Json::Value{FormatDetail::kind_str(entry.kind)}); + o.emplace_back("thread", + Json::Value{FormatDetail::thread_str(entry.thread_id)}); + if (!entry.scopes.empty()) { + auto arr = Json::array(); + arr.as_array().reserve(entry.scopes.size()); + for (const auto& s : entry.scopes) { + arr.as_array().emplace_back(s); + } + o.emplace_back("scopes", std::move(arr)); + } + o.emplace_back("message", Json::Value{entry.message}); + if (auto file = FormatDetail::file_basename(entry); !file.empty()) { + o.emplace_back("file", Json::Value{file}); + o.emplace_back( + "line", + Json::Value{static_cast(entry.location.line())}); + } + return Json::serialize(obj); + } + + // ============================================================================= + // LogfmtFormatter + // ============================================================================= + + namespace + { + void append_quoted(std::string& out, std::string_view value) + { + out += '"'; + for (const char c : value) { + if (c == '"' || c == '\\') { + out += '\\'; + } + out += c; + } + out += '"'; + } + } // namespace + + std::string LogfmtFormatter::format(const Entry& entry) const + { + std::string out; + out += "time="; + out += FormatDetail::iso8601(entry.timestamp); + out += " level="; + out += to_string(entry.level); + out += " thread="; + out += FormatDetail::thread_str(entry.thread_id); + if (auto crumb = FormatDetail::scope_breadcrumb(entry.scopes); + !crumb.empty()) { + out += " scopes="; + out += crumb; + } + if (auto file = FormatDetail::file_basename(entry); !file.empty()) { + out += " file="; + out += file; + out += ':'; + out += std::to_string(entry.location.line()); + } + out += " msg="; + append_quoted(out, entry.message); + return out; + } + +} // namespace Void::Logging diff --git a/src/Log/FromConfig.cpp b/src/Log/FromConfig.cpp new file mode 100644 index 0000000..d965b36 --- /dev/null +++ b/src/Log/FromConfig.cpp @@ -0,0 +1,259 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Logging +{ + + namespace + { + std::vector split_list(std::string_view csv) + { + std::vector out; + std::size_t start = 0; + while (start <= csv.size()) { + auto comma = csv.find(',', start); + if (comma == std::string_view::npos) { + comma = csv.size(); + } + auto item = csv.substr(start, comma - start); + while (!item.empty() && item.front() == ' ') { + item.remove_prefix(1); + } + while (!item.empty() && item.back() == ' ') { + item.remove_suffix(1); + } + if (!item.empty()) { + out.emplace_back(item); + } + start = comma + 1; + } + return out; + } + + std::optional parse_level(std::string_view name) + { + std::string lower; + for (const char c : name) { + lower += static_cast( + std::tolower(static_cast(c))); + } + if (lower == "trace") { + return Level::Trace; + } + if (lower == "debug") { + return Level::Debug; + } + if (lower == "info") { + return Level::Info; + } + if (lower == "warning" || lower == "warn") { + return Level::Warning; + } + if (lower == "error") { + return Level::Error; + } + if (lower == "fatal") { + return Level::Fatal; + } + if (lower == "disabled" || lower == "off") { + return Level::Disabled; + } + return std::nullopt; + } + + std::optional + parse_facade_level(std::string_view name) + { + const auto l = parse_level(name); + if (!l.has_value()) { + return std::nullopt; + } + switch (*l) { + case Level::Trace: + return Void::Log::Level::Trace; + case Level::Debug: + return Void::Log::Level::Debug; + case Level::Info: + return Void::Log::Level::Info; + case Level::Warning: + return Void::Log::Level::Warning; + case Level::Error: + return Void::Log::Level::Error; + case Level::Fatal: + return Void::Log::Level::Fatal; + case Level::Disabled: + return Void::Log::Level::Disabled; + } + return std::nullopt; + } + + std::shared_ptr + make_formatter(const Configuration::Config& cfg) + { + const auto format = cfg.get_or("format", "default"); + if (format == "pattern") { + return std::make_shared( + std::string{cfg.get_or( + "pattern", "{time} [{level}] {scopes}{message}")}); + } + if (format == "json") { + return std::make_shared(); + } + if (format == "logfmt") { + return std::make_shared(); + } + return nullptr; // "default": per-sink built-in rendering + } + + struct Dispatch { + Mode mode = Mode::Async; + std::size_t capacity = 512; + OverflowPolicy policy = OverflowPolicy::Block; + }; + + Dispatch make_dispatch(const Configuration::Config& cfg) + { + Dispatch d; + if (!cfg.get_or_as("async", true)) { + d.mode = Mode::Immediate; + } + d.capacity = cfg.get_or_as("capacity", 512); + const auto overflow = cfg.get_or("overflow", "block"); + if (overflow == "drop_newest") { + d.policy = OverflowPolicy::DropNewest; + } else if (overflow == "drop_oldest") { + d.policy = OverflowPolicy::DropOldest; + } + return d; + } + } // namespace + + Void::Result::Result, Void::Result::Error> + from_config(const Configuration::Config& cfg, std::string_view prefix) + { + const auto sub = cfg.subtree(prefix); + const auto dispatch = make_dispatch(sub); + const auto formatter = make_formatter(sub); + + std::vector> sinks; + for (const auto& name : split_list(sub.get_or("sinks", "console"))) { + if (name == "console") { + const bool to_stdout = + sub.get_or("console.stream", "stderr") == "stdout"; + auto sink = std::make_shared( + to_stdout ? std::cout : std::cerr, dispatch.mode, + dispatch.capacity); + if (formatter) { + sink->set_formatter(formatter); + } + sinks.push_back(std::move(sink)); + } else if (name == "file") { + const auto path = sub.get_or("file.path"); + if (path.empty()) { + return Void::Result::fail( + "Logging::from_config: sink 'file' needs " + "file.path"); + } + auto sink = FileLogger::open(std::filesystem::path{path}, + dispatch.mode, + dispatch.capacity); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + if (formatter) { + (*sink)->set_formatter(formatter); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "rotating") { + const auto path = sub.get_or("rotating.path"); + if (path.empty()) { + return Void::Result::fail( + "Logging::from_config: sink 'rotating' needs " + "rotating.path"); + } + RotatingFileLogger::Options opt; + opt.max_bytes = + sub.get_or_as("rotating.max_kb", 1024) * 1024; + opt.max_files = + sub.get_or_as("rotating.max_files", 5); + opt.mode = dispatch.mode; + opt.capacity = dispatch.capacity; + opt.policy = dispatch.policy; + auto sink = + RotatingFileLogger::open(std::filesystem::path{path}, opt); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + if (formatter) { + (*sink)->set_formatter(formatter); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "syslog") { +#ifdef VOID_HAS_SYSLOG + const auto identity = sub.get_or("syslog.identity"); + if (identity.empty()) { + return Void::Result::fail( + "Logging::from_config: sink 'syslog' needs " + "syslog.identity"); + } + sinks.push_back(std::make_shared( + std::string{identity}, dispatch.mode, dispatch.capacity)); +#else + return Void::Result::fail( + "Logging::from_config: syslog is not available on " + "this platform"); +#endif + } else { + return Void::Result::fail(std::format( + "Logging::from_config: unknown sink '{}'", name)); + } + } + + std::shared_ptr root; + if (sinks.empty()) { + root = std::make_shared(); + } else if (sinks.size() == 1) { + root = std::move(sinks.front()); + } else { + root = std::make_shared(std::move(sinks)); + } + + if (const auto level = parse_level(sub.get_or("level", "trace")); + level.has_value()) { + root->set_level(*level); + } + + Void::Log::debug("Logging", "from_config: built logger tree"); + return Void::Result::ok(std::move(root)); + } + + void apply_facade_config(const Configuration::Config& cfg, + std::string_view prefix) + { + const auto sub = cfg.subtree(prefix); + if (const auto level = parse_facade_level(sub.get_or("level", "")); + level.has_value()) { + Void::Log::set_min_level(*level); + } + for (const auto& key : sub.subtree("module_levels").keys()) { + const auto value = sub.get_or(std::string{"module_levels."} + key); + if (const auto level = parse_facade_level(value); + level.has_value()) { + Void::Log::set_module_level(key, *level); + } + } + } + +} // namespace Void::Logging diff --git a/src/Log/Logger.cpp b/src/Log/Logger.cpp index 6e1b3c8..4916edd 100644 --- a/src/Log/Logger.cpp +++ b/src/Log/Logger.cpp @@ -65,62 +65,85 @@ namespace Void::Logging // Logger — lifetime // ============================================================================= - Logger::Logger(Mode mode, std::size_t capacity) noexcept - : m_mode(mode), m_buffer_capacity(capacity) + Logger::Logger(Mode mode, std::size_t capacity, + OverflowPolicy policy) noexcept + : m_mode(mode), + m_async_capacity(capacity > 0 ? capacity : 1), + m_policy(policy), + m_buffer_capacity(capacity > 0 ? capacity : 1), + m_space(static_cast(capacity > 0 ? capacity : 1)) { - if (m_mode == Mode::Buffered) { + if (mode == Mode::Buffered) { m_buffer.reserve(m_buffer_capacity); } } + Logger::~Logger() noexcept + { + // Only stop and join the worker. Virtual extension points must not + // be touched here — the derived class is already destroyed. Pending + // entries are freed (silently dropped) by the queue's destructor. + m_stop.store(true, std::memory_order_release); + wake_worker(); + if (m_worker.joinable()) { + m_worker.join(); + } + } + // ============================================================================= // Configuration // ============================================================================= void Logger::set_level(Level level) noexcept { - std::lock_guard lock(m_mutex); - m_level = level; + m_level.store(level, std::memory_order_relaxed); } Level Logger::level() const noexcept { - std::lock_guard lock(m_mutex); - return m_level; + return m_level.load(std::memory_order_relaxed); } void Logger::set_mode(Mode mode) noexcept { - std::vector to_flush; - { - std::lock_guard lock(m_mutex); - if (m_mode == mode) { - return; - } - // Flush any buffered entries before switching modes. - to_flush = std::move(m_buffer); - m_buffer = {}; - m_mode = mode; + const Mode old = m_mode.load(std::memory_order_acquire); + if (old == mode) { + return; + } - if (m_mode == Mode::Buffered) { - m_buffer.reserve(m_buffer_capacity); + // Deliver everything pending under the old strategy first so no + // entry is stranded in a queue/buffer nobody drains anymore. + if (old == Mode::Async) { + drain_async(); + } + else if (old == Mode::Buffered) { + std::vector to_flush; + { + std::lock_guard lock(m_mutex); + to_flush = std::move(m_buffer); + m_buffer = {}; + } + if (!to_flush.empty()) { + on_flush(to_flush); } } - if (!to_flush.empty()) { - on_flush(to_flush); // called outside the lock + + if (mode == Mode::Buffered) { + std::lock_guard lock(m_mutex); + m_buffer.reserve(m_buffer_capacity); } + m_mode.store(mode, std::memory_order_release); } Mode Logger::mode() const noexcept { - std::lock_guard lock(m_mutex); - return m_mode; + return m_mode.load(std::memory_order_acquire); } void Logger::set_buffer_capacity(std::size_t n) noexcept { std::lock_guard lock(m_mutex); - m_buffer_capacity = n; + m_buffer_capacity = n > 0 ? n : 1; } std::size_t Logger::buffer_capacity() const noexcept @@ -129,6 +152,11 @@ namespace Void::Logging return m_buffer_capacity; } + OverflowPolicy Logger::overflow_policy() const noexcept + { + return m_policy; + } + // ============================================================================= // Scoped context // ============================================================================= @@ -194,6 +222,11 @@ namespace Void::Logging submit(std::move(entry)); } + void Logger::relay(Entry entry) + { + submit(std::move(entry)); + } + void Logger::trace(std::string_view msg, std::source_location loc) { log(Level::Trace, msg, loc); @@ -225,6 +258,10 @@ namespace Void::Logging void Logger::flush() { + if (m_mode.load(std::memory_order_acquire) == Mode::Async) { + drain_async(); + return; + } std::vector to_flush; { std::lock_guard lock(m_mutex); @@ -281,36 +318,153 @@ namespace Void::Logging void Logger::submit(Entry entry) { - bool write_now = false; + if (entry.level < m_level.load(std::memory_order_relaxed)) { + return; + } + + switch (m_mode.load(std::memory_order_acquire)) { + case Mode::Async: + async_submit(std::move(entry)); + return; + + case Mode::Immediate: + // Virtual call outside any lock (see class documentation). + write(entry); + return; + + case Mode::Buffered: { + std::vector batch; + { + std::lock_guard lock(m_mutex); + m_buffer.push_back(std::move(entry)); + if (m_buffer.size() >= m_buffer_capacity) { + batch = std::move(m_buffer); + m_buffer = {}; + m_buffer.reserve(m_buffer_capacity); + } + } + if (!batch.empty()) { + on_flush(batch); + } + return; + } + } + } + + // ============================================================================= + // Private — async machinery + // ============================================================================= + + void Logger::async_submit(Entry entry) + { + start_worker(); + + switch (m_policy) { + case OverflowPolicy::Block: + // Wait for queue space; the worker releases one slot per + // popped entry. Nothing is ever dropped. + m_space.acquire(); + break; + + case OverflowPolicy::DropNewest: + if (!m_space.try_acquire()) { + return; // full — discard the incoming entry + } + break; + + case OverflowPolicy::DropOldest: + // Unbounded enqueue; the worker trims the oldest entries + // down to capacity when it falls behind. + break; + } + + m_submitted.fetch_add(1, std::memory_order_release); + m_queue.push(std::move(entry)); + wake_worker(); + } + + void Logger::start_worker() + { + if (m_worker_started.load(std::memory_order_acquire)) { + return; + } + std::call_once(m_worker_once, [this] { + m_worker = std::thread([this] { worker_loop(); }); + m_worker_started.store(true, std::memory_order_release); + }); + } + + void Logger::wake_worker() noexcept + { + if (m_sleeping.exchange(false, std::memory_order_acq_rel)) { + m_wakeup.release(); + } + } + + void Logger::worker_loop() + { std::vector batch; + const bool counts_space = m_policy != OverflowPolicy::DropOldest; - { - std::lock_guard lock(m_mutex); + for (;;) { + // Drain everything currently queued. + while (auto e = m_queue.try_pop()) { + batch.push_back(std::move(*e)); + if (counts_space) { + m_space.release(); + } + } - // Re-check level under the lock; set_level() may have raced. - if (entry.level < m_level) { + if (!batch.empty()) { + const bool stopping = m_stop.load(std::memory_order_acquire); + + std::size_t dropped = 0; + if (m_policy == OverflowPolicy::DropOldest && + batch.size() > m_async_capacity) { + dropped = batch.size() - m_async_capacity; + batch.erase(batch.begin(), + batch.begin() + + static_cast(dropped)); + } + + // After stop the derived class may already be destroyed — + // never touch the virtuals; just account and discard. + if (!stopping) { + on_flush(batch); + } + m_completed.fetch_add(batch.size() + dropped, + std::memory_order_release); + m_completed.notify_all(); + batch.clear(); + continue; // re-poll before considering a park + } + + if (m_stop.load(std::memory_order_acquire)) { return; } - if (m_mode == Mode::Immediate) { - write_now = true; - // entry intentionally NOT moved — used below outside the lock. - } else { - m_buffer.push_back(std::move(entry)); - - if (m_buffer.size() >= m_buffer_capacity) { - batch = std::move(m_buffer); - m_buffer = {}; - m_buffer.reserve(m_buffer_capacity); - } + // Park. Producers re-check m_sleeping after pushing, so a wake + // between the store and acquire below cannot be missed. + m_sleeping.store(true, std::memory_order_release); + if (!m_queue.empty() || m_stop.load(std::memory_order_acquire)) { + m_sleeping.store(false, std::memory_order_release); + continue; } - } // ← mutex released here + m_wakeup.acquire(); + m_sleeping.store(false, std::memory_order_release); + } + } - // Virtual calls happen outside the lock (see class documentation). - if (write_now) { - write(entry); // entry was not moved in this branch - } else if (!batch.empty()) { - on_flush(batch); + void Logger::drain_async() + { + const auto target = m_submitted.load(std::memory_order_acquire); + for (;;) { + const auto done = m_completed.load(std::memory_order_acquire); + if (done >= target) { + return; + } + wake_worker(); + m_completed.wait(done, std::memory_order_acquire); } } diff --git a/src/Log/RotatingFileLogger.cpp b/src/Log/RotatingFileLogger.cpp new file mode 100644 index 0000000..9d835cf --- /dev/null +++ b/src/Log/RotatingFileLogger.cpp @@ -0,0 +1,109 @@ +#include +#include + +#include +#include +#include + +namespace Void::Logging +{ + + RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path, + Options options) + : Logger(options.mode, options.capacity, options.policy), m_path(path), + m_options(options) + { + std::error_code ec; + if (std::filesystem::exists(m_path, ec)) { + m_current_bytes = static_cast( + std::filesystem::file_size(m_path, ec)); + } + m_file.open(m_path, std::ios::app); + if (!m_file.is_open()) { + throw std::runtime_error(std::format( + "RotatingFileLogger: cannot open '{}'", m_path.string())); + } + Void::Log::debug("Log.RotatingFile", "opened '{}' ({} bytes)", + m_path.string(), m_current_bytes); + } + + Void::Result::Result, + Void::Result::Error> + RotatingFileLogger::open(const std::filesystem::path& path, + Options options) + { + try { + return Void::Result::ok( + std::make_unique(path, options)); + } catch (const std::exception& e) { + return Void::Result::fail(std::string{e.what()}); + } + } + + RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); } + + void RotatingFileLogger::write(const Entry& entry) + { + append(entry); + m_file.flush(); + rotate_if_needed(); + } + + void RotatingFileLogger::on_flush(std::span entries) + { + for (const auto& entry : entries) { + append(entry); + } + m_file.flush(); + rotate_if_needed(); + } + + void RotatingFileLogger::append(const Entry& entry) + { + std::string line; + if (m_formatter) { + line = m_formatter->format(entry); + } else { + line = + std::format("[{}] {}", to_string(entry.level), entry.message); + } + line += '\n'; + m_file << line; + m_current_bytes += line.size(); + } + + void RotatingFileLogger::rotate_if_needed() + { + if (m_current_bytes < m_options.max_bytes) { + return; + } + + m_file.close(); + std::error_code ec; + + // Shift app.log.(N-1) -> app.log.N, ..., app.log -> app.log.1; + // the oldest file falls off the end. + const auto numbered = [&](std::size_t n) { + auto p = m_path; + p += std::format(".{}", n); + return p; + }; + std::filesystem::remove(numbered(m_options.max_files), ec); + for (std::size_t n = m_options.max_files; n > 1; --n) { + const auto from = numbered(n - 1); + if (std::filesystem::exists(from, ec)) { + std::filesystem::rename(from, numbered(n), ec); + } + } + if (m_options.max_files > 0) { + std::filesystem::rename(m_path, numbered(1), ec); + } else { + std::filesystem::remove(m_path, ec); + } + + m_file.open(m_path, std::ios::trunc); + m_current_bytes = 0; + Void::Log::debug("Log.RotatingFile", "rotated '{}'", m_path.string()); + } + +} // namespace Void::Logging diff --git a/src/Log/SyslogLogger.cpp b/src/Log/SyslogLogger.cpp new file mode 100644 index 0000000..bfcb588 --- /dev/null +++ b/src/Log/SyslogLogger.cpp @@ -0,0 +1,55 @@ +#include + +#ifdef VOID_HAS_SYSLOG + +#include + +#include + +namespace Void::Logging +{ + + namespace + { + int priority_for(Level level) noexcept + { + switch (level) { + case Level::Trace: + case Level::Debug: + return LOG_DEBUG; + case Level::Info: + return LOG_INFO; + case Level::Warning: + return LOG_WARNING; + case Level::Error: + return LOG_ERR; + case Level::Fatal: + return LOG_CRIT; + case Level::Disabled: + break; + } + return LOG_INFO; + } + } // namespace + + SyslogLogger::SyslogLogger(std::string identity, Mode mode, + std::size_t capacity) + : Logger(mode, capacity), m_identity(std::move(identity)) + { + ::openlog(m_identity.c_str(), LOG_PID, LOG_USER); + } + + SyslogLogger::~SyslogLogger() noexcept + { + flush(); + ::closelog(); + } + + void SyslogLogger::write(const Entry& entry) + { + ::syslog(priority_for(entry.level), "%s", entry.message.c_str()); + } + +} // namespace Void::Logging + +#endif // VOID_HAS_SYSLOG diff --git a/src/Log/module.cmake b/src/Log/module.cmake index 461252b..4c346cd 100644 --- a/src/Log/module.cmake +++ b/src/Log/module.cmake @@ -1,4 +1,4 @@ void_add_module(Log - INTERNAL_DEPS Functional + INTERNAL_DEPS Functional Configuration OPTIONAL_DEPS Stacktrace ) diff --git a/src/Plugin/Loader.cpp b/src/Plugin/Loader.cpp index 0dff2b9..01eca53 100644 --- a/src/Plugin/Loader.cpp +++ b/src/Plugin/Loader.cpp @@ -1,3 +1,4 @@ +#include #include #if defined(__unix__) || defined(__APPLE__) @@ -95,10 +96,15 @@ PluginLoader::load(std::filesystem::path path) PluginLoader ldr; ldr.path_ = path; - if (auto r = ldr.load_from(path); !r) + if (auto r = ldr.load_from(path); !r) { + Void::Log::warn("Plugin", "load '{}' failed: {}", path.string(), + to_string(r.error())); return std::unexpected{r.error()}; + } ldr.plugin_->on_load(); + Void::Log::info("Plugin", "loaded '{}' ({} v{})", path.string(), + ldr.info_.name, ldr.info_.plugin_version); return ldr; } @@ -148,6 +154,8 @@ std::expected PluginLoader::reload() if (auto r = next.load_from(tmp); !r) { std::error_code ec; std::filesystem::remove(tmp, ec); + Void::Log::warn("Plugin", "reload '{}' failed: {}; keeping old", + path_.string(), to_string(r.error())); return r; } @@ -160,6 +168,8 @@ std::expected PluginLoader::reload() *this = std::move(next); plugin_->on_load(); + Void::Log::info("Plugin", "reloaded '{}' ({} v{})", path_.string(), + info_.name, info_.plugin_version); std::error_code ec; std::filesystem::remove(tmp, ec); diff --git a/src/Stacktrace/Stacktrace.cpp b/src/Stacktrace/Stacktrace.cpp index ed197e8..12eda59 100644 --- a/src/Stacktrace/Stacktrace.cpp +++ b/src/Stacktrace/Stacktrace.cpp @@ -38,8 +38,7 @@ namespace Void::Stacktrace } } catch (...) { } - Void::Log::log(Void::Log::Level::Debug, "Stacktrace", - std::format("captured {} frames", result.size())); + Void::Log::debug("Stacktrace", "captured {} frames", result.size()); return result; } @@ -49,9 +48,7 @@ namespace Void::Stacktrace { std::ifstream ifs{file}; if (!ifs.is_open()) { - Void::Log::log( - Void::Log::Level::Warning, "Stacktrace", - std::format("read_source_snippet: cannot open '{}'", file)); + Void::Log::warn("Stacktrace", "read_source_snippet: cannot open '{}'", file); return Void::Result::fail( std::format("read_source_snippet: cannot open '{}'", file)); } diff --git a/src/System/FileWatcher.cpp b/src/System/FileWatcher.cpp new file mode 100644 index 0000000..9e4fbcc --- /dev/null +++ b/src/System/FileWatcher.cpp @@ -0,0 +1,130 @@ +#include +#include + +#include +#include +#include + +namespace Void::FileSystem +{ + + FileWatcher::FileWatcher(Options options) : m_options(options) + { + m_thread = std::thread([this] { run(); }); + } + + FileWatcher::~FileWatcher() + { + { + std::lock_guard lock(m_mutex); + m_stop = true; + } + m_cv.notify_all(); + if (m_thread.joinable()) { + m_thread.join(); + } + } + + void FileWatcher::watch(std::filesystem::path path, Callback callback) + { + Entry entry; + entry.callback = std::move(callback); + entry.accepted = stat(path); + + std::lock_guard lock(m_mutex); + Void::Log::debug("System.FileWatcher", "watching '{}'", path.string()); + m_watches.insert_or_assign(std::move(path), std::move(entry)); + } + + void FileWatcher::unwatch(const std::filesystem::path& path) + { + std::lock_guard lock(m_mutex); + m_watches.erase(path); + } + + std::size_t FileWatcher::watch_count() const + { + std::lock_guard lock(m_mutex); + return m_watches.size(); + } + + void FileWatcher::poll_now() { poll_round(); } + + FileWatcher::Signature FileWatcher::stat(const std::filesystem::path& path) + { + Signature sig; + std::error_code ec; + sig.exists = std::filesystem::exists(path, ec) && !ec; + if (sig.exists) { + sig.mtime = std::filesystem::last_write_time(path, ec); + sig.size = std::filesystem::file_size(path, ec); + if (ec) { + sig = Signature{}; // treat stat failure as absent + } + } + return sig; + } + + void FileWatcher::poll_round() + { + // Collect ripe callbacks under the lock, invoke them outside it so + // a callback may call watch()/unwatch() without deadlocking. + std::vector> ripe; + + { + std::lock_guard lock(m_mutex); + for (auto& [path, entry] : m_watches) { + const Signature now = stat(path); + + if (!entry.dirty) { + if (now != entry.accepted) { + entry.dirty = true; + entry.pending = now; + entry.stable_polls = 1; + } + continue; + } + + if (now != entry.pending) { + // Still changing — restart the stability count. + entry.pending = now; + entry.stable_polls = 1; + continue; + } + + if (++entry.stable_polls >= m_options.debounce_polls) { + entry.accepted = now; + entry.dirty = false; + entry.stable_polls = 0; + ripe.emplace_back(entry.callback, Event{path, now.exists}); + } + } + } + + for (auto& [callback, event] : ripe) { + Void::Log::debug("System.FileWatcher", "change on '{}'", + event.path.string()); + if (callback) { + callback(event); + } + } + } + + void FileWatcher::run() + { + // Wait first, poll after: nothing is watched at startup, and an + // eager first round would race callers that add watches right + // after construction. + std::unique_lock lock(m_mutex); + while (!m_stop) { + if (m_cv.wait_for(lock, m_options.poll_interval, + [this] { return m_stop; })) { + return; + } + lock.unlock(); + poll_round(); + lock.lock(); + } + } + +} // namespace Void::FileSystem diff --git a/src/System/Process.cpp b/src/System/Process.cpp index 9636955..b19b303 100644 --- a/src/System/Process.cpp +++ b/src/System/Process.cpp @@ -104,8 +104,7 @@ Void::Result::Result std::strerror(errno))); } - Void::Log::log(Void::Log::Level::Debug, "Process", - std::format("run: '{}'", executable.string())); + Void::Log::debug("Process", "run: '{}'", executable.string()); std::vector argv; argv.push_back(executable.c_str()); @@ -234,10 +233,8 @@ Void::Result::Result ::waitpid(pid, &status, 0); output.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : -1; - Void::Log::log( - Void::Log::Level::Debug, "Process", - std::format("run: '{}' exited {}", executable.string(), - output.exit_code)); + Void::Log::debug("Process", "run: '{}' exited {}", executable.string(), + output.exit_code); return Void::Result::ok(std::move(output)); } diff --git a/tests/internal/CrossModule.cpp b/tests/internal/CrossModule.cpp index 446977a..5ef5f67 100644 --- a/tests/internal/CrossModule.cpp +++ b/tests/internal/CrossModule.cpp @@ -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") != diff --git a/tests/standalone/Configuration/Bind.cpp b/tests/standalone/Configuration/Bind.cpp new file mode 100644 index 0000000..721cf12 --- /dev/null +++ b/tests/standalone/Configuration/Bind.cpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include + +#include +#include +#include +#include + +#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 sample_rate; + std::vector 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(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(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(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(cfg); + Void::Testing::expect(s.has_value()); + Void::Testing::expect_eq(s->path, std::string{"root.log"}); +} + +#endif // VOID_HAS_CONFIG_REFLECTION diff --git a/tests/standalone/Configuration/Sources.cpp b/tests/standalone/Configuration/Sources.cpp new file mode 100644 index 0000000..85f06d0 --- /dev/null +++ b/tests/standalone/Configuration/Sources.cpp @@ -0,0 +1,112 @@ +#include +#include +#include + +#include +#include + +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("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("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("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"); +} diff --git a/tests/standalone/Configuration/Typed.cpp b/tests/standalone/Configuration/Typed.cpp new file mode 100644 index 0000000..d618883 --- /dev/null +++ b/tests/standalone/Configuration/Typed.cpp @@ -0,0 +1,104 @@ +#include +#include +#include + +#include +#include + +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("port"), 8080); + Void::Testing::expect_eq(*cfg.get_as("ratio"), 0.25); + Void::Testing::expect_eq(*cfg.get_as("negative"), -42L); +} + +Void::Testing::Test typed_bool_spellings() +{ + const auto cfg = sample(); + Void::Testing::expect(*cfg.get_as("verbose")); + Void::Testing::expect(!*cfg.get_as("quiet")); +} + +Void::Testing::Test typed_enum_by_name() +{ + const auto cfg = sample(); + const auto color = cfg.get_as("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("timeout") == + milliseconds{250}); + Void::Testing::expect(*cfg.get_as("interval") == + seconds{120}); +} + +Void::Testing::Test typed_errors_are_reported() +{ + const auto cfg = sample(); + Void::Testing::expect(!cfg.get_as("junk").has_value()); + Void::Testing::expect(!cfg.get_as("missing").has_value()); + Void::Testing::expect(!cfg.get_as("port").has_value()); + Void::Testing::expect(!cfg.get_as("verbose").has_value()); +} + +Void::Testing::Test typed_get_or_as_fallback() +{ + const auto cfg = sample(); + Void::Testing::expect_eq(cfg.get_or_as("port", 1), 8080); + Void::Testing::expect_eq(cfg.get_or_as("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"}); +} diff --git a/tests/standalone/Configuration/Watch.cpp b/tests/standalone/Configuration/Watch.cpp new file mode 100644 index 0000000..3ef23d1 --- /dev/null +++ b/tests/standalone/Configuration/Watch.cpp @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +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 last_changed; + std::string last_level; + + auto watch = ConfigWatch::ini( + file, + [&](const Config& cfg, const std::vector& 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 reloads{0}; + auto watch = ConfigWatch::ini( + file, + [&](const Config&, const std::vector&) { + ++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 reloads{0}; + auto watch = ConfigWatch::ini( + file, + [&](const Config&, const std::vector&) { + ++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"); +} diff --git a/tests/standalone/Log/AsyncLogger.cpp b/tests/standalone/Log/AsyncLogger.cpp new file mode 100644 index 0000000..26cbe36 --- /dev/null +++ b/tests/standalone/Log/AsyncLogger.cpp @@ -0,0 +1,198 @@ +#include +#include +#include +#include + +#include +#include +#include +#include + +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 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 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 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 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 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 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 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 release{false}; + std::atomic 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 delivered{0}; + { + CallbackLogger log{[&](const Entry&) { ++delivered; }, Mode::Async, + 1024, OverflowPolicy::Block}; + log.set_level(Level::Trace); + + std::vector 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(producers) * per_producer); +} diff --git a/tests/standalone/Log/Formatter.cpp b/tests/standalone/Log/Formatter.cpp new file mode 100644 index 0000000..9a642ca --- /dev/null +++ b/tests/standalone/Log/Formatter.cpp @@ -0,0 +1,100 @@ +#include +#include +#include +#include + +#include + +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); +} diff --git a/tests/standalone/Log/FromConfig.cpp b/tests/standalone/Log/FromConfig.cpp new file mode 100644 index 0000000..249e203 --- /dev/null +++ b/tests/standalone/Log/FromConfig.cpp @@ -0,0 +1,105 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +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(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({}); +} diff --git a/tests/standalone/Log/Log.cpp b/tests/standalone/Log/Log.cpp index ef3d1b1..411a972 100644 --- a/tests/standalone/Log/Log.cpp +++ b/tests/standalone/Log/Log.cpp @@ -7,9 +7,15 @@ #include #include -// 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 : std::formatter { + template + auto format(const FormatProbe& p, Ctx& ctx) const + { + ++*p.format_count; + return std::formatter::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")); +} diff --git a/tests/standalone/Log/Sinks.cpp b/tests/standalone/Log/Sinks.cpp new file mode 100644 index 0000000..7ca83a6 --- /dev/null +++ b/tests/standalone/Log/Sinks.cpp @@ -0,0 +1,183 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +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( + [&](const Entry&) { ++a; }, Mode::Immediate)); + multi.add(std::make_shared( + [&](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( + [&](const Entry&) { ++verbose_count; }, Mode::Immediate); + auto strict = std::make_shared( + [&](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( + [&](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("{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(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)); + } +}; diff --git a/tests/standalone/System/FileWatcher.cpp b/tests/standalone/System/FileWatcher.cpp new file mode 100644 index 0000000..b9f604e --- /dev/null +++ b/tests/standalone/System/FileWatcher.cpp @@ -0,0 +1,136 @@ +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +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 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 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 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 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 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); +}