feat(Log): harden LogState facade, bounded Logger delivery/tickets/quarantine, file sync/reopen, redaction, and separate LogConfig (M-LOG-01..05)
This commit is contained in:
1 parent
18a623aa62
commit
a74a402938
23 files changed
+2656
-1197
No files matched your search
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
@@ -12,37 +14,12 @@ namespace Void::Logging::Detail
|
||||
struct RollingFileOptions {
|
||||
std::size_t max_bytes = 1024 * 1024;
|
||||
std::size_t max_files = 5;
|
||||
bool create_directories = true;
|
||||
};
|
||||
|
||||
/// Format a time point as a filesystem-safe, lexicographically (and
|
||||
/// therefore chronologically) sortable UTC timestamp:
|
||||
/// `YYYYMMDD-HHMMSS-ffffff` (microseconds).
|
||||
[[nodiscard]] std::string
|
||||
format_timestamp(std::chrono::system_clock::time_point tp);
|
||||
|
||||
/// A single append-only log file with size-based rotation. Not thread
|
||||
/// safe — each sink owns one and drives it from its single worker.
|
||||
///
|
||||
/// Two rotation modes, selected by the `self_rotate` constructor
|
||||
/// argument:
|
||||
///
|
||||
/// - self_rotate = true (default), "solo": write() rotates on its
|
||||
/// own once the file exceeds max_bytes. The live file is closed
|
||||
/// and renamed in place to `<name>-<rotation_time>` — same
|
||||
/// directory, no subfolder. At most max_files such archives are
|
||||
/// kept; the oldest (by name, which sorts chronologically) is
|
||||
/// deleted. With max_files == 0 nothing is kept — the file is
|
||||
/// just truncated.
|
||||
///
|
||||
/// - self_rotate = false, "grouped": write() only tracks size and
|
||||
/// never rotates by itself. The owner polls exceeds_limit()
|
||||
/// across a set of RollingFiles and, once any one of them crosses
|
||||
/// the threshold, calls snapshot_into(dir) on every file in that
|
||||
/// set so they all land — under their original names — in the
|
||||
/// same directory at the same moment (e.g. so several files can
|
||||
/// roll together into one shared `history/<creation_time>/`).
|
||||
/// max_files does not apply to this path: nothing is ever deleted,
|
||||
/// every snapshot is kept.
|
||||
class RollingFile
|
||||
{
|
||||
public:
|
||||
@@ -50,32 +27,18 @@ namespace Void::Logging::Detail
|
||||
RollingFile(std::filesystem::path path, RollingFileOptions opt,
|
||||
bool self_rotate = true);
|
||||
|
||||
/// Open for append (creating parent dirs). False on failure.
|
||||
[[nodiscard]] bool open();
|
||||
[[nodiscard]] bool reopen();
|
||||
|
||||
/// Append a line (a trailing '\n' is added). In solo mode,
|
||||
/// rotates automatically once max_bytes is exceeded; in
|
||||
/// grouped mode this only updates the byte count — the
|
||||
/// caller drives rotation via exceeds_limit()/snapshot_into().
|
||||
/// No-op if not open.
|
||||
void write(std::string_view line);
|
||||
|
||||
void flush();
|
||||
[[nodiscard]] Void::Result::Result<void> sync();
|
||||
|
||||
/// True once the current file has reached max_bytes. Meant
|
||||
/// for grouped (self_rotate == false) use, so an owner can
|
||||
/// check a whole set of files and decide when to roll them
|
||||
/// together.
|
||||
[[nodiscard]] bool exceeds_limit() const noexcept
|
||||
{
|
||||
return m_current_bytes >= m_opt.max_bytes;
|
||||
}
|
||||
|
||||
/// Move the live file — same name, unmodified — into `dir`
|
||||
/// (created if needed), then continue with a fresh file at
|
||||
/// path(). Ignores max_files; nothing is ever deleted here.
|
||||
/// Intended to be called on every file in a group so they
|
||||
/// land together.
|
||||
void snapshot_into(const std::filesystem::path& dir);
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept
|
||||
@@ -102,4 +65,4 @@ namespace Void::Logging::Detail
|
||||
std::chrono::time_point<std::chrono::system_clock> m_rotationTime;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging::Detail
|
||||
} // namespace Void::Logging::Detail
|
||||
@@ -11,14 +11,6 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Distinguishes regular messages from scope boundary markers.
|
||||
///
|
||||
/// Sinks may use Kind to render scope entries differently —
|
||||
/// e.g. with indentation, brackets, or a dedicated colour.
|
||||
///
|
||||
/// Message — a regular log record
|
||||
/// ScopeEnter — emitted when a named scope opens (scope() call)
|
||||
/// ScopeExit — emitted when a named scope closes (RAII destructor)
|
||||
enum class Kind { Message, ScopeEnter, ScopeExit };
|
||||
|
||||
/// A single, immutable log record produced by Logger and handed to
|
||||
@@ -44,18 +36,15 @@ namespace Void::Logging
|
||||
std::thread::id thread_id{std::this_thread::get_id()};
|
||||
|
||||
/// Frozen snapshot of the thread-local ScopedContext stack at log
|
||||
/// time. Ordered outermost → innermost (index 0 is the root
|
||||
/// scope). For ScopeEnter this already includes the new scope as
|
||||
/// the last element; for ScopeExit it reflects the stack *before*
|
||||
/// the pop.
|
||||
/// time.
|
||||
std::vector<std::string> scopes{};
|
||||
|
||||
/// Structured key/value fields attached to this entry — a frozen
|
||||
/// snapshot of the thread-local FieldScope stack at log time.
|
||||
/// Formatters expose them as custom pattern tokens
|
||||
/// (`{field:key}`) and in JSON/logfmt output. Later duplicate
|
||||
/// keys win.
|
||||
/// Structured key/value fields attached to this entry.
|
||||
std::vector<std::pair<std::string, std::string>> fields{};
|
||||
|
||||
/// True when explicit oversize-truncation policy clipped message,
|
||||
/// fields, scopes, or formatted payload.
|
||||
bool truncated{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
@@ -12,21 +12,6 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Logger sink that appends formatted entries to a file on disk.
|
||||
///
|
||||
/// 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
|
||||
/// `Result<unique_ptr<FileLogger>, Error>` and never throws —
|
||||
/// prefer this in code that already uses Void::Result for error
|
||||
/// plumbing.
|
||||
/// - The throwing constructor stays for callers that prefer
|
||||
/// exceptions; it throws std::runtime_error if the path cannot
|
||||
/// be opened for append.
|
||||
class FileLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
@@ -35,6 +20,9 @@ namespace Void::Logging
|
||||
Mode mode = Mode::Async,
|
||||
std::size_t capacity = 512);
|
||||
|
||||
explicit FileLogger(const std::filesystem::path& path,
|
||||
LoggerOptions options);
|
||||
|
||||
~FileLogger() noexcept override;
|
||||
|
||||
FileLogger(const FileLogger&) = delete;
|
||||
@@ -42,21 +30,30 @@ namespace Void::Logging
|
||||
FileLogger(FileLogger&&) = delete;
|
||||
FileLogger& operator=(FileLogger&&) = delete;
|
||||
|
||||
/// Non-throwing factory. On failure returns
|
||||
/// `Failure<Error>{Error{"FileLogger: cannot open '<path>'"}}`.
|
||||
[[nodiscard]] static Void::Result::
|
||||
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path,
|
||||
Mode mode = Mode::Async,
|
||||
std::size_t capacity = 512);
|
||||
|
||||
/// Install a formatter replacing the default "[Level] message"
|
||||
/// rendering. Call before logging starts.
|
||||
[[nodiscard]] static Void::Result::
|
||||
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path,
|
||||
LoggerOptions options);
|
||||
|
||||
void set_formatter(std::shared_ptr<const Formatter> formatter)
|
||||
{
|
||||
m_formatter = std::move(formatter);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> reopen();
|
||||
[[nodiscard]] Void::Result::Result<void> sync_files() override;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
void write(const Entry& entry) override;
|
||||
@@ -71,4 +68,4 @@ namespace Void::Logging
|
||||
std::shared_ptr<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
@@ -1,8 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
@@ -11,11 +13,6 @@
|
||||
|
||||
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:
|
||||
@@ -26,8 +23,6 @@ namespace Void::Logging
|
||||
format(const Entry& entry) const = 0;
|
||||
};
|
||||
|
||||
// ── colour ────────────────────────────────────────────────────────────
|
||||
|
||||
enum class AnsiColor {
|
||||
Default,
|
||||
Black,
|
||||
@@ -48,99 +43,24 @@ namespace Void::Logging
|
||||
BrightWhite,
|
||||
};
|
||||
|
||||
/// Parse a colour name ("red", "bright_black", "cyan", ...). Returns
|
||||
/// AnsiColor::Default for unknown names.
|
||||
[[nodiscard]] AnsiColor parse_color(std::string_view name) noexcept;
|
||||
|
||||
/// SGR escape for a colour ("\x1b[31m"); empty for Default.
|
||||
[[nodiscard]] std::string_view ansi_code(AnsiColor color) noexcept;
|
||||
|
||||
inline constexpr std::string_view kAnsiReset = "\x1b[0m";
|
||||
|
||||
/// Colour configuration for a PatternFormatter. Disabled by default;
|
||||
/// ConsoleLogger turns it on when the stream is a colour-capable TTY.
|
||||
struct ColorPolicy {
|
||||
bool enabled = false;
|
||||
std::unordered_map<Level, AnsiColor> level_colors;
|
||||
std::unordered_map<std::string, AnsiColor> token_colors;
|
||||
|
||||
/// Sensible per-level defaults (Trace dim → Fatal bright magenta).
|
||||
[[nodiscard]] static ColorPolicy defaults();
|
||||
};
|
||||
|
||||
// ── PatternFormatter ──────────────────────────────────────────────────
|
||||
//
|
||||
// Placeholder pattern with per-token appearance and colour.
|
||||
//
|
||||
// {token} — substitute the token
|
||||
// {token:spec} — spec = [align][width][,colour]
|
||||
// align : '<' left (default), '>' right, '^'
|
||||
// centre width : decimal field width (padded with
|
||||
// spaces) colour: a name ("cyan") or "auto" (=
|
||||
// level colour)
|
||||
//
|
||||
// Built-in tokens: time, level, thread, scopes, message, file, line,
|
||||
// kind. An unknown token resolves against registered custom tokens
|
||||
// (register_token), then against Entry::fields by key, and otherwise
|
||||
// stays literal — so `{request_id:>8}` prints a structured field.
|
||||
//
|
||||
// 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;
|
||||
|
||||
/// Add a custom token. `name` becomes usable as `{name}`.
|
||||
/// Overrides a built-in of the same name.
|
||||
void register_token(std::string name,
|
||||
std::function<std::string(const Entry&)>
|
||||
renderer);
|
||||
|
||||
void set_color_policy(ColorPolicy policy)
|
||||
{
|
||||
m_colors = std::move(policy);
|
||||
}
|
||||
|
||||
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
|
||||
{
|
||||
return m_colors;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
enum class Align { Left, Right, Center };
|
||||
enum class ColorMode { None, Auto, Fixed };
|
||||
|
||||
struct Segment {
|
||||
bool literal{true};
|
||||
std::string text; // literal text, or the token name
|
||||
Align align{Align::Left};
|
||||
std::size_t width{0};
|
||||
ColorMode color_mode{ColorMode::None};
|
||||
AnsiColor color{AnsiColor::Default};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string render_token(const Segment& seg,
|
||||
const Entry& entry) const;
|
||||
|
||||
std::vector<Segment> m_segments;
|
||||
std::unordered_map<std::string,
|
||||
std::function<std::string(const Entry&)>>
|
||||
m_custom;
|
||||
ColorPolicy m_colors;
|
||||
};
|
||||
|
||||
/// An allow/deny list applied to an entry's structured fields by the
|
||||
/// json/logfmt sinks. `include` empty means "all keys" (still subject to
|
||||
/// `exclude`); a non-empty `include` admits only those keys. `exclude`
|
||||
/// always wins.
|
||||
struct FieldFilter {
|
||||
std::vector<std::string> include;
|
||||
std::vector<std::string> exclude;
|
||||
std::vector<std::string> include{};
|
||||
std::vector<std::string> exclude{};
|
||||
std::vector<std::string> redact{};
|
||||
std::string redaction_mask{"[REDACTED]"};
|
||||
|
||||
[[nodiscard]] bool allows(std::string_view key) const
|
||||
{
|
||||
@@ -159,9 +79,68 @@ namespace Void::Logging
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_redacted(std::string_view key) const
|
||||
{
|
||||
for (const auto& r : redact) {
|
||||
if (r == key) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
class PatternFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
|
||||
explicit PatternFormatter(
|
||||
std::string pattern = "{time} [{level}] {scopes}{message}");
|
||||
|
||||
[[nodiscard]] std::string format(const Entry& entry) const override;
|
||||
|
||||
void register_token(std::string name,
|
||||
std::function<std::string(const Entry&)>
|
||||
renderer);
|
||||
|
||||
void set_color_policy(ColorPolicy policy)
|
||||
{
|
||||
m_colors = std::move(policy);
|
||||
}
|
||||
|
||||
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
|
||||
{
|
||||
return m_colors;
|
||||
}
|
||||
|
||||
void set_field_filter(FieldFilter f) { m_fields = std::move(f); }
|
||||
|
||||
private:
|
||||
|
||||
enum class Align { Left, Right, Center };
|
||||
enum class ColorMode { None, Auto, Fixed };
|
||||
|
||||
struct Segment {
|
||||
bool literal{true};
|
||||
std::string text;
|
||||
Align align{Align::Left};
|
||||
std::size_t width{0};
|
||||
ColorMode color_mode{ColorMode::None};
|
||||
AnsiColor color{AnsiColor::Default};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string render_token(const Segment& seg,
|
||||
const Entry& entry) const;
|
||||
|
||||
std::vector<Segment> m_segments;
|
||||
std::unordered_map<std::string,
|
||||
std::function<std::string(const Entry&)>>
|
||||
m_custom;
|
||||
ColorPolicy m_colors;
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
/// One compact JSON object per entry (includes fields when present).
|
||||
class JsonLinesFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
@@ -175,7 +154,6 @@ namespace Void::Logging
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
/// logfmt: time=... level=... thread=... msg="..." plus scopes/fields.
|
||||
class LogfmtFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
@@ -189,15 +167,19 @@ namespace Void::Logging
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
format_bounded(const Formatter& formatter,
|
||||
const Entry& entry,
|
||||
std::size_t max_bytes = 64ULL * 1024ULL,
|
||||
bool truncate = false);
|
||||
|
||||
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
|
||||
} // namespace Void::Logging
|
||||
+208
-53
@@ -1,8 +1,12 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <concepts>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <source_location>
|
||||
@@ -11,6 +15,7 @@
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// ── Void::Log — the emission facade
|
||||
// ─────────────────────────────────────────── Header-only apart from its
|
||||
@@ -18,18 +23,6 @@
|
||||
// once per process, so every module (including INTERFACE libraries) can log by
|
||||
// linking only that. 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
|
||||
{
|
||||
@@ -44,23 +37,24 @@ namespace Void::Log
|
||||
Disabled
|
||||
};
|
||||
|
||||
/// Signature for any log consumer. Four arguments:
|
||||
/// level — severity of the event
|
||||
/// module — short library-internal label (e.g. "System.Process")
|
||||
/// message — human-readable description
|
||||
/// location — the call site that emitted the event (file/line/function)
|
||||
/// Signature for any log consumer.
|
||||
using Sink =
|
||||
std::function<void(Level level, std::string_view module,
|
||||
std::string_view message,
|
||||
const std::source_location& location)>;
|
||||
|
||||
using RegistrationId = std::uint64_t;
|
||||
|
||||
enum class DrainResult : std::uint8_t {
|
||||
drained = 0,
|
||||
not_found,
|
||||
would_deadlock
|
||||
};
|
||||
|
||||
using EmergencyHandler = void (*)(std::string_view message) noexcept;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
// std::source_location cannot follow a variadic pack in a parameter
|
||||
// list, so this wrapper captures the format string together with the
|
||||
// caller's source location in its (consteval) constructor.
|
||||
// std::type_identity_t<Args>... keeps Args non-deduced here, so they
|
||||
// are deduced solely from the trailing argument pack.
|
||||
template <typename... Args> struct FmtLoc {
|
||||
std::format_string<Args...> fmt;
|
||||
std::source_location location;
|
||||
@@ -74,36 +68,176 @@ namespace Void::Log
|
||||
}
|
||||
};
|
||||
|
||||
struct SinkRegistration {
|
||||
RegistrationId id{0};
|
||||
Sink sink{};
|
||||
std::shared_ptr<const void> owner{};
|
||||
std::atomic<bool> detached{false};
|
||||
std::atomic<std::size_t> active_calls{0};
|
||||
std::mutex drain_mutex;
|
||||
std::condition_variable drain_cv;
|
||||
};
|
||||
|
||||
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};
|
||||
std::atomic<std::uint64_t> reentrant_dropped{0};
|
||||
std::atomic<EmergencyHandler> emergency_handler{nullptr};
|
||||
|
||||
// Slow path.
|
||||
Sink sink;
|
||||
// Slow path (registration is immutable after creation;
|
||||
// invoked and destroyed strictly outside `mutex`).
|
||||
std::shared_ptr<SinkRegistration> registration{};
|
||||
RegistrationId next_id{0};
|
||||
std::unordered_map<RegistrationId, std::weak_ptr<SinkRegistration>> known;
|
||||
std::unordered_map<std::string, Level> module_levels;
|
||||
std::shared_mutex mutex;
|
||||
};
|
||||
|
||||
// The process's one State, defined in Void::LogState (a static in an
|
||||
// inline function would be one per DLL on Windows).
|
||||
inline constexpr std::size_t kMaxNestedFacadeSinks = 8;
|
||||
|
||||
// Process-wide singleton accessors defined in Void::LogState.
|
||||
State& state();
|
||||
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept;
|
||||
|
||||
struct ActiveRegistrationGuard {
|
||||
std::shared_ptr<SinkRegistration> reg;
|
||||
std::vector<const SinkRegistration*>& stack;
|
||||
|
||||
ActiveRegistrationGuard(std::shared_ptr<SinkRegistration> r,
|
||||
std::vector<const SinkRegistration*>& st)
|
||||
: reg(std::move(r)), stack(st)
|
||||
{
|
||||
stack.push_back(reg.get());
|
||||
}
|
||||
|
||||
~ActiveRegistrationGuard() noexcept
|
||||
{
|
||||
if (!stack.empty()) {
|
||||
stack.pop_back();
|
||||
}
|
||||
if (reg->active_calls.fetch_sub(
|
||||
1, std::memory_order_acq_rel) == 1) {
|
||||
std::lock_guard lock{reg->drain_mutex};
|
||||
reg->drain_cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
ActiveRegistrationGuard(const ActiveRegistrationGuard&) = delete;
|
||||
ActiveRegistrationGuard&
|
||||
operator=(const ActiveRegistrationGuard&) = delete;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
/// Install the global sink. Any previously installed sink is replaced.
|
||||
/// Pass a default-constructed (empty) Sink to silence all output.
|
||||
/// Thread-safe: the new sink is visible to all threads after this returns.
|
||||
inline void set_sink(Sink sink)
|
||||
/// Install a sink alongside an optional lifetime-keepalive owner and return
|
||||
/// its registration ID for explicit detach_and_drain().
|
||||
inline RegistrationId
|
||||
register_sink(Sink sink, std::shared_ptr<const void> owner = {})
|
||||
{
|
||||
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);
|
||||
std::shared_ptr<Detail::SinkRegistration> prev;
|
||||
RegistrationId id = 0;
|
||||
|
||||
if (sink) {
|
||||
auto next = std::make_shared<Detail::SinkRegistration>();
|
||||
next->sink = std::move(sink);
|
||||
next->owner = std::move(owner);
|
||||
std::unique_lock lock{s.mutex};
|
||||
id = ++s.next_id;
|
||||
next->id = id;
|
||||
s.known.emplace(id, next);
|
||||
for (auto it = s.known.begin(); it != s.known.end();) {
|
||||
if (it->second.expired()) {
|
||||
it = s.known.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
prev = std::exchange(s.registration, std::move(next));
|
||||
if (prev) {
|
||||
prev->detached.store(true, std::memory_order_release);
|
||||
}
|
||||
s.has_sink.store(true, std::memory_order_release);
|
||||
} else {
|
||||
std::unique_lock lock{s.mutex};
|
||||
prev = std::exchange(s.registration, nullptr);
|
||||
if (prev) {
|
||||
prev->detached.store(true, std::memory_order_release);
|
||||
}
|
||||
s.has_sink.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
// Destroy previous callback/owner outside s.mutex.
|
||||
prev.reset();
|
||||
return id;
|
||||
}
|
||||
|
||||
/// Install the global sink. Any previously installed sink is replaced
|
||||
/// outside the facade lock (does not block waiting for in-flight calls).
|
||||
inline void set_sink(Sink sink)
|
||||
{
|
||||
(void)register_sink(std::move(sink), {});
|
||||
}
|
||||
|
||||
/// Detach a registered sink (or active sink when id == 0) and wait until
|
||||
/// all already-admitted invocations using that registration complete.
|
||||
/// Returns would_deadlock if called synchronously from that registration's
|
||||
/// own active callback.
|
||||
[[nodiscard]] inline DrainResult detach_and_drain(RegistrationId id = 0)
|
||||
{
|
||||
auto& s = Detail::state();
|
||||
std::shared_ptr<Detail::SinkRegistration> target;
|
||||
{
|
||||
std::unique_lock lock{s.mutex};
|
||||
if (id == 0) {
|
||||
target = s.registration;
|
||||
} else if (s.registration && s.registration->id == id) {
|
||||
target = s.registration;
|
||||
} else if (const auto it = s.known.find(id); it != s.known.end()) {
|
||||
target = it->second.lock();
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
return DrainResult::not_found;
|
||||
}
|
||||
|
||||
const auto& active = Detail::active_registrations_tls();
|
||||
for (const auto* entry : active) {
|
||||
if (entry == target.get()) {
|
||||
return DrainResult::would_deadlock;
|
||||
}
|
||||
}
|
||||
|
||||
target->detached.store(true, std::memory_order_release);
|
||||
if (target == s.registration) {
|
||||
s.registration.reset();
|
||||
s.has_sink.store(false, std::memory_order_release);
|
||||
}
|
||||
s.known.erase(target->id);
|
||||
}
|
||||
|
||||
{
|
||||
std::unique_lock drain_lock{target->drain_mutex};
|
||||
target->drain_cv.wait(drain_lock, [&target] {
|
||||
return target->active_calls.load(std::memory_order_acquire) == 0;
|
||||
});
|
||||
}
|
||||
target.reset();
|
||||
return DrainResult::drained;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::uint64_t reentrant_dropped() noexcept
|
||||
{
|
||||
return Detail::state().reentrant_dropped.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
inline void set_emergency_handler(EmergencyHandler handler) noexcept
|
||||
{
|
||||
Detail::state().emergency_handler.store(
|
||||
handler, std::memory_order_release);
|
||||
}
|
||||
|
||||
/// 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);
|
||||
@@ -114,8 +248,6 @@ namespace Void::Log
|
||||
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();
|
||||
@@ -124,7 +256,6 @@ namespace Void::Log
|
||||
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();
|
||||
@@ -134,7 +265,6 @@ namespace Void::Log
|
||||
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();
|
||||
@@ -154,15 +284,8 @@ namespace Void::Log
|
||||
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.
|
||||
namespace Detail
|
||||
{
|
||||
// Single, non-overloaded dispatch to the sink. The formatted paths
|
||||
// must forward through this rather than through log() itself: a
|
||||
// log(level, module, std::string, source_location) call would also
|
||||
// match the variadic log() overload (deducing source_location as a
|
||||
// format argument) and fail in FmtLoc's consteval constructor.
|
||||
inline void emit(Level level, std::string_view module,
|
||||
std::string_view message,
|
||||
const std::source_location& location)
|
||||
@@ -171,10 +294,45 @@ namespace Void::Log
|
||||
if (!::Void::Log::enabled(level, module)) {
|
||||
return;
|
||||
}
|
||||
std::shared_lock lock{s.mutex};
|
||||
if (s.sink) {
|
||||
s.sink(level, module, message, location);
|
||||
|
||||
std::shared_ptr<SinkRegistration> reg;
|
||||
bool reentrant = false;
|
||||
{
|
||||
std::shared_lock lock{s.mutex};
|
||||
reg = s.registration;
|
||||
if (!reg || reg->detached.load(std::memory_order_acquire) ||
|
||||
!reg->sink) {
|
||||
return;
|
||||
}
|
||||
const auto& active = active_registrations_tls();
|
||||
if (active.size() >= kMaxNestedFacadeSinks) {
|
||||
reentrant = true;
|
||||
} else {
|
||||
for (const auto* entry : active) {
|
||||
if (entry == reg.get()) {
|
||||
reentrant = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!reentrant) {
|
||||
reg->active_calls.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
}
|
||||
|
||||
if (reentrant) {
|
||||
s.reentrant_dropped.fetch_add(1, std::memory_order_relaxed);
|
||||
if (const auto eh =
|
||||
s.emergency_handler.load(std::memory_order_acquire);
|
||||
eh != nullptr) {
|
||||
eh(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ActiveRegistrationGuard guard{
|
||||
std::move(reg), active_registrations_tls()};
|
||||
guard.reg->sink(level, module, message, location);
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
@@ -186,9 +344,6 @@ namespace Void::Log
|
||||
Detail::emit(level, module, message, location);
|
||||
}
|
||||
|
||||
/// Leveled, lazily-formatted emission: arguments are formatted only
|
||||
/// after the level/sink gate passes. The call-site source location is
|
||||
/// captured transparently via FmtLoc.
|
||||
template <typename... Args>
|
||||
void log(Level level, std::string_view module,
|
||||
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
|
||||
@@ -243,4 +398,4 @@ namespace Void::Log
|
||||
log(Level::Fatal, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
} // namespace Void::Log
|
||||
} // namespace Void::Log
|
||||
+244
-263
@@ -1,18 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Void/Log/Field.hpp"
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <semaphore>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <source_location>
|
||||
#include <span>
|
||||
#include <string>
|
||||
@@ -23,104 +30,159 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// 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, lock-free gate)
|
||||
/// - Entry construction: timestamp, thread_id, scope snapshot
|
||||
/// - 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.
|
||||
///
|
||||
/// ## 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
|
||||
/// Immediate mode and by the default `on_flush` implementation.
|
||||
/// 2. Optionally override `on_flush(std::span<const Entry>)` — useful
|
||||
/// for sinks that benefit from batch writes (e.g. file loggers).
|
||||
/// 3. **Call `flush()` in your own destructor** before the base
|
||||
/// 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 (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
|
||||
/// class StdoutLogger final : public Void::Logging::Logger
|
||||
/// {
|
||||
/// public:
|
||||
/// ~StdoutLogger() noexcept override { flush(); }
|
||||
/// protected:
|
||||
/// void write(const Void::Logging::Entry& e) override
|
||||
/// {
|
||||
/// std::println("[{}] {}", e.level, e.message);
|
||||
/// }
|
||||
/// };
|
||||
/// @endcode
|
||||
enum class LogErrorCode : std::int32_t {
|
||||
invalid_argument = 1,
|
||||
queue_full = 2,
|
||||
entry_too_large = 3,
|
||||
closed = 4,
|
||||
cancelled = 5,
|
||||
timeout = 6,
|
||||
would_deadlock = 7,
|
||||
quarantined = 8,
|
||||
unsupported_capability = 9,
|
||||
io_error = 10,
|
||||
cycle_detected = 11
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_log_error(LogErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case LogErrorCode::invalid_argument:
|
||||
case LogErrorCode::entry_too_large:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case LogErrorCode::queue_full:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case LogErrorCode::closed:
|
||||
case LogErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case LogErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case LogErrorCode::would_deadlock:
|
||||
case LogErrorCode::cycle_detected:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case LogErrorCode::quarantined:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case LogErrorCode::unsupported_capability:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case LogErrorCode::io_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
}
|
||||
return Error{kind,
|
||||
std::move(message),
|
||||
ErrorCode{Void::Result::kLogErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct DeliveryLimits {
|
||||
std::size_t entries = 4096;
|
||||
std::size_t owned_bytes = 8ULL * 1024ULL * 1024ULL;
|
||||
std::size_t max_entry_bytes = 64ULL * 1024ULL;
|
||||
std::size_t batch_entries = 128;
|
||||
std::size_t batch_bytes = 256ULL * 1024ULL;
|
||||
std::size_t max_fields = 32;
|
||||
std::size_t max_scopes = 16;
|
||||
std::size_t max_field_key_bytes = 256;
|
||||
std::size_t max_field_value_bytes = 2048;
|
||||
std::size_t max_format_scratch_bytes = 1024ULL * 1024ULL;
|
||||
bool truncate_oversize = false;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const;
|
||||
};
|
||||
|
||||
enum class FailurePolicy : std::uint8_t {
|
||||
Quarantine = 0,
|
||||
Continue
|
||||
};
|
||||
|
||||
struct LoggerOptions {
|
||||
Mode mode = Mode::Async;
|
||||
OverflowPolicy policy = OverflowPolicy::DropNewest;
|
||||
DeliveryLimits limits{};
|
||||
FailurePolicy failure_policy = FailurePolicy::Quarantine;
|
||||
bool suppress_reentrancy = true;
|
||||
const Void::Time::MonotonicClock* clock =
|
||||
&Void::Time::SystemMonotonicClock::instance();
|
||||
};
|
||||
|
||||
enum class SubmitState : std::uint8_t {
|
||||
Accepted = 0,
|
||||
Filtered,
|
||||
Dropped,
|
||||
Closed
|
||||
};
|
||||
|
||||
using Ticket = std::uint64_t;
|
||||
|
||||
struct SubmitReceipt {
|
||||
SubmitState state{SubmitState::Dropped};
|
||||
std::optional<Ticket> ticket{};
|
||||
bool truncated{false};
|
||||
};
|
||||
|
||||
enum class FlushDurability : std::uint8_t {
|
||||
BufferFlush = 0,
|
||||
SyncFiles
|
||||
};
|
||||
|
||||
struct FlushOptions {
|
||||
FlushDurability durability = FlushDurability::BufferFlush;
|
||||
Void::Async::OperationOptions async{};
|
||||
};
|
||||
|
||||
struct CloseOptions {
|
||||
bool drop_pending = false;
|
||||
Void::Async::OperationOptions async{};
|
||||
};
|
||||
|
||||
struct FlushReport {
|
||||
std::uint64_t delivered{0};
|
||||
std::uint64_t dropped{0};
|
||||
std::uint64_t failed{0};
|
||||
Ticket watermark{0};
|
||||
bool timed_out{false};
|
||||
bool cancelled{false};
|
||||
};
|
||||
|
||||
struct LoggerStats {
|
||||
std::size_t queued_entries{0};
|
||||
std::size_t queued_bytes{0};
|
||||
std::size_t in_flight_entries{0};
|
||||
std::size_t in_flight_bytes{0};
|
||||
std::uint64_t admitted{0};
|
||||
std::uint64_t delivered{0};
|
||||
std::uint64_t dropped{0};
|
||||
std::uint64_t failed{0};
|
||||
std::uint64_t reentrant_dropped{0};
|
||||
Ticket completed_watermark{0};
|
||||
bool quarantined{false};
|
||||
bool closed{false};
|
||||
};
|
||||
|
||||
/// Abstract base class for all Void loggers with bounded entry/byte
|
||||
/// admission, ticket completion watermarks, failure quarantine, and flush
|
||||
/// durability controls.
|
||||
class Logger
|
||||
{
|
||||
public:
|
||||
|
||||
// =========================================================================
|
||||
// ScopedContext — RAII, per-thread, named scope push/pop
|
||||
//
|
||||
// Pushing a scope has two effects:
|
||||
// 1. The scope name is appended to this thread's scope stack so
|
||||
// all subsequent entries carry it in Entry::scopes.
|
||||
// 2. A ScopeEnter entry is emitted at the level supplied to
|
||||
// push_scope() (or Trace by default).
|
||||
// 3. On destruction a ScopeExit entry is emitted at the same
|
||||
// level.
|
||||
//
|
||||
// Usage:
|
||||
// {
|
||||
// auto s = logger.push_scope("network"); // →
|
||||
// ScopeEnter logger.info("connecting …"); //
|
||||
// scopes={"network"}
|
||||
// {
|
||||
// auto t = logger.push_scope("tls"); // →
|
||||
// ScopeEnter logger.debug("handshake"); //
|
||||
// scopes={"network","tls"}
|
||||
// } // → ScopeExit
|
||||
// "tls"
|
||||
// } // → ScopeExit
|
||||
// "network"
|
||||
// =========================================================================
|
||||
class ScopedContext
|
||||
{
|
||||
public:
|
||||
@@ -131,8 +193,6 @@ namespace Void::Logging
|
||||
std::source_location loc) noexcept;
|
||||
~ScopedContext() noexcept;
|
||||
|
||||
// Non-copyable; move transfers ownership so the moved-from
|
||||
// guard does not emit a spurious ScopeExit on destruction.
|
||||
ScopedContext(const ScopedContext&) = delete;
|
||||
ScopedContext& operator=(const ScopedContext&) = delete;
|
||||
ScopedContext(ScopedContext&&) noexcept;
|
||||
@@ -146,23 +206,6 @@ namespace Void::Logging
|
||||
bool m_active{true};
|
||||
};
|
||||
|
||||
// =========================================================================
|
||||
// Preset — a partially-applied logger
|
||||
//
|
||||
// A Preset captures a reference to the owning Logger together with
|
||||
// a fixed Level (and optional message prefix). Call it with just
|
||||
// the message / format args; the level is already baked in.
|
||||
//
|
||||
// Lifetime: a Preset must not outlive the Logger it was made from.
|
||||
//
|
||||
// Usage:
|
||||
// auto net_err = logger.make_preset(Level::Error, "[network] ");
|
||||
// net_err("connection refused"); // same as:
|
||||
// // logger.error("[network] connection refused");
|
||||
//
|
||||
// auto dbg = logger.make_preset(Level::Debug);
|
||||
// dbg("value = {}", 42);
|
||||
// =========================================================================
|
||||
class Preset
|
||||
{
|
||||
public:
|
||||
@@ -174,16 +217,11 @@ namespace Void::Logging
|
||||
{
|
||||
}
|
||||
|
||||
// Non-owning; copyable so presets can be stored / passed
|
||||
// around.
|
||||
Preset(const Preset&) = default;
|
||||
Preset& operator=(const Preset&) = default;
|
||||
Preset(Preset&&) = default;
|
||||
Preset& operator=(Preset&&) = default;
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Plain string overload
|
||||
// -----------------------------------------------------------------
|
||||
void operator()(std::string_view message,
|
||||
std::source_location loc =
|
||||
std::source_location::current()) const
|
||||
@@ -197,22 +235,6 @@ namespace Void::Logging
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FormatWithLocation helper
|
||||
//
|
||||
// std::source_location cannot share a parameter list with
|
||||
// a variadic pack, so this wrapper type captures both the
|
||||
// format string and the caller's source location in its
|
||||
// constructor.
|
||||
//
|
||||
// std::type_identity_t<Args>... prevents Args from being
|
||||
// deduced from the wrapper; they are deduced solely from
|
||||
// the trailing pack.
|
||||
//
|
||||
// Usage — source location is captured transparently:
|
||||
// logger.info("player {} scored {} points", name,
|
||||
// score);
|
||||
// =========================================================================
|
||||
template <typename... Args> struct FormatWithLocation {
|
||||
std::format_string<Args...> fmt;
|
||||
std::source_location location;
|
||||
@@ -227,12 +249,6 @@ namespace Void::Logging
|
||||
}
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Formatted overload
|
||||
// Uses the same FormatWithLocation trick as Logger itself
|
||||
// so the call-site source location is captured
|
||||
// transparently.
|
||||
// -----------------------------------------------------------------
|
||||
template <typename... Args>
|
||||
void operator()(
|
||||
FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
@@ -249,7 +265,6 @@ namespace Void::Logging
|
||||
m_owner->log(m_level, msg, fwl.location);
|
||||
}
|
||||
|
||||
// Accessors
|
||||
[[nodiscard]] Level level() const noexcept
|
||||
{
|
||||
return m_level;
|
||||
@@ -273,18 +288,13 @@ namespace Void::Logging
|
||||
// =========================================================================
|
||||
// Lifetime
|
||||
// =========================================================================
|
||||
/// @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;
|
||||
|
||||
/// Stops and joins the worker thread (Async). Does NOT flush
|
||||
/// remaining entries — see class-level note.
|
||||
explicit Logger(LoggerOptions options);
|
||||
|
||||
virtual ~Logger() noexcept;
|
||||
|
||||
Logger(const Logger&) = delete;
|
||||
@@ -293,103 +303,75 @@ namespace Void::Logging
|
||||
Logger& operator=(Logger&&) = delete;
|
||||
|
||||
// =========================================================================
|
||||
// Configuration (all setters are thread-safe)
|
||||
// Configuration
|
||||
// =========================================================================
|
||||
|
||||
/// Set the minimum level. Entries below this level are dropped.
|
||||
/// Level::Disabled suppresses all output.
|
||||
void set_level(Level level) noexcept;
|
||||
[[nodiscard]] Level level() const noexcept;
|
||||
|
||||
/// 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; 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;
|
||||
[[nodiscard]] const DeliveryLimits& delivery_limits() const noexcept
|
||||
{
|
||||
return m_options.limits;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Flush
|
||||
// P2 Checked Submission, Flush, Close, and Quarantine Controls
|
||||
// =========================================================================
|
||||
[[nodiscard]] Void::Result::Result<SubmitReceipt>
|
||||
try_submit(Entry entry,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FlushReport>
|
||||
flush_through(Ticket target = 0, FlushOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FlushReport>
|
||||
close(CloseOptions options = {});
|
||||
|
||||
void request_close() noexcept;
|
||||
|
||||
/// 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
|
||||
// =========================================================================
|
||||
[[nodiscard]] LoggerStats stats() const;
|
||||
[[nodiscard]] bool is_quarantined() const noexcept;
|
||||
[[nodiscard]] std::string last_error_summary() const;
|
||||
void reset_quarantine() noexcept;
|
||||
|
||||
/// Push a named scope onto this thread's scope stack AND emit a
|
||||
/// ScopeEnter entry at the given level. The returned ScopedContext
|
||||
/// emits a ScopeExit entry and pops the stack when it goes out of
|
||||
/// scope.
|
||||
///
|
||||
/// @param name Human-readable scope label.
|
||||
/// @param level Level used for the ScopeEnter/ScopeExit entries.
|
||||
/// Defaults to Trace so scope boundaries are usually
|
||||
/// invisible in production builds.
|
||||
/// @return A [[nodiscard]] RAII guard — assign it to a named
|
||||
/// local; do NOT discard (it would immediately exit).
|
||||
// =========================================================================
|
||||
// Scoped context & Presets
|
||||
// =========================================================================
|
||||
[[nodiscard]] ScopedContext
|
||||
push_scope(std::string name,
|
||||
Level level = Level::Trace,
|
||||
std::source_location loc =
|
||||
std::source_location::current()) noexcept;
|
||||
|
||||
/// Emit a named scope open/close pair as explicit log entries
|
||||
/// WITHOUT modifying the thread-local scope stack. Useful when you
|
||||
/// want scope boundaries in the log but don't want child entries
|
||||
/// annotated.
|
||||
///
|
||||
/// Both ScopeEnter and ScopeExit are emitted immediately (Immediate
|
||||
/// mode) or buffered together (Buffered mode).
|
||||
void scope(
|
||||
std::string_view name,
|
||||
Level level = Level::Trace,
|
||||
std::source_location loc = std::source_location::current());
|
||||
|
||||
/// Read-only view of the current thread's scope stack.
|
||||
/// Ordered outermost → innermost.
|
||||
[[nodiscard]] static std::span<const std::string>
|
||||
current_scopes() noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Preset factory
|
||||
// =========================================================================
|
||||
|
||||
/// Create a Preset that fixes the level and an optional message
|
||||
/// prefix. The Preset holds a non-owning reference to *this — do
|
||||
/// not outlive the logger.
|
||||
[[nodiscard]] Preset make_preset(Level level,
|
||||
std::string prefix = {}) noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Core (non-template) logging — canonical entry points
|
||||
// Core & Formatted Logging (legacy compatibility adapters)
|
||||
// =========================================================================
|
||||
inline void log(
|
||||
Level level, std::string_view message,
|
||||
std::source_location location = std::source_location::current())
|
||||
{
|
||||
// Early level check outside the lock to avoid allocations on
|
||||
// the hot path.
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
if (level < m_level) {
|
||||
return;
|
||||
}
|
||||
if (level < m_level.load(std::memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto fields = current_fields();
|
||||
Entry entry{
|
||||
.kind = Kind::Message,
|
||||
@@ -398,7 +380,6 @@ namespace Void::Logging
|
||||
.timestamp = std::chrono::system_clock::now(),
|
||||
.location = location,
|
||||
.thread_id = std::this_thread::get_id(),
|
||||
// Snapshot here through the existing DLL function boundary.
|
||||
.scopes = [] {
|
||||
const auto scopes = Logger::current_scopes();
|
||||
return std::vector<std::string>(
|
||||
@@ -406,14 +387,9 @@ namespace Void::Logging
|
||||
}(),
|
||||
.fields = {fields.begin(), fields.end()},
|
||||
};
|
||||
|
||||
submit(std::move(entry));
|
||||
(void)try_submit(std::move(entry));
|
||||
}
|
||||
|
||||
/// 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(
|
||||
@@ -435,10 +411,6 @@ namespace Void::Logging
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
|
||||
// =========================================================================
|
||||
// Formatted logging
|
||||
// =========================================================================
|
||||
|
||||
template <typename... Args>
|
||||
void log(Level level,
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...>
|
||||
@@ -498,81 +470,90 @@ namespace Void::Logging
|
||||
log(Level::Fatal, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void> sync_files();
|
||||
|
||||
protected:
|
||||
|
||||
// =========================================================================
|
||||
// Extension points
|
||||
//
|
||||
// Both methods are called OUTSIDE the internal mutex. Derived
|
||||
// classes may block, acquire their own locks, or call other Logger
|
||||
// methods without risk of deadlock.
|
||||
// =========================================================================
|
||||
|
||||
/// Deliver one entry to the sink.
|
||||
/// Called once per entry in Immediate mode, and by the default
|
||||
/// on_flush() for each entry in the batch.
|
||||
virtual void write(const Entry& entry) = 0;
|
||||
|
||||
/// Deliver a batch of buffered entries to the sink.
|
||||
/// The default implementation calls write() for each entry in
|
||||
/// order. Override to enable batched / vectored I/O.
|
||||
virtual void on_flush(std::span<const Entry> entries);
|
||||
|
||||
private:
|
||||
|
||||
/// Build an Entry and route it to the queue, write() or the
|
||||
/// buffer depending on the active mode.
|
||||
void submit(Entry entry);
|
||||
enum class TerminalOutcome : std::uint8_t {
|
||||
Delivered = 0,
|
||||
Dropped,
|
||||
Failed
|
||||
};
|
||||
|
||||
/// Async path: bounded enqueue honoring the overflow policy.
|
||||
void async_submit(Entry entry);
|
||||
struct QueuedItem {
|
||||
Ticket ticket{0};
|
||||
std::size_t bytes{0};
|
||||
Entry entry;
|
||||
};
|
||||
|
||||
[[nodiscard]] static std::size_t
|
||||
estimate_entry_bytes(const Entry& entry) noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
prepare_entry(Entry& entry) const;
|
||||
|
||||
/// 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 mark_terminal_locked(Ticket t, TerminalOutcome outcome);
|
||||
void advance_watermark_locked();
|
||||
void deliver_batch_unlocked(
|
||||
std::vector<QueuedItem>& items,
|
||||
bool stopping,
|
||||
std::size_t total_bytes);
|
||||
void emit_scope_boundary(Kind kind,
|
||||
std::string_view name,
|
||||
Level level,
|
||||
std::source_location loc);
|
||||
|
||||
[[nodiscard]] bool is_active_logger_on_thread() const noexcept;
|
||||
|
||||
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; // Buffered mode only
|
||||
LoggerOptions m_options;
|
||||
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};
|
||||
mutable std::mutex m_mutex;
|
||||
std::condition_variable m_work_cv;
|
||||
std::condition_variable m_space_cv;
|
||||
std::condition_variable m_done_cv;
|
||||
|
||||
std::deque<QueuedItem> m_queue;
|
||||
std::size_t m_queued_entries{0};
|
||||
std::size_t m_queued_bytes{0};
|
||||
std::size_t m_in_flight_entries{0};
|
||||
std::size_t m_in_flight_bytes{0};
|
||||
|
||||
Ticket m_next_ticket{0};
|
||||
Ticket m_completed_watermark{0};
|
||||
std::set<std::pair<Ticket, TerminalOutcome>> m_pending_terminals;
|
||||
|
||||
std::uint64_t m_admitted_count{0};
|
||||
std::uint64_t m_delivered_count{0};
|
||||
std::uint64_t m_dropped_count{0};
|
||||
std::uint64_t m_failed_count{0};
|
||||
std::uint64_t m_wm_delivered{0};
|
||||
std::uint64_t m_wm_dropped{0};
|
||||
std::uint64_t m_wm_failed{0};
|
||||
std::atomic<std::uint64_t> m_reentrant_dropped{0};
|
||||
|
||||
bool m_mode_changing{false};
|
||||
bool m_stop_admission{false};
|
||||
bool m_closed{false};
|
||||
std::atomic<bool> m_stop_worker{false};
|
||||
std::atomic<bool> m_quarantined{false};
|
||||
std::string m_last_error;
|
||||
|
||||
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};
|
||||
std::atomic<std::thread::id> m_worker_id{};
|
||||
|
||||
/// Per-thread scope stack. ScopedContext pushes/pops into this.
|
||||
static thread_local std::vector<std::string> s_scope_stack;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
@@ -13,21 +13,25 @@
|
||||
|
||||
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;
|
||||
bool create_directories = true;
|
||||
|
||||
[[nodiscard]] static constexpr RotatingFileOptions
|
||||
roadmap_defaults() noexcept
|
||||
{
|
||||
return RotatingFileOptions{
|
||||
.max_bytes = 16ULL * 1024ULL * 1024ULL,
|
||||
.max_files = 5,
|
||||
.mode = Mode::Async,
|
||||
.capacity = 4096,
|
||||
.policy = OverflowPolicy::DropNewest,
|
||||
.create_directories = false};
|
||||
}
|
||||
};
|
||||
|
||||
class RotatingFileLogger final : public Logger
|
||||
@@ -46,17 +50,18 @@ namespace Void::Logging
|
||||
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]] Void::Result::Result<void> reopen();
|
||||
[[nodiscard]] Void::Result::Result<void> sync_files() override;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
@@ -76,4 +81,4 @@ namespace Void::Logging
|
||||
std::shared_ptr<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
+79
-13
@@ -9,12 +9,17 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Discards everything. Useful as a placeholder or for benchmarks.
|
||||
inline constexpr std::size_t kDefaultMaxFanoutChildren = 8;
|
||||
|
||||
class NullLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
|
||||
explicit NullLogger(Mode mode = Mode::Immediate) : Logger(mode) {}
|
||||
explicit NullLogger(LoggerOptions options)
|
||||
: Logger(std::move(options))
|
||||
{
|
||||
}
|
||||
|
||||
~NullLogger() noexcept override { flush(); }
|
||||
|
||||
@@ -23,8 +28,6 @@ namespace Void::Logging
|
||||
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:
|
||||
@@ -41,6 +44,11 @@ namespace Void::Logging
|
||||
{
|
||||
}
|
||||
|
||||
explicit CallbackLogger(Callback callback, LoggerOptions options)
|
||||
: Logger(std::move(options)), m_callback(std::move(callback))
|
||||
{
|
||||
}
|
||||
|
||||
~CallbackLogger() noexcept override { flush(); }
|
||||
|
||||
protected:
|
||||
@@ -57,10 +65,6 @@ namespace Void::Logging
|
||||
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:
|
||||
@@ -72,15 +76,41 @@ namespace Void::Logging
|
||||
{
|
||||
}
|
||||
|
||||
explicit MultiLogger(
|
||||
std::vector<std::shared_ptr<Logger>> children,
|
||||
LoggerOptions options)
|
||||
: Logger(std::move(options)), 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));
|
||||
(void)try_add(std::move(child));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
try_add(std::shared_ptr<Logger> child,
|
||||
std::size_t max_children = kDefaultMaxFanoutChildren)
|
||||
{
|
||||
if (!child) {
|
||||
return Void::Result::fail(make_log_error(
|
||||
LogErrorCode::invalid_argument,
|
||||
"MultiLogger::try_add: null child"));
|
||||
}
|
||||
if (m_children.size() >= max_children) {
|
||||
return Void::Result::fail(make_log_error(
|
||||
LogErrorCode::queue_full,
|
||||
"MultiLogger child fan-out limit exceeded"));
|
||||
}
|
||||
if (reaches_self(*child)) {
|
||||
return Void::Result::fail(make_log_error(
|
||||
LogErrorCode::cycle_detected,
|
||||
"MultiLogger fan-out cycle detected"));
|
||||
}
|
||||
m_children.push_back(std::move(child));
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t child_count() const noexcept
|
||||
@@ -88,7 +118,6 @@ namespace Void::Logging
|
||||
return m_children.size();
|
||||
}
|
||||
|
||||
/// Flush own pending entries, then every child.
|
||||
void flush() override
|
||||
{
|
||||
Logger::flush();
|
||||
@@ -97,6 +126,26 @@ namespace Void::Logging
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> sync_files() override
|
||||
{
|
||||
if (m_children.empty()) {
|
||||
return Logger::sync_files();
|
||||
}
|
||||
bool any_synced = false;
|
||||
for (const auto& child : m_children) {
|
||||
auto res = child->sync_files();
|
||||
if (res) {
|
||||
any_synced = true;
|
||||
} else if (res.error().code().value !=
|
||||
static_cast<std::int32_t>(
|
||||
LogErrorCode::unsupported_capability)) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return any_synced ? Void::Result::Result<void>{}
|
||||
: Logger::sync_files();
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
void write(const Entry& entry) override
|
||||
@@ -108,7 +157,24 @@ namespace Void::Logging
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool reaches_self(const Logger& candidate) const
|
||||
{
|
||||
if (&candidate == this) {
|
||||
return true;
|
||||
}
|
||||
const auto* nested = dynamic_cast<const MultiLogger*>(&candidate);
|
||||
if (nested == nullptr) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& grandchild : nested->m_children) {
|
||||
if (grandchild && reaches_self(*grandchild)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<Logger>> m_children;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
Reference in new issue
Block a user