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,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>)
|
||||
Reference in new issue
Block a user