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

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

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

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

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

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

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

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

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

No files matched your search

+2 -5
View File
@@ -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;
+168
View File
@@ -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
+400 -18
View File
@@ -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_;
};
+159
View File
@@ -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
+17 -6
View File
@@ -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
+20 -8
View File
@@ -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
+103
View File
@@ -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
+45
View File
@@ -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
View File
@@ -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
View File
@@ -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;
+2
View File
@@ -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
+82
View File
@@ -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
+114
View File
@@ -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
+44
View File
@@ -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>)
+94
View File
@@ -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
+17 -32
View File
@@ -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()));
+16 -29
View File
@@ -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 {};
}
+3 -6
View File
@@ -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;
}
}