Overhaul Logging and Configuration; integrate the log facade library-wide
Void::Log facade (header-only, macro-free):
- Leveled function templates trace/debug/info/warn/error/fatal(module,
fmt, args...) with lazy formatting - a disabled call is one relaxed
atomic load, no allocation, no formatting.
- Global min level + per-module overrides (can raise or lower); empty
sink/Disabled level = logging fully off; set_sink remains the splice
point for external logging libraries.
Void::Logging::Logger - async by default, one class for both modes:
- Mode::Async (default): lock-free MPSC queue + logger-owned worker
delivering batches via on_flush outside any lock; Immediate/Buffered
give synchronous behavior via constructor arg or set_mode at runtime.
- Bounded queue with OverflowPolicy{Block, DropNewest, DropOldest};
flush() (now virtual) blocks until everything submitted is delivered;
base destructor only stops/joins the worker, never touches virtuals.
- Fixed a wakeup race: stale park token + fresh release overflowed the
binary semaphore; wakeup is a counting semaphore (spurious wakes are
absorbed by the worker loop).
New sinks and formatters:
- RotatingFileLogger (size-based rotation, max-files cap), NullLogger,
CallbackLogger, MultiLogger (tee via new Logger::relay), SyslogLogger.
- Formatter interface: PatternFormatter ({time}/{level}/{scopes}/...),
JsonLinesFormatter, LogfmtFormatter; installable on Console/File/
Rotating sinks. Console/File sinks now default to Async.
- Logging::from_config builds the whole sink tree from Config keys;
apply_facade_config drives facade levels.
Configuration:
- Typed get_as<T>/get_or_as<T> (numbers, bool spellings, enums by name,
chrono durations), dotted keys, subtree(), sorted keys().
- New sources: from_env_prefix (APP_LOG__LEVEL -> log.level), from_ini
(sections as prefixes), from_json (objects/arrays flattened),
from_args (--key=value / --key value / --flag).
- Bind.hpp: reflection bind<T>(cfg, prefix) fills aggregates; defaults
in the struct are the schema; nested aggregates, optional, vector.
- Watch.hpp: ConfigWatch reloads on change with per-key diff; parse
failures keep the previous config.
System: new FileSystem::FileWatcher - debounced polling watcher (stable
mtime+size across N polls), callbacks off-thread, deletion events;
shared groundwork for plugin hot-reload.
Sweep: all internal Void::Log::log call sites migrated to the leveled
API ("Umbrella.Feature" labels); Plugin loader now logs load/reload.
918 tests green (28 new), stable across 30 consecutive runs, ASan+UBSan
clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8a6065539a
commit
c74a02a5a5
43 files changed
+3889
-236
No files matched your search
@@ -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(<target>)`.
|
||||
|
||||
### 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<const Entry>)`** — 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<const Entry>)`** — 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<T>` / `get_or_as<T>` (numbers, bool spellings, enums by name via reflection, chrono durations like "250ms"). `subtree(prefix)` strips a prefix. `Bind.hpp`: `bind<T>(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
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <format>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
#if __has_include(<meta>)
|
||||
#include <meta>
|
||||
#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<LogSettings>(cfg, "log");
|
||||
//
|
||||
// Supported member types: everything Config::get_as<T> accepts (string,
|
||||
// bool, arithmetic, enums, chrono durations), std::optional<leaf>,
|
||||
// std::vector<leaf> (keys "name.0", "name.1", ...), nested aggregates.
|
||||
|
||||
namespace Void::Configuration
|
||||
{
|
||||
|
||||
#ifdef VOID_HAS_CONFIG_REFLECTION
|
||||
|
||||
namespace BindDetail
|
||||
{
|
||||
template <typename T> struct IsOptional : std::false_type {
|
||||
};
|
||||
template <typename U>
|
||||
struct IsOptional<std::optional<U>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T> struct IsVector : std::false_type {
|
||||
};
|
||||
template <typename U> struct IsVector<std::vector<U>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T> struct IsDuration : std::false_type {
|
||||
};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>> : std::true_type {
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
concept Leaf = std::is_same_v<T, std::string> ||
|
||||
std::is_same_v<T, bool> || std::is_arithmetic_v<T> ||
|
||||
std::is_enum_v<T> || IsDuration<T>::value;
|
||||
|
||||
template <typename T>
|
||||
concept BindableAggregate =
|
||||
std::is_aggregate_v<T> && !std::is_array_v<T> &&
|
||||
std::is_default_constructible_v<T>;
|
||||
|
||||
[[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 <BindableAggregate T>
|
||||
Void::Result::Result<T, Void::Result::Error>
|
||||
bind_into(const Config& cfg, std::string_view prefix)
|
||||
{
|
||||
T out{};
|
||||
std::optional<Void::Result::Error> 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<MT> && !Leaf<MT>) {
|
||||
auto nested = bind_into<MT>(cfg, key);
|
||||
if (!nested.has_value()) {
|
||||
failure = std::move(nested).error();
|
||||
} else {
|
||||
out.[:m:] = std::move(*nested);
|
||||
}
|
||||
} else if constexpr (IsOptional<MT>::value) {
|
||||
using U = typename MT::value_type;
|
||||
if (cfg.contains(key)) {
|
||||
auto v = cfg.get_as<U>(key);
|
||||
if (!v.has_value()) {
|
||||
failure = std::move(v).error();
|
||||
} else {
|
||||
out.[:m:] = std::move(*v);
|
||||
}
|
||||
}
|
||||
} else if constexpr (IsVector<MT>::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<U>(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<MT>,
|
||||
"member type not bindable from Config");
|
||||
if (cfg.contains(key)) {
|
||||
auto v = cfg.get_as<MT>(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 <BindDetail::BindableAggregate T>
|
||||
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
|
||||
bind(const Config& cfg, std::string_view prefix = {})
|
||||
{
|
||||
return BindDetail::bind_into<T>(cfg, prefix);
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_CONFIG_REFLECTION
|
||||
|
||||
} // namespace Void::Configuration
|
||||
@@ -1,30 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Env.hpp>
|
||||
#include <Void/Data/Ini.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Detail/Enum.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cctype>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <initializer_list>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
#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<T>(). 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<int>("net.retries"); // Result<int>
|
||||
///
|
||||
/// 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<char>(std::tolower(
|
||||
static_cast<unsigned char>(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<Config, Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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<Config, Void::Result::Error>
|
||||
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 <typename T>
|
||||
[[nodiscard]] Void::Result::Result<T, Void::Result::Error>
|
||||
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<T>(key, it->second);
|
||||
}
|
||||
|
||||
/// Typed lookup with fallback for missing keys. Conversion errors
|
||||
/// on a *present* key still surface the fallback but are logged.
|
||||
template <typename T>
|
||||
[[nodiscard]] T get_or_as(std::string_view key, T fallback) const
|
||||
{
|
||||
auto r = get_as<T>(key);
|
||||
if (r.has_value()) {
|
||||
return std::move(*r);
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
// Key enumeration / subtrees
|
||||
// ═════════════════════════════════════════════════════════════════
|
||||
|
||||
/// All keys, sorted.
|
||||
[[nodiscard]] std::vector<std::string> keys() const
|
||||
{
|
||||
std::vector<std::string> 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<double>(static_cast<long long>(d))) {
|
||||
cfg.values_.insert_or_assign(
|
||||
prefix,
|
||||
std::to_string(static_cast<long long>(d)));
|
||||
}
|
||||
else {
|
||||
cfg.values_.insert_or_assign(prefix,
|
||||
std::format("{}", d));
|
||||
}
|
||||
}
|
||||
// null: key omitted
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct IsDuration : std::false_type {};
|
||||
template <typename Rep, typename Period>
|
||||
struct IsDuration<std::chrono::duration<Rep, Period>>
|
||||
: std::true_type {};
|
||||
|
||||
template <typename T>
|
||||
static Void::Result::Result<T, Void::Result::Error>
|
||||
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<T, std::string>) {
|
||||
return Void::Result::ok(raw);
|
||||
}
|
||||
else if constexpr (std::is_same_v<T, bool>) {
|
||||
std::string lower;
|
||||
lower.reserve(raw.size());
|
||||
for (const char c : raw) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<T>) {
|
||||
#ifdef VOID_HAS_ENUM_REFLECTION
|
||||
if (auto e = Void::Detail::enum_parse<T>(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<T>::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<T>(*parsed));
|
||||
}
|
||||
else if constexpr (std::is_arithmetic_v<T>) {
|
||||
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<T, std::string>,
|
||||
"unsupported get_as<T> type");
|
||||
}
|
||||
}
|
||||
|
||||
static std::optional<std::chrono::nanoseconds>
|
||||
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<nanoseconds>(
|
||||
duration<double, typename decltype(unit)::period>{
|
||||
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<std::string, std::string> values_;
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<Void::Result::Result<Config, Void::Result::Error>(
|
||||
const std::filesystem::path&)>;
|
||||
using OnReload = std::function<void(
|
||||
const Config&, const std::vector<std::string>& 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<std::string> 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<std::string>
|
||||
diff(const Config& before, const Config& after)
|
||||
{
|
||||
std::vector<std::string> 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
|
||||
@@ -1,29 +1,33 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#include <iosfwd>
|
||||
#include <memory>
|
||||
|
||||
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<const Formatter> 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<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -1,8 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Log/Logger.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
@@ -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<std::unique_ptr<FileLogger>, 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<const Formatter> 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<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <vector>
|
||||
|
||||
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<Segment> 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<std::string>& scopes);
|
||||
} // namespace FormatDetail
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,45 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#include <memory>
|
||||
#include <string_view>
|
||||
|
||||
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<std::shared_ptr<Logger>,
|
||||
Void::Result::Error>
|
||||
from_config(const Configuration::Config& cfg,
|
||||
std::string_view prefix = "log");
|
||||
|
||||
/// Apply `<prefix>.level` and `<prefix>.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
|
||||
+160
-21
@@ -1,10 +1,32 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
|
||||
// ── 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<void(
|
||||
Level level, std::string_view module, std::string_view message)>;
|
||||
/// module — short library-internal label (e.g. "System.Process")
|
||||
/// message — human-readable description
|
||||
using Sink = std::function<void(Level level, std::string_view module,
|
||||
std::string_view message)>;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
struct SinkState {
|
||||
Sink sink;
|
||||
std::shared_mutex mutex;
|
||||
struct State {
|
||||
// Fast-path gates (checked before any locking or formatting).
|
||||
std::atomic<bool> has_sink{false};
|
||||
std::atomic<Level> min_level{Level::Trace};
|
||||
std::atomic<bool> has_module_levels{false};
|
||||
|
||||
// Slow path.
|
||||
Sink sink;
|
||||
std::unordered_map<std::string, Level> 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<bool>(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 <typename... Args>
|
||||
void log(Level level, std::string_view module,
|
||||
std::format_string<Args...> fmt, Args&&... args)
|
||||
{
|
||||
if (!enabled(level, module)) {
|
||||
return;
|
||||
}
|
||||
log(level, module, std::format(fmt, std::forward<Args>(args)...));
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void trace(std::string_view module, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Trace, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void debug(std::string_view module, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Debug, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void info(std::string_view module, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Info, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void warn(std::string_view module, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Warning, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void error(std::string_view module, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Error, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void fatal(std::string_view module, std::format_string<Args...> fmt,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Fatal, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
} // namespace Void::Log
|
||||
+110
-27
@@ -1,42 +1,68 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <semaphore>
|
||||
#include <source_location>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
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<Level> m_level{Level::Trace};
|
||||
std::atomic<Mode> m_mode;
|
||||
std::size_t m_async_capacity;
|
||||
OverflowPolicy m_policy;
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::vector<Entry> m_buffer;
|
||||
std::vector<Entry> m_buffer; // Buffered mode only
|
||||
std::size_t m_buffer_capacity;
|
||||
|
||||
// ── Async machinery ──────────────────────────────────────────
|
||||
Void::Async::MpscQueue<Entry> 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<bool> m_sleeping{false};
|
||||
std::atomic<bool> m_stop{false};
|
||||
std::atomic<bool> m_worker_started{false};
|
||||
std::once_flag m_worker_once;
|
||||
std::thread m_worker;
|
||||
std::atomic<std::uint64_t> m_submitted{0};
|
||||
std::atomic<std::uint64_t> m_completed{0};
|
||||
|
||||
/// Per-thread scope stack. ScopedContext pushes/pops into this.
|
||||
static thread_local std::vector<std::string> s_scope_stack;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
|
||||
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<std::unique_ptr<RotatingFileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path, Options options = {});
|
||||
|
||||
/// Install a formatter. Call before logging starts.
|
||||
void set_formatter(std::shared_ptr<const Formatter> 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<const Entry> 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<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,114 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <span>
|
||||
#include <vector>
|
||||
|
||||
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<void(const Entry&)>;
|
||||
|
||||
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<std::shared_ptr<Logger>> 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<Logger> 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<std::shared_ptr<Logger>> m_children;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
|
||||
#if __has_include(<syslog.h>)
|
||||
#define VOID_HAS_SYSLOG 1
|
||||
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
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(<syslog.h>)
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
|
||||
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<void(const Event&)>;
|
||||
|
||||
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<std::filesystem::path, Entry> m_watches;
|
||||
bool m_stop = false;
|
||||
std::thread m_thread;
|
||||
};
|
||||
|
||||
} // namespace Void::FileSystem
|
||||
@@ -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<char>(f),
|
||||
std::istreambuf_iterator<char>()};
|
||||
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<std::streamsize>(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()));
|
||||
|
||||
@@ -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 {};
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
void_add_module(Configuration
|
||||
INTERNAL_DEPS Functional System
|
||||
INTERNAL_DEPS Functional System Data
|
||||
)
|
||||
@@ -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();
|
||||
}
|
||||
|
||||
|
||||
+17
-11
@@ -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<std::unique_ptr<FileLogger>, 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<const Entry> 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
|
||||
@@ -0,0 +1,250 @@
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace FormatDetail
|
||||
{
|
||||
|
||||
std::string iso8601(std::chrono::system_clock::time_point tp)
|
||||
{
|
||||
const auto ms = std::chrono::floor<std::chrono::milliseconds>(tp);
|
||||
return std::format("{:%FT%H:%M:%S}Z", ms);
|
||||
}
|
||||
|
||||
std::string scope_breadcrumb(const std::vector<std::string>& 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<double>(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
|
||||
@@ -0,0 +1,259 @@
|
||||
#include <Void/Log/FromConfig.hpp>
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/FileLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/SyslogLogger.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
std::vector<std::string> split_list(std::string_view csv)
|
||||
{
|
||||
std::vector<std::string> 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<Level> parse_level(std::string_view name)
|
||||
{
|
||||
std::string lower;
|
||||
for (const char c : name) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<Void::Log::Level>
|
||||
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<const Formatter>
|
||||
make_formatter(const Configuration::Config& cfg)
|
||||
{
|
||||
const auto format = cfg.get_or("format", "default");
|
||||
if (format == "pattern") {
|
||||
return std::make_shared<PatternFormatter>(
|
||||
std::string{cfg.get_or(
|
||||
"pattern", "{time} [{level}] {scopes}{message}")});
|
||||
}
|
||||
if (format == "json") {
|
||||
return std::make_shared<JsonLinesFormatter>();
|
||||
}
|
||||
if (format == "logfmt") {
|
||||
return std::make_shared<LogfmtFormatter>();
|
||||
}
|
||||
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<bool>("async", true)) {
|
||||
d.mode = Mode::Immediate;
|
||||
}
|
||||
d.capacity = cfg.get_or_as<std::size_t>("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<std::shared_ptr<Logger>, 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<std::shared_ptr<Logger>> 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<ConsoleLogger>(
|
||||
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<Logger>{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<std::size_t>("rotating.max_kb", 1024) * 1024;
|
||||
opt.max_files =
|
||||
sub.get_or_as<std::size_t>("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<Logger>{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<SyslogLogger>(
|
||||
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<Logger> root;
|
||||
if (sinks.empty()) {
|
||||
root = std::make_shared<NullLogger>();
|
||||
} else if (sinks.size() == 1) {
|
||||
root = std::move(sinks.front());
|
||||
} else {
|
||||
root = std::make_shared<MultiLogger>(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
|
||||
+200
-46
@@ -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<std::ptrdiff_t>(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<Entry> 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<Entry> 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<Entry> 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<Entry> 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<Entry> 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<std::ptrdiff_t>(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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
|
||||
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::size_t>(
|
||||
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<std::unique_ptr<RotatingFileLogger>,
|
||||
Void::Result::Error>
|
||||
RotatingFileLogger::open(const std::filesystem::path& path,
|
||||
Options options)
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(
|
||||
std::make_unique<RotatingFileLogger>(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<const Entry> 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
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <Void/Log/SyslogLogger.hpp>
|
||||
|
||||
#ifdef VOID_HAS_SYSLOG
|
||||
|
||||
#include <syslog.h>
|
||||
|
||||
#include <utility>
|
||||
|
||||
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
|
||||
@@ -1,4 +1,4 @@
|
||||
void_add_module(Log
|
||||
INTERNAL_DEPS Functional
|
||||
INTERNAL_DEPS Functional Configuration
|
||||
OPTIONAL_DEPS Stacktrace
|
||||
)
|
||||
+11
-1
@@ -1,3 +1,4 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Plugin/Loader.hpp>
|
||||
|
||||
#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<void, LoadError> 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<void, LoadError> 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);
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<std::pair<Callback, Event>> 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
|
||||
@@ -104,8 +104,7 @@ Void::Result::Result<Output, Void::Result::Error>
|
||||
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<const char*> argv;
|
||||
argv.push_back(executable.c_str());
|
||||
@@ -234,10 +233,8 @@ Void::Result::Result<Output, Void::Result::Error>
|
||||
::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));
|
||||
}
|
||||
|
||||
@@ -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") !=
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
#include <Void/Configuration/Bind.hpp>
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#ifdef VOID_HAS_CONFIG_REFLECTION
|
||||
|
||||
using Void::Configuration::Config;
|
||||
|
||||
namespace
|
||||
{
|
||||
enum class Sink { Console, File };
|
||||
|
||||
struct FileSettings {
|
||||
std::string path = "default.log";
|
||||
int max_files = 3;
|
||||
};
|
||||
|
||||
struct LogSettings {
|
||||
std::string level = "info";
|
||||
bool async = true;
|
||||
Sink sink = Sink::Console;
|
||||
std::chrono::milliseconds flush_every{250};
|
||||
FileSettings file;
|
||||
std::optional<int> sample_rate;
|
||||
std::vector<std::string> tags;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test bind_fills_present_keys_keeps_defaults()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("log.level", "debug");
|
||||
cfg.set("log.file.path", "/var/log/app.log");
|
||||
cfg.set("log.flush_every", "1s");
|
||||
|
||||
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
|
||||
Void::Testing::expect(s.has_value());
|
||||
Void::Testing::expect_eq(s->level, std::string{"debug"});
|
||||
Void::Testing::expect(s->async); // default kept
|
||||
Void::Testing::expect_eq(s->file.path, std::string{"/var/log/app.log"});
|
||||
Void::Testing::expect_eq(s->file.max_files, 3); // nested default kept
|
||||
Void::Testing::expect(s->flush_every ==
|
||||
std::chrono::milliseconds{1000});
|
||||
}
|
||||
|
||||
Void::Testing::Test bind_enum_optional_vector()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("log.sink", "File");
|
||||
cfg.set("log.sample_rate", "10");
|
||||
cfg.set("log.tags.0", "alpha");
|
||||
cfg.set("log.tags.1", "beta");
|
||||
|
||||
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
|
||||
Void::Testing::expect(s.has_value());
|
||||
Void::Testing::expect(s->sink == Sink::File);
|
||||
Void::Testing::expect(s->sample_rate.has_value());
|
||||
Void::Testing::expect_eq(*s->sample_rate, 10);
|
||||
Void::Testing::expect_eq(s->tags.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(s->tags[1], std::string{"beta"});
|
||||
}
|
||||
|
||||
Void::Testing::Test bind_reports_conversion_errors()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("log.async", "not-a-bool");
|
||||
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
|
||||
Void::Testing::expect(!s.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test bind_empty_prefix_binds_root_keys()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("path", "root.log");
|
||||
const auto s = Void::Configuration::bind<FileSettings>(cfg);
|
||||
Void::Testing::expect(s.has_value());
|
||||
Void::Testing::expect_eq(s->path, std::string{"root.log"});
|
||||
}
|
||||
|
||||
#endif // VOID_HAS_CONFIG_REFLECTION
|
||||
@@ -0,0 +1,112 @@
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <string>
|
||||
|
||||
using Void::Configuration::Config;
|
||||
|
||||
// ── from_env_prefix ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test env_prefix_strips_and_normalizes()
|
||||
{
|
||||
::setenv("VOIDTEST_LOG__LEVEL", "debug", 1);
|
||||
::setenv("VOIDTEST_PORT", "9000", 1);
|
||||
::setenv("UNRELATED_KEY", "x", 1);
|
||||
|
||||
const auto cfg = Config::from_env_prefix("VOIDTEST_");
|
||||
Void::Testing::expect(cfg.get_or("log.level") ==
|
||||
"debug");
|
||||
Void::Testing::expect(cfg.get_or("port") ==
|
||||
"9000");
|
||||
Void::Testing::expect(!cfg.contains("unrelated_key"));
|
||||
|
||||
::unsetenv("VOIDTEST_LOG__LEVEL");
|
||||
::unsetenv("VOIDTEST_PORT");
|
||||
::unsetenv("UNRELATED_KEY");
|
||||
}
|
||||
|
||||
// ── from_ini_text ─────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test ini_sections_become_prefixes()
|
||||
{
|
||||
const auto cfg = Config::from_ini_text(
|
||||
"global_key = 1\n"
|
||||
"[log]\n"
|
||||
"level = warn\n"
|
||||
"[net]\n"
|
||||
"port = 4242\n");
|
||||
Void::Testing::expect(cfg.has_value());
|
||||
Void::Testing::expect(cfg->get_or("global_key") ==
|
||||
"1");
|
||||
Void::Testing::expect(cfg->get_or("log.level") ==
|
||||
"warn");
|
||||
Void::Testing::expect_eq(*cfg->get_as<int>("net.port"), 4242);
|
||||
}
|
||||
|
||||
Void::Testing::Test ini_parse_error_surfaces()
|
||||
{
|
||||
const auto cfg = Config::from_ini_text("[unterminated\nkey=1\n");
|
||||
Void::Testing::expect(!cfg.has_value());
|
||||
}
|
||||
|
||||
// ── from_json_text ────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test json_objects_flatten_to_dotted_keys()
|
||||
{
|
||||
const auto cfg = Config::from_json_text(R"({
|
||||
"log": {"level": "error", "async": true},
|
||||
"servers": [{"host": "a"}, {"host": "b"}],
|
||||
"ratio": 0.5,
|
||||
"count": 3
|
||||
})");
|
||||
Void::Testing::expect(cfg.has_value());
|
||||
Void::Testing::expect(cfg->get_or("log.level") ==
|
||||
"error");
|
||||
Void::Testing::expect(*cfg->get_as<bool>("log.async"));
|
||||
Void::Testing::expect(cfg->get_or("servers.0.host") ==
|
||||
"a");
|
||||
Void::Testing::expect(cfg->get_or("servers.1.host") ==
|
||||
"b");
|
||||
Void::Testing::expect_eq(*cfg->get_as<double>("ratio"), 0.5);
|
||||
Void::Testing::expect(cfg->get_or("count") ==
|
||||
"3"); // integral form
|
||||
}
|
||||
|
||||
Void::Testing::Test json_parse_error_surfaces()
|
||||
{
|
||||
Void::Testing::expect(!Config::from_json_text("{nope").has_value());
|
||||
}
|
||||
|
||||
// ── from_args ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test args_equals_space_and_flag_forms()
|
||||
{
|
||||
const char* argv[] = {"prog", "--log.level=debug",
|
||||
"--net.port", "8080",
|
||||
"--verbose", "positional",
|
||||
"--trailing-flag"};
|
||||
const auto cfg = Config::from_args(7, argv);
|
||||
Void::Testing::expect(cfg.get_or("log.level") ==
|
||||
"debug");
|
||||
Void::Testing::expect(cfg.get_or("net.port") ==
|
||||
"8080");
|
||||
Void::Testing::expect(cfg.get_or("verbose") ==
|
||||
"positional");
|
||||
Void::Testing::expect(cfg.get_or("trailing-flag") ==
|
||||
"true");
|
||||
}
|
||||
|
||||
// ── overlay precedence ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test overlay_last_wins_across_sources()
|
||||
{
|
||||
auto base = Config::from_ini_text("[log]\nlevel = info\n");
|
||||
Void::Testing::expect(base.has_value());
|
||||
|
||||
const char* argv[] = {"prog", "--log.level=trace"};
|
||||
base->overlay(Config::from_args(2, argv));
|
||||
Void::Testing::expect(base->get_or("log.level") ==
|
||||
"trace");
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <string>
|
||||
|
||||
using Void::Configuration::Config;
|
||||
|
||||
namespace
|
||||
{
|
||||
enum class Color { Red, Green, Blue };
|
||||
|
||||
Config sample()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("port", "8080");
|
||||
cfg.set("ratio", "0.25");
|
||||
cfg.set("verbose", "TRUE");
|
||||
cfg.set("quiet", "off");
|
||||
cfg.set("color", "Green");
|
||||
cfg.set("timeout", "250ms");
|
||||
cfg.set("interval", "2m");
|
||||
cfg.set("negative", "-42");
|
||||
cfg.set("junk", "12abc");
|
||||
return cfg;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test typed_int_and_double()
|
||||
{
|
||||
const auto cfg = sample();
|
||||
Void::Testing::expect_eq(*cfg.get_as<int>("port"), 8080);
|
||||
Void::Testing::expect_eq(*cfg.get_as<double>("ratio"), 0.25);
|
||||
Void::Testing::expect_eq(*cfg.get_as<long>("negative"), -42L);
|
||||
}
|
||||
|
||||
Void::Testing::Test typed_bool_spellings()
|
||||
{
|
||||
const auto cfg = sample();
|
||||
Void::Testing::expect(*cfg.get_as<bool>("verbose"));
|
||||
Void::Testing::expect(!*cfg.get_as<bool>("quiet"));
|
||||
}
|
||||
|
||||
Void::Testing::Test typed_enum_by_name()
|
||||
{
|
||||
const auto cfg = sample();
|
||||
const auto color = cfg.get_as<Color>("color");
|
||||
Void::Testing::expect(color.has_value());
|
||||
Void::Testing::expect(*color == Color::Green);
|
||||
}
|
||||
|
||||
Void::Testing::Test typed_durations()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
const auto cfg = sample();
|
||||
Void::Testing::expect(*cfg.get_as<milliseconds>("timeout") ==
|
||||
milliseconds{250});
|
||||
Void::Testing::expect(*cfg.get_as<seconds>("interval") ==
|
||||
seconds{120});
|
||||
}
|
||||
|
||||
Void::Testing::Test typed_errors_are_reported()
|
||||
{
|
||||
const auto cfg = sample();
|
||||
Void::Testing::expect(!cfg.get_as<int>("junk").has_value());
|
||||
Void::Testing::expect(!cfg.get_as<int>("missing").has_value());
|
||||
Void::Testing::expect(!cfg.get_as<bool>("port").has_value());
|
||||
Void::Testing::expect(!cfg.get_as<Color>("verbose").has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test typed_get_or_as_fallback()
|
||||
{
|
||||
const auto cfg = sample();
|
||||
Void::Testing::expect_eq(cfg.get_or_as<int>("port", 1), 8080);
|
||||
Void::Testing::expect_eq(cfg.get_or_as<int>("missing", 7), 7);
|
||||
}
|
||||
|
||||
Void::Testing::Test subtree_strips_prefix()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("log.level", "debug");
|
||||
cfg.set("log.file.path", "/tmp/a.log");
|
||||
cfg.set("net.port", "1");
|
||||
|
||||
const auto log = cfg.subtree("log");
|
||||
Void::Testing::expect_eq(log.size(), std::size_t{2});
|
||||
Void::Testing::expect(log.get_or("level") ==
|
||||
"debug");
|
||||
Void::Testing::expect(log.get_or("file.path") ==
|
||||
"/tmp/a.log");
|
||||
Void::Testing::expect(!log.contains("net.port"));
|
||||
}
|
||||
|
||||
Void::Testing::Test keys_are_sorted()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("b", "2");
|
||||
cfg.set("a", "1");
|
||||
const auto keys = cfg.keys();
|
||||
Void::Testing::expect_eq(keys.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(keys[0], std::string{"a"});
|
||||
Void::Testing::expect_eq(keys[1], std::string{"b"});
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
#include <Void/Configuration/Watch.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using Void::Configuration::Config;
|
||||
using Void::Configuration::ConfigWatch;
|
||||
|
||||
namespace
|
||||
{
|
||||
Void::FileSystem::FileWatcherOptions manual_poll()
|
||||
{
|
||||
return {.poll_interval = std::chrono::milliseconds{60'000},
|
||||
.debounce_polls = 2};
|
||||
}
|
||||
|
||||
int bump = 0;
|
||||
|
||||
void write(const std::filesystem::path& p, std::string_view text)
|
||||
{
|
||||
auto r = Void::FileSystem::write_file(p, text);
|
||||
Void::Testing::expect(r.has_value());
|
||||
const auto now = std::filesystem::file_time_type::clock::now();
|
||||
std::filesystem::last_write_time(
|
||||
p, now + std::chrono::milliseconds{(++bump) * 10});
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test config_watch_reloads_and_diffs()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_cfgwatch"};
|
||||
const auto file = tmp.path() / "app.ini";
|
||||
write(file, "[log]\nlevel = info\nkeep = 1\n");
|
||||
|
||||
std::mutex mu;
|
||||
std::vector<std::string> last_changed;
|
||||
std::string last_level;
|
||||
|
||||
auto watch = ConfigWatch::ini(
|
||||
file,
|
||||
[&](const Config& cfg, const std::vector<std::string>& changed) {
|
||||
std::lock_guard lock(mu);
|
||||
last_changed = changed;
|
||||
last_level = cfg.get_or("log.level");
|
||||
},
|
||||
manual_poll());
|
||||
|
||||
Void::Testing::expect(watch.current().get_or("log.level") ==
|
||||
"info");
|
||||
|
||||
write(file, "[log]\nlevel = debug\nkeep = 1\nadded = x\n");
|
||||
watch.poll_now();
|
||||
watch.poll_now(); // debounce satisfied -> reload + callback
|
||||
|
||||
std::lock_guard lock(mu);
|
||||
Void::Testing::expect_eq(last_level, std::string{"debug"});
|
||||
Void::Testing::expect_eq(last_changed.size(), std::size_t{2});
|
||||
Void::Testing::expect_eq(last_changed[0], std::string{"log.added"});
|
||||
Void::Testing::expect_eq(last_changed[1], std::string{"log.level"});
|
||||
Void::Testing::expect(watch.current().get_or("log.level") ==
|
||||
"debug");
|
||||
}
|
||||
|
||||
Void::Testing::Test config_watch_keeps_old_config_on_parse_error()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_cfgwatch"};
|
||||
const auto file = tmp.path() / "app.ini";
|
||||
write(file, "[log]\nlevel = info\n");
|
||||
|
||||
std::atomic<int> reloads{0};
|
||||
auto watch = ConfigWatch::ini(
|
||||
file,
|
||||
[&](const Config&, const std::vector<std::string>&) {
|
||||
++reloads;
|
||||
},
|
||||
manual_poll());
|
||||
|
||||
write(file, "[broken\nlevel=zzz\n"); // malformed section
|
||||
watch.poll_now();
|
||||
watch.poll_now();
|
||||
|
||||
Void::Testing::expect_eq(reloads.load(), 0);
|
||||
Void::Testing::expect(watch.current().get_or("log.level") ==
|
||||
"info");
|
||||
}
|
||||
|
||||
Void::Testing::Test config_watch_deletion_keeps_last_config()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_cfgwatch"};
|
||||
const auto file = tmp.path() / "app.ini";
|
||||
write(file, "[log]\nlevel = info\n");
|
||||
|
||||
std::atomic<int> reloads{0};
|
||||
auto watch = ConfigWatch::ini(
|
||||
file,
|
||||
[&](const Config&, const std::vector<std::string>&) {
|
||||
++reloads;
|
||||
},
|
||||
manual_poll());
|
||||
|
||||
std::filesystem::remove(file);
|
||||
watch.poll_now();
|
||||
watch.poll_now();
|
||||
|
||||
Void::Testing::expect_eq(reloads.load(), 0);
|
||||
Void::Testing::expect(watch.current().get_or("log.level") ==
|
||||
"info");
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
#include <Void/Log/Logger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
using Void::Logging::CallbackLogger;
|
||||
using Void::Logging::Entry;
|
||||
using Void::Logging::Level;
|
||||
using Void::Logging::Mode;
|
||||
using Void::Logging::OverflowPolicy;
|
||||
|
||||
// ── basics ────────────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test async_is_the_default_mode()
|
||||
{
|
||||
CallbackLogger log{[](const Entry&) {}};
|
||||
Void::Testing::expect(log.mode() == Mode::Async);
|
||||
}
|
||||
|
||||
Void::Testing::Test async_flush_delivers_everything_submitted()
|
||||
{
|
||||
std::atomic<int> delivered{0};
|
||||
CallbackLogger log{[&](const Entry&) { ++delivered; }};
|
||||
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
log.info("entry");
|
||||
}
|
||||
log.flush();
|
||||
Void::Testing::expect_eq(delivered.load(), 100);
|
||||
}
|
||||
|
||||
Void::Testing::Test async_entries_arrive_in_order()
|
||||
{
|
||||
std::vector<std::string> messages;
|
||||
CallbackLogger log{
|
||||
[&](const Entry& e) { messages.push_back(e.message); }};
|
||||
|
||||
log.info("one");
|
||||
log.info("two");
|
||||
log.info("three");
|
||||
log.flush();
|
||||
|
||||
Void::Testing::expect_eq(messages.size(), std::size_t{3});
|
||||
Void::Testing::expect_eq(messages[0], std::string{"one"});
|
||||
Void::Testing::expect_eq(messages[1], std::string{"two"});
|
||||
Void::Testing::expect_eq(messages[2], std::string{"three"});
|
||||
}
|
||||
|
||||
Void::Testing::Test async_level_filter_applies()
|
||||
{
|
||||
std::atomic<int> delivered{0};
|
||||
CallbackLogger log{[&](const Entry&) { ++delivered; }};
|
||||
log.set_level(Level::Warning);
|
||||
|
||||
log.debug("dropped");
|
||||
log.warning("kept");
|
||||
log.flush();
|
||||
Void::Testing::expect_eq(delivered.load(), 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test destructor_flushes_via_derived_contract()
|
||||
{
|
||||
std::atomic<int> delivered{0};
|
||||
{
|
||||
CallbackLogger log{[&](const Entry&) { ++delivered; }};
|
||||
for (int i = 0; i < 32; ++i) {
|
||||
log.info("entry");
|
||||
}
|
||||
// No explicit flush — CallbackLogger's destructor must flush.
|
||||
}
|
||||
Void::Testing::expect_eq(delivered.load(), 32);
|
||||
}
|
||||
|
||||
// ── mode switching (same class, no decorators) ────────────────────────────────
|
||||
|
||||
Void::Testing::Test switch_async_to_immediate_makes_calls_synchronous()
|
||||
{
|
||||
std::atomic<int> delivered{0};
|
||||
std::thread::id write_thread{};
|
||||
CallbackLogger log{[&](const Entry&) {
|
||||
++delivered;
|
||||
write_thread = std::this_thread::get_id();
|
||||
}};
|
||||
|
||||
log.info("async one");
|
||||
log.set_mode(Mode::Immediate); // drains pending first
|
||||
Void::Testing::expect_eq(delivered.load(), 1);
|
||||
|
||||
log.info("sync two");
|
||||
// Immediate: delivered inline on this thread, no flush needed.
|
||||
Void::Testing::expect_eq(delivered.load(), 2);
|
||||
Void::Testing::expect(write_thread == std::this_thread::get_id());
|
||||
}
|
||||
|
||||
Void::Testing::Test switch_immediate_to_async_round_trip()
|
||||
{
|
||||
std::atomic<int> delivered{0};
|
||||
CallbackLogger log{[&](const Entry&) { ++delivered; },
|
||||
Mode::Immediate};
|
||||
|
||||
log.info("sync");
|
||||
Void::Testing::expect_eq(delivered.load(), 1);
|
||||
|
||||
log.set_mode(Mode::Async);
|
||||
log.info("queued");
|
||||
log.flush();
|
||||
Void::Testing::expect_eq(delivered.load(), 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test async_writes_happen_on_worker_thread()
|
||||
{
|
||||
std::thread::id write_thread{};
|
||||
CallbackLogger log{[&](const Entry&) {
|
||||
write_thread = std::this_thread::get_id();
|
||||
}};
|
||||
|
||||
log.info("from main");
|
||||
log.flush();
|
||||
Void::Testing::expect(write_thread != std::this_thread::get_id());
|
||||
}
|
||||
|
||||
// ── overflow policies ─────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test block_policy_loses_nothing_under_pressure()
|
||||
{
|
||||
std::atomic<int> delivered{0};
|
||||
{
|
||||
// Tiny capacity + slow-ish sink forces producers to block.
|
||||
CallbackLogger log{[&](const Entry&) { ++delivered; }, Mode::Async,
|
||||
4, OverflowPolicy::Block};
|
||||
for (int i = 0; i < 500; ++i) {
|
||||
log.info("pressure");
|
||||
}
|
||||
log.flush();
|
||||
}
|
||||
Void::Testing::expect_eq(delivered.load(), 500);
|
||||
}
|
||||
|
||||
Void::Testing::Test drop_newest_policy_bounds_pending()
|
||||
{
|
||||
std::atomic<bool> release{false};
|
||||
std::atomic<int> delivered{0};
|
||||
{
|
||||
CallbackLogger log{[&](const Entry&) {
|
||||
// Stall the worker so the queue stays full.
|
||||
release.wait(false);
|
||||
++delivered;
|
||||
},
|
||||
Mode::Async, 2, OverflowPolicy::DropNewest};
|
||||
for (int i = 0; i < 100; ++i) {
|
||||
log.info("burst");
|
||||
}
|
||||
release = true;
|
||||
release.notify_all();
|
||||
log.flush();
|
||||
}
|
||||
// Far fewer than 100 must have arrived; none blocked the producer.
|
||||
Void::Testing::expect(delivered.load() < 100);
|
||||
Void::Testing::expect(delivered.load() >= 1);
|
||||
}
|
||||
|
||||
// ── multi-producer stress ─────────────────────────────────────────────────────
|
||||
|
||||
// @tag stress, concurrency
|
||||
Void::Testing::Test async_multi_producer_no_loss()
|
||||
{
|
||||
constexpr int producers = 8;
|
||||
constexpr int per_producer = 50'000;
|
||||
|
||||
std::atomic<long long> delivered{0};
|
||||
{
|
||||
CallbackLogger log{[&](const Entry&) { ++delivered; }, Mode::Async,
|
||||
1024, OverflowPolicy::Block};
|
||||
log.set_level(Level::Trace);
|
||||
|
||||
std::vector<std::thread> threads;
|
||||
threads.reserve(producers);
|
||||
for (int p = 0; p < producers; ++p) {
|
||||
threads.emplace_back([&log] {
|
||||
for (int i = 0; i < per_producer; ++i) {
|
||||
log.info("stress");
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& t : threads) {
|
||||
t.join();
|
||||
}
|
||||
log.flush();
|
||||
}
|
||||
Void::Testing::expect_eq(
|
||||
delivered.load(),
|
||||
static_cast<long long>(producers) * per_producer);
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
#include <Void/Data/Json.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <string>
|
||||
|
||||
using Void::Logging::Entry;
|
||||
using Void::Logging::JsonLinesFormatter;
|
||||
using Void::Logging::Level;
|
||||
using Void::Logging::LogfmtFormatter;
|
||||
using Void::Logging::PatternFormatter;
|
||||
|
||||
namespace
|
||||
{
|
||||
Entry make_entry()
|
||||
{
|
||||
Entry e;
|
||||
e.level = Level::Warning;
|
||||
e.message = "disk almost full";
|
||||
e.scopes = {"sys", "disk"};
|
||||
return e;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// ── PatternFormatter ──────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test pattern_default_renders_level_and_message()
|
||||
{
|
||||
PatternFormatter fmt;
|
||||
const auto line = fmt.format(make_entry());
|
||||
Void::Testing::expect(line.find("[Warning]") != std::string::npos);
|
||||
Void::Testing::expect(line.find("disk almost full") !=
|
||||
std::string::npos);
|
||||
Void::Testing::expect(line.find("sys.disk") != std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test pattern_custom_layout()
|
||||
{
|
||||
PatternFormatter fmt{"{level}|{message}"};
|
||||
Void::Testing::expect_eq(fmt.format(make_entry()),
|
||||
std::string{"Warning|disk almost full"});
|
||||
}
|
||||
|
||||
Void::Testing::Test pattern_unknown_placeholder_stays_literal()
|
||||
{
|
||||
PatternFormatter fmt{"{nope} {message}"};
|
||||
Void::Testing::expect_eq(fmt.format(make_entry()),
|
||||
std::string{"{nope} disk almost full"});
|
||||
}
|
||||
|
||||
Void::Testing::Test pattern_time_is_iso8601()
|
||||
{
|
||||
PatternFormatter fmt{"{time}"};
|
||||
const auto line = fmt.format(make_entry());
|
||||
// "2026-06-12T10:30:00.123Z"
|
||||
Void::Testing::expect_eq(line.size(), std::size_t{24});
|
||||
Void::Testing::expect_eq(line[10], 'T');
|
||||
Void::Testing::expect_eq(line.back(), 'Z');
|
||||
}
|
||||
|
||||
// ── JsonLinesFormatter ────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test jsonlines_produces_valid_json_with_fields()
|
||||
{
|
||||
JsonLinesFormatter fmt;
|
||||
const auto line = fmt.format(make_entry());
|
||||
|
||||
const auto parsed = Void::Json::parse(line);
|
||||
Void::Testing::expect(parsed.has_value());
|
||||
Void::Testing::expect_eq((*parsed)["level"].as_string(),
|
||||
std::string{"Warning"});
|
||||
Void::Testing::expect_eq((*parsed)["message"].as_string(),
|
||||
std::string{"disk almost full"});
|
||||
Void::Testing::expect_eq((*parsed)["scopes"].as_array().size(),
|
||||
std::size_t{2});
|
||||
}
|
||||
|
||||
// ── LogfmtFormatter ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test logfmt_renders_key_value_pairs()
|
||||
{
|
||||
LogfmtFormatter fmt;
|
||||
const auto line = fmt.format(make_entry());
|
||||
Void::Testing::expect(line.find("level=Warning") != std::string::npos);
|
||||
Void::Testing::expect(line.find("msg=\"disk almost full\"") !=
|
||||
std::string::npos);
|
||||
Void::Testing::expect(line.find("scopes=sys.disk") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test logfmt_escapes_quotes_in_message()
|
||||
{
|
||||
Entry e = make_entry();
|
||||
e.message = R"(said "hi")";
|
||||
LogfmtFormatter fmt;
|
||||
const auto line = fmt.format(e);
|
||||
Void::Testing::expect(line.find(R"(msg="said \"hi\"")") !=
|
||||
std::string::npos);
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
#include <Void/Configuration/Config.hpp>
|
||||
#include <Void/Log/FromConfig.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <string>
|
||||
|
||||
using Void::Configuration::Config;
|
||||
|
||||
Void::Testing::Test from_config_defaults_to_console()
|
||||
{
|
||||
Config cfg; // empty: console sink, trace level, async
|
||||
const auto logger = Void::Logging::from_config(cfg);
|
||||
Void::Testing::expect(logger.has_value());
|
||||
Void::Testing::expect((*logger)->mode() ==
|
||||
Void::Logging::Mode::Async);
|
||||
}
|
||||
|
||||
Void::Testing::Test from_config_builds_multi_sink_tree()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_fromcfg"};
|
||||
Config cfg;
|
||||
cfg.set("log.sinks", "console, file");
|
||||
cfg.set("log.file.path", (tmp.path() / "a.log").string());
|
||||
cfg.set("log.level", "warning");
|
||||
cfg.set("log.async", "false");
|
||||
|
||||
const auto logger = Void::Logging::from_config(cfg);
|
||||
Void::Testing::expect(logger.has_value());
|
||||
Void::Testing::expect((*logger)->mode() ==
|
||||
Void::Logging::Mode::Immediate);
|
||||
Void::Testing::expect((*logger)->level() ==
|
||||
Void::Logging::Level::Warning);
|
||||
|
||||
(*logger)->warning("to both sinks");
|
||||
(*logger)->flush();
|
||||
std::ifstream f(tmp.path() / "a.log");
|
||||
std::string content((std::istreambuf_iterator<char>(f)), {});
|
||||
Void::Testing::expect(content.find("to both sinks") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test from_config_json_format_applies()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_fromcfg"};
|
||||
Config cfg;
|
||||
cfg.set("log.sinks", "file");
|
||||
cfg.set("log.file.path", (tmp.path() / "j.log").string());
|
||||
cfg.set("log.format", "json");
|
||||
cfg.set("log.async", "false");
|
||||
|
||||
const auto logger = Void::Logging::from_config(cfg);
|
||||
Void::Testing::expect(logger.has_value());
|
||||
(*logger)->info("structured");
|
||||
(*logger)->flush();
|
||||
|
||||
std::ifstream f(tmp.path() / "j.log");
|
||||
std::string line;
|
||||
std::getline(f, line);
|
||||
Void::Testing::expect(line.find("\"message\":\"structured\"") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test from_config_missing_file_path_is_error()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("log.sinks", "file");
|
||||
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test from_config_unknown_sink_is_error()
|
||||
{
|
||||
Config cfg;
|
||||
cfg.set("log.sinks", "carrier-pigeon");
|
||||
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test apply_facade_config_sets_levels()
|
||||
{
|
||||
struct Reset {
|
||||
~Reset()
|
||||
{
|
||||
Void::Log::set_min_level(Void::Log::Level::Trace);
|
||||
Void::Log::clear_module_level("Fsm");
|
||||
}
|
||||
} reset;
|
||||
|
||||
Config cfg;
|
||||
cfg.set("log.level", "error");
|
||||
cfg.set("log.module_levels.Fsm", "trace");
|
||||
Void::Logging::apply_facade_config(cfg);
|
||||
|
||||
Void::Log::set_sink([](auto, auto, auto) {});
|
||||
Void::Testing::expect(
|
||||
!Void::Log::enabled(Void::Log::Level::Info, "Other"));
|
||||
Void::Testing::expect(
|
||||
Void::Log::enabled(Void::Log::Level::Trace, "Fsm"));
|
||||
Void::Log::set_sink({});
|
||||
}
|
||||
@@ -7,9 +7,15 @@
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
// Reset the global sink between tests via a scoped RAII guard.
|
||||
// Reset the global facade state between tests via a scoped RAII guard.
|
||||
struct SinkGuard {
|
||||
~SinkGuard() { Void::Log::set_sink({}); }
|
||||
~SinkGuard()
|
||||
{
|
||||
Void::Log::set_sink({});
|
||||
Void::Log::set_min_level(Void::Log::Level::Trace);
|
||||
Void::Log::clear_module_level("Filtered");
|
||||
Void::Log::clear_module_level("Verbose");
|
||||
}
|
||||
};
|
||||
|
||||
Void::Testing::Test no_sink_is_silent()
|
||||
@@ -105,3 +111,119 @@ Void::Testing::Test all_levels_are_forwarded()
|
||||
|
||||
Void::Testing::expect_eq(calls, 6);
|
||||
}
|
||||
|
||||
// ── leveled helpers & lazy formatting ─────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test leveled_helpers_format_arguments()
|
||||
{
|
||||
SinkGuard guard;
|
||||
std::string got;
|
||||
Void::Log::Level got_level{};
|
||||
Void::Log::set_sink([&](Void::Log::Level l, auto, std::string_view msg) {
|
||||
got_level = l;
|
||||
got = msg;
|
||||
});
|
||||
|
||||
Void::Log::warn("m", "answer = {}", 42);
|
||||
Void::Testing::expect(got_level == Void::Log::Level::Warning);
|
||||
Void::Testing::expect_eq(got, std::string{"answer = 42"});
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
// A format argument whose formatting is observable — proves laziness.
|
||||
struct FormatProbe {
|
||||
int* format_count;
|
||||
};
|
||||
} // namespace
|
||||
|
||||
template <>
|
||||
struct std::formatter<FormatProbe> : std::formatter<int> {
|
||||
template <class Ctx>
|
||||
auto format(const FormatProbe& p, Ctx& ctx) const
|
||||
{
|
||||
++*p.format_count;
|
||||
return std::formatter<int>::format(0, ctx);
|
||||
}
|
||||
};
|
||||
|
||||
Void::Testing::Test disabled_calls_do_not_format()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int formatted = 0;
|
||||
|
||||
// No sink: nothing may be formatted.
|
||||
Void::Log::debug("m", "{}", FormatProbe{&formatted});
|
||||
Void::Testing::expect_eq(formatted, 0);
|
||||
|
||||
// Sink present but level below the global minimum: still nothing.
|
||||
int calls = 0;
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
|
||||
Void::Log::set_min_level(Void::Log::Level::Error);
|
||||
Void::Log::debug("m", "{}", FormatProbe{&formatted});
|
||||
Void::Testing::expect_eq(formatted, 0);
|
||||
Void::Testing::expect_eq(calls, 0);
|
||||
|
||||
// Passing the gate formats exactly once.
|
||||
Void::Log::error("m", "{}", FormatProbe{&formatted});
|
||||
Void::Testing::expect_eq(formatted, 1);
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
}
|
||||
|
||||
// ── level filtering ───────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test global_min_level_filters()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int calls = 0;
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
|
||||
Void::Log::set_min_level(Void::Log::Level::Warning);
|
||||
|
||||
Void::Log::info("m", "dropped");
|
||||
Void::Log::warn("m", "kept");
|
||||
Void::Log::error("m", "kept");
|
||||
Void::Testing::expect_eq(calls, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test disabled_level_silences_everything()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int calls = 0;
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
|
||||
Void::Log::set_min_level(Void::Log::Level::Disabled);
|
||||
|
||||
Void::Log::fatal("m", "still dropped");
|
||||
Void::Testing::expect_eq(calls, 0);
|
||||
}
|
||||
|
||||
Void::Testing::Test module_override_lowers_and_raises()
|
||||
{
|
||||
SinkGuard guard;
|
||||
int calls = 0;
|
||||
Void::Log::set_sink([&](auto, auto, auto) { ++calls; });
|
||||
Void::Log::set_min_level(Void::Log::Level::Warning);
|
||||
|
||||
// Lower the threshold for one module only.
|
||||
Void::Log::set_module_level("Verbose", Void::Log::Level::Trace);
|
||||
Void::Log::debug("Verbose", "kept by override");
|
||||
Void::Log::debug("Other", "dropped by global");
|
||||
Void::Testing::expect_eq(calls, 1);
|
||||
|
||||
// Raise the threshold for one module above the global.
|
||||
Void::Log::set_module_level("Filtered", Void::Log::Level::Fatal);
|
||||
Void::Log::error("Filtered", "dropped by override");
|
||||
Void::Log::error("Other", "kept by global");
|
||||
Void::Testing::expect_eq(calls, 2);
|
||||
}
|
||||
|
||||
Void::Testing::Test enabled_reflects_configuration()
|
||||
{
|
||||
SinkGuard guard;
|
||||
Void::Testing::expect(
|
||||
!Void::Log::enabled(Void::Log::Level::Fatal, "m")); // no sink
|
||||
|
||||
Void::Log::set_sink([](auto, auto, auto) {});
|
||||
Void::Log::set_min_level(Void::Log::Level::Info);
|
||||
Void::Testing::expect(Void::Log::enabled(Void::Log::Level::Info, "m"));
|
||||
Void::Testing::expect(!Void::Log::enabled(Void::Log::Level::Debug, "m"));
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Fixture.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
|
||||
using namespace Void::Logging;
|
||||
|
||||
// ── NullLogger / CallbackLogger ───────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test null_logger_swallows_everything()
|
||||
{
|
||||
NullLogger log;
|
||||
log.fatal("into the void");
|
||||
log.flush();
|
||||
Void::Testing::expect(true); // reached without crashing
|
||||
}
|
||||
|
||||
Void::Testing::Test callback_logger_receives_entry_fields()
|
||||
{
|
||||
Entry got;
|
||||
CallbackLogger log{[&](const Entry& e) { got = e; },
|
||||
Mode::Immediate};
|
||||
log.warning("payload");
|
||||
Void::Testing::expect(got.level == Level::Warning);
|
||||
Void::Testing::expect_eq(got.message, std::string{"payload"});
|
||||
}
|
||||
|
||||
// ── MultiLogger ───────────────────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test multi_logger_fans_out_to_all_children()
|
||||
{
|
||||
int a = 0;
|
||||
int b = 0;
|
||||
MultiLogger multi;
|
||||
multi.add(std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++a; }, Mode::Immediate));
|
||||
multi.add(std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++b; }, Mode::Immediate));
|
||||
|
||||
multi.info("to both");
|
||||
Void::Testing::expect_eq(a, 1);
|
||||
Void::Testing::expect_eq(b, 1);
|
||||
Void::Testing::expect_eq(multi.child_count(), std::size_t{2});
|
||||
}
|
||||
|
||||
Void::Testing::Test multi_logger_children_keep_own_levels()
|
||||
{
|
||||
int verbose_count = 0;
|
||||
int errors_only = 0;
|
||||
auto verbose = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++verbose_count; }, Mode::Immediate);
|
||||
auto strict = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++errors_only; }, Mode::Immediate);
|
||||
strict->set_level(Level::Error);
|
||||
|
||||
MultiLogger multi;
|
||||
multi.add(verbose);
|
||||
multi.add(strict);
|
||||
|
||||
multi.info("info");
|
||||
multi.error("error");
|
||||
Void::Testing::expect_eq(verbose_count, 2);
|
||||
Void::Testing::expect_eq(errors_only, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test multi_logger_relays_async_children_with_flush()
|
||||
{
|
||||
int delivered = 0;
|
||||
auto async_child = std::make_shared<CallbackLogger>(
|
||||
[&](const Entry&) { ++delivered; }); // Async by default
|
||||
MultiLogger multi;
|
||||
multi.add(async_child);
|
||||
|
||||
multi.info("queued in child");
|
||||
multi.flush(); // flushes children too
|
||||
Void::Testing::expect_eq(delivered, 1);
|
||||
}
|
||||
|
||||
// ── ConsoleLogger + Formatter ─────────────────────────────────────────────────
|
||||
|
||||
Void::Testing::Test console_logger_uses_installed_formatter()
|
||||
{
|
||||
std::ostringstream out;
|
||||
{
|
||||
ConsoleLogger log{out, Mode::Immediate};
|
||||
log.set_formatter(
|
||||
std::make_shared<PatternFormatter>("{level}>{message}"));
|
||||
log.info("custom format");
|
||||
}
|
||||
Void::Testing::expect_eq(out.str(),
|
||||
std::string{"Info>custom format\n"});
|
||||
}
|
||||
|
||||
// ── RotatingFileLogger ────────────────────────────────────────────────────────
|
||||
|
||||
class RotatingFileLoggerTests : public Void::Testing::Fixture
|
||||
{
|
||||
public:
|
||||
|
||||
std::filesystem::path dir;
|
||||
std::filesystem::path file;
|
||||
|
||||
void setup() override
|
||||
{
|
||||
dir = std::filesystem::temp_directory_path() /
|
||||
"void_rotating_test";
|
||||
std::filesystem::remove_all(dir);
|
||||
std::filesystem::create_directories(dir);
|
||||
file = dir / "app.log";
|
||||
}
|
||||
|
||||
void teardown() override { std::filesystem::remove_all(dir); }
|
||||
|
||||
static std::string slurp(const std::filesystem::path& p)
|
||||
{
|
||||
std::ifstream f(p);
|
||||
return {std::istreambuf_iterator<char>(f), {}};
|
||||
}
|
||||
|
||||
Void::Testing::Test writes_and_flushes()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger log{file};
|
||||
log.info("rotating hello");
|
||||
}
|
||||
Void::Testing::expect(slurp(file).find("rotating hello") !=
|
||||
std::string::npos);
|
||||
}
|
||||
|
||||
Void::Testing::Test rotates_when_size_exceeded()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger::Options opt;
|
||||
opt.max_bytes = 256;
|
||||
opt.max_files = 3;
|
||||
opt.mode = Mode::Immediate;
|
||||
RotatingFileLogger log{file, opt};
|
||||
for (int i = 0; i < 40; ++i) {
|
||||
log.info("a reasonably long line to fill the file " +
|
||||
std::to_string(i));
|
||||
}
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(file));
|
||||
auto rotated = file;
|
||||
rotated += ".1";
|
||||
Void::Testing::expect(std::filesystem::exists(rotated));
|
||||
// The bound holds: no file beyond .3
|
||||
auto beyond = file;
|
||||
beyond += ".4";
|
||||
Void::Testing::expect(!std::filesystem::exists(beyond));
|
||||
}
|
||||
|
||||
Void::Testing::Test open_factory_rejects_bad_path()
|
||||
{
|
||||
auto r = RotatingFileLogger::open(
|
||||
"/this/path/does/not/exist/app.log");
|
||||
Void::Testing::expect(!r.has_value());
|
||||
}
|
||||
|
||||
Void::Testing::Test async_rotation_under_load()
|
||||
{
|
||||
{
|
||||
RotatingFileLogger::Options opt;
|
||||
opt.max_bytes = 512;
|
||||
opt.max_files = 2;
|
||||
RotatingFileLogger log{file, opt}; // Async default
|
||||
for (int i = 0; i < 200; ++i) {
|
||||
log.info("async rotation line " + std::to_string(i));
|
||||
}
|
||||
log.flush();
|
||||
}
|
||||
Void::Testing::expect(std::filesystem::exists(file));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
#include <Void/System/FileWatcher.hpp>
|
||||
#include <Void/System/Path.hpp>
|
||||
#include <Void/System/TempDir.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <thread>
|
||||
|
||||
using Void::FileSystem::FileWatcher;
|
||||
|
||||
namespace
|
||||
{
|
||||
// Long poll interval so only explicit poll_now() rounds matter.
|
||||
FileWatcher::Options manual_poll()
|
||||
{
|
||||
return {.poll_interval = std::chrono::milliseconds{60'000},
|
||||
.debounce_polls = 2};
|
||||
}
|
||||
|
||||
int write_counter = 0;
|
||||
|
||||
void write(const std::filesystem::path& p, std::string_view text)
|
||||
{
|
||||
auto r = Void::FileSystem::write_file(p, text);
|
||||
Void::Testing::expect(r.has_value());
|
||||
// Nudge mtime forward — coarse filesystem timestamps could
|
||||
// otherwise hide consecutive writes from the watcher.
|
||||
const auto now = std::filesystem::file_time_type::clock::now();
|
||||
std::filesystem::last_write_time(
|
||||
p, now + std::chrono::milliseconds{(++write_counter) * 10});
|
||||
}
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test watcher_fires_after_debounce()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_watch"};
|
||||
const auto file = tmp.path() / "config.txt";
|
||||
write(file, "v1");
|
||||
|
||||
std::atomic<int> fired{0};
|
||||
FileWatcher watcher{manual_poll()};
|
||||
watcher.watch(file, [&](const FileWatcher::Event& e) {
|
||||
Void::Testing::expect(e.exists);
|
||||
++fired;
|
||||
});
|
||||
|
||||
write(file, "v2-with-different-size");
|
||||
watcher.poll_now(); // change observed, stability count = 1
|
||||
Void::Testing::expect_eq(fired.load(), 0);
|
||||
watcher.poll_now(); // stable for 2 polls -> fires
|
||||
Void::Testing::expect_eq(fired.load(), 1);
|
||||
watcher.poll_now(); // no further change -> no further events
|
||||
Void::Testing::expect_eq(fired.load(), 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test watcher_debounce_restarts_while_changing()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_watch"};
|
||||
const auto file = tmp.path() / "config.txt";
|
||||
write(file, "v1");
|
||||
|
||||
std::atomic<int> fired{0};
|
||||
FileWatcher watcher{manual_poll()};
|
||||
watcher.watch(file, [&](const FileWatcher::Event&) { ++fired; });
|
||||
|
||||
write(file, "second version");
|
||||
watcher.poll_now();
|
||||
write(file, "third version, longer again");
|
||||
watcher.poll_now(); // still changing -> debounce restarts
|
||||
Void::Testing::expect_eq(fired.load(), 0);
|
||||
watcher.poll_now();
|
||||
Void::Testing::expect_eq(fired.load(), 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test watcher_reports_deletion()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_watch"};
|
||||
const auto file = tmp.path() / "config.txt";
|
||||
write(file, "v1");
|
||||
|
||||
std::atomic<int> gone{0};
|
||||
FileWatcher watcher{manual_poll()};
|
||||
watcher.watch(file, [&](const FileWatcher::Event& e) {
|
||||
if (!e.exists) {
|
||||
++gone;
|
||||
}
|
||||
});
|
||||
|
||||
std::filesystem::remove(file);
|
||||
watcher.poll_now();
|
||||
watcher.poll_now();
|
||||
Void::Testing::expect_eq(gone.load(), 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test watcher_unwatch_stops_events()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_watch"};
|
||||
const auto file = tmp.path() / "config.txt";
|
||||
write(file, "v1");
|
||||
|
||||
std::atomic<int> fired{0};
|
||||
FileWatcher watcher{manual_poll()};
|
||||
watcher.watch(file, [&](const FileWatcher::Event&) { ++fired; });
|
||||
Void::Testing::expect_eq(watcher.watch_count(), std::size_t{1});
|
||||
|
||||
watcher.unwatch(file);
|
||||
Void::Testing::expect_eq(watcher.watch_count(), std::size_t{0});
|
||||
|
||||
write(file, "changed");
|
||||
watcher.poll_now();
|
||||
watcher.poll_now();
|
||||
Void::Testing::expect_eq(fired.load(), 0);
|
||||
}
|
||||
|
||||
// @tag integration
|
||||
Void::Testing::Test watcher_background_thread_fires_on_its_own()
|
||||
{
|
||||
Void::FileSystem::TempDir tmp{"void_watch"};
|
||||
const auto file = tmp.path() / "config.txt";
|
||||
write(file, "v1");
|
||||
|
||||
std::atomic<int> fired{0};
|
||||
FileWatcher watcher{
|
||||
{.poll_interval = std::chrono::milliseconds{10},
|
||||
.debounce_polls = 2}};
|
||||
watcher.watch(file, [&](const FileWatcher::Event&) { ++fired; });
|
||||
|
||||
write(file, "v2 changed contents");
|
||||
for (int i = 0; i < 200 && fired.load() == 0; ++i) {
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds{5});
|
||||
}
|
||||
Void::Testing::expect_eq(fired.load(), 1);
|
||||
}
|
||||
Reference in new issue
Block a user