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
@@ -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_;
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user