diff --git a/include/Void/Log/Detail/RollingFile.hpp b/include/Void/Log/Detail/RollingFile.hpp index 40deb65..8afac02 100644 --- a/include/Void/Log/Detail/RollingFile.hpp +++ b/include/Void/Log/Detail/RollingFile.hpp @@ -1,5 +1,7 @@ #pragma once +#include + #include #include #include @@ -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 `-` — 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//`). - /// 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 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 m_rotationTime; }; -} // namespace Void::Logging::Detail +} // namespace Void::Logging::Detail \ No newline at end of file diff --git a/include/Void/Log/Entry.hpp b/include/Void/Log/Entry.hpp index 5c63276..b608d1d 100644 --- a/include/Void/Log/Entry.hpp +++ b/include/Void/Log/Entry.hpp @@ -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 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> fields{}; + + /// True when explicit oversize-truncation policy clipped message, + /// fields, scopes, or formatted payload. + bool truncated{false}; }; -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/include/Void/Log/FileLogger.hpp b/include/Void/Log/FileLogger.hpp index 7f7bc94..9e8f569 100644 --- a/include/Void/Log/FileLogger.hpp +++ b/include/Void/Log/FileLogger.hpp @@ -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, 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{"FileLogger: cannot open ''"}}`. [[nodiscard]] static Void::Result:: Result, 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, Void::Result::Error> + open(const std::filesystem::path& path, + LoggerOptions options); + void set_formatter(std::shared_ptr formatter) { m_formatter = std::move(formatter); } + [[nodiscard]] Void::Result::Result reopen(); + [[nodiscard]] Void::Result::Result 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 m_formatter; }; -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/include/Void/Log/Formatter.hpp b/include/Void/Log/Formatter.hpp index 67e54fe..d189f1b 100644 --- a/include/Void/Log/Formatter.hpp +++ b/include/Void/Log/Formatter.hpp @@ -1,8 +1,10 @@ #pragma once +#include #include #include +#include #include #include #include @@ -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_colors; std::unordered_map 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 - 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 m_segments; - std::unordered_map> - 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 include; - std::vector exclude; + std::vector include{}; + std::vector exclude{}; + std::vector 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 + 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 m_segments; + std::unordered_map> + 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 + 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& scopes); } // namespace FormatDetail -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/include/Void/Log/Log.hpp b/include/Void/Log/Log.hpp index 01dd7a3..4eb36d2 100644 --- a/include/Void/Log/Log.hpp +++ b/include/Void/Log/Log.hpp @@ -1,8 +1,12 @@ #pragma once #include #include +#include +#include +#include #include #include +#include #include #include #include @@ -11,6 +15,7 @@ #include #include #include +#include // ── 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; + 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... keeps Args non-deduced here, so they - // are deduced solely from the trailing argument pack. template struct FmtLoc { std::format_string fmt; std::source_location location; @@ -74,36 +68,176 @@ namespace Void::Log } }; + struct SinkRegistration { + RegistrationId id{0}; + Sink sink{}; + std::shared_ptr owner{}; + std::atomic detached{false}; + std::atomic 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 has_sink{false}; std::atomic min_level{Level::Trace}; std::atomic has_module_levels{false}; + std::atomic reentrant_dropped{0}; + std::atomic emergency_handler{nullptr}; - // Slow path. - Sink sink; + // Slow path (registration is immutable after creation; + // invoked and destroyed strictly outside `mutex`). + std::shared_ptr registration{}; + RegistrationId next_id{0}; + std::unordered_map> known; std::unordered_map 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& active_registrations_tls() noexcept; + + struct ActiveRegistrationGuard { + std::shared_ptr reg; + std::vector& stack; + + ActiveRegistrationGuard(std::shared_ptr r, + std::vector& 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 owner = {}) { auto& s = Detail::state(); - std::unique_lock lock{s.mutex}; - s.sink = std::move(sink); - s.has_sink.store(static_cast(s.sink), std::memory_order_release); + std::shared_ptr prev; + RegistrationId id = 0; + + if (sink) { + auto next = std::make_shared(); + 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 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 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 void log(Level level, std::string_view module, Detail::FmtLoc...> fmt, Args&&... args) @@ -243,4 +398,4 @@ namespace Void::Log log(Level::Fatal, module, fmt, std::forward(args)...); } -} // namespace Void::Log +} // namespace Void::Log \ No newline at end of file diff --git a/include/Void/Log/Logger.hpp b/include/Void/Log/Logger.hpp index 7a0db44..918bd7b 100644 --- a/include/Void/Log/Logger.hpp +++ b/include/Void/Log/Logger.hpp @@ -1,18 +1,25 @@ #pragma once #include "Void/Log/Field.hpp" -#include +#include +#include +#include #include #include +#include #include +#include #include +#include #include #include +#include #include #include #include -#include +#include +#include #include #include #include @@ -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)` — 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(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 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{}; + 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... 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 struct FormatWithLocation { std::format_string 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 void operator()( FormatWithLocation...> 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 + try_submit(Entry entry, + Void::Async::OperationOptions options = {}); + + [[nodiscard]] Void::Result::Result + flush_through(Ticket target = 0, FlushOptions options = {}); + + [[nodiscard]] Void::Result::Result + 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 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( @@ -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 void log(Level level, Preset::FormatWithLocation...> @@ -498,81 +470,90 @@ namespace Void::Logging log(Level::Fatal, fwl, std::forward(args)...); } + [[nodiscard]] virtual Void::Result::Result 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 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 + 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& 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 m_level{Level::Trace}; std::atomic m_mode; - std::size_t m_async_capacity; - OverflowPolicy m_policy; - - mutable std::mutex m_mutex; - std::vector m_buffer; // Buffered mode only + LoggerOptions m_options; std::size_t m_buffer_capacity; - // ── Async machinery ────────────────────────────────────────── - Void::Async::MpscQueue 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 m_sleeping{false}; - std::atomic 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 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> 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 m_reentrant_dropped{0}; + + bool m_mode_changing{false}; + bool m_stop_admission{false}; + bool m_closed{false}; + std::atomic m_stop_worker{false}; + std::atomic m_quarantined{false}; + std::string m_last_error; + std::atomic m_worker_started{false}; std::once_flag m_worker_once; std::thread m_worker; - std::atomic m_submitted{0}; - std::atomic m_completed{0}; + std::atomic m_worker_id{}; - /// Per-thread scope stack. ScopedContext pushes/pops into this. static thread_local std::vector s_scope_stack; }; -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/include/Void/Log/RotatingFileLogger.hpp b/include/Void/Log/RotatingFileLogger.hpp index 01a7fed..b2774a0 100644 --- a/include/Void/Log/RotatingFileLogger.hpp +++ b/include/Void/Log/RotatingFileLogger.hpp @@ -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, Void::Result::Error> open(const std::filesystem::path& path, Options options = {}); - /// Install a formatter. Call before logging starts. void set_formatter(std::shared_ptr formatter) { m_formatter = std::move(formatter); } + [[nodiscard]] Void::Result::Result reopen(); + [[nodiscard]] Void::Result::Result sync_files() override; + [[nodiscard]] const std::filesystem::path& path() const noexcept { return m_path; @@ -76,4 +81,4 @@ namespace Void::Logging std::shared_ptr m_formatter; }; -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/include/Void/Log/Sinks.hpp b/include/Void/Log/Sinks.hpp index 9aaba9f..c43c365 100644 --- a/include/Void/Log/Sinks.hpp +++ b/include/Void/Log/Sinks.hpp @@ -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> 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 child) { - if (child) { - m_children.push_back(std::move(child)); + (void)try_add(std::move(child)); + } + + [[nodiscard]] Void::Result::Result + try_add(std::shared_ptr 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 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( + LogErrorCode::unsupported_capability)) { + return res; + } + } + return any_synced ? Void::Result::Result{} + : 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(&candidate); + if (nested == nullptr) { + return false; + } + for (const auto& grandchild : nested->m_children) { + if (grandchild && reaches_self(*grandchild)) { + return true; + } + } + return false; + } + std::vector> m_children; }; -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/src/Log/FileLogger.cpp b/src/Log/FileLogger.cpp index 5389234..f177372 100644 --- a/src/Log/FileLogger.cpp +++ b/src/Log/FileLogger.cpp @@ -1,7 +1,15 @@ #include #include +#ifndef _WIN32 +#include +#include +#include +#include +#endif + #include +#include #include namespace Void::Logging @@ -20,6 +28,18 @@ namespace Void::Logging Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string()); } + FileLogger::FileLogger(const std::filesystem::path& path, + LoggerOptions options) + : Logger(std::move(options)), m_path(path), m_file(path, std::ios::app) + { + if (!m_file.is_open()) { + Void::Log::warn("Logging", "FileLogger: cannot open '{}'", path.string()); + throw std::runtime_error( + std::format("FileLogger: cannot open '{}'", path.string())); + } + Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string()); + } + Void::Result::Result, Void::Result::Error> FileLogger::open(const std::filesystem::path& path, Mode mode, @@ -29,7 +49,21 @@ namespace Void::Logging return Void::Result::ok( std::make_unique(path, mode, capacity)); } catch (const std::exception& e) { - return Void::Result::fail(std::string{e.what()}); + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, std::string{e.what()})); + } + } + + Void::Result::Result, Void::Result::Error> + FileLogger::open(const std::filesystem::path& path, + LoggerOptions options) + { + try { + return Void::Result::ok( + std::make_unique(path, std::move(options))); + } catch (const std::exception& e) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, std::string{e.what()})); } } @@ -37,13 +71,70 @@ namespace Void::Logging { flush(); Void::Log::debug("Logging", "FileLogger: closed '{}'", - m_path.string()); + m_path.string()); + } + + Void::Result::Result FileLogger::reopen() + { + flush(); + m_file.close(); + m_file.clear(); + m_file.open(m_path, std::ios::app); + if (!m_file.is_open()) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("FileLogger::reopen failed for '{}'", + m_path.string()))); + } + return {}; + } + + Void::Result::Result FileLogger::sync_files() + { + flush(); + if (is_quarantined()) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, last_error_summary())); + } + m_file.flush(); + if (!m_file.good()) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("FileLogger::sync_files flush failure for '{}'", + m_path.string()))); + } +#ifndef _WIN32 + const int fd = ::open(m_path.c_str(), O_RDONLY); + if (fd < 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("FileLogger::sync_files open('{}') failed: {}", + m_path.string(), std::strerror(errno)))); + } + int rc = 0; + do { + rc = ::fsync(fd); + } while (rc < 0 && errno == EINTR); + const int saved_err = errno; + ::close(fd); + if (rc < 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("FileLogger::sync_files fsync('{}') failed: {}", + m_path.string(), std::strerror(saved_err)))); + } +#endif + return {}; } void FileLogger::write(const Entry& entry) { append(entry); m_file.flush(); + if (!m_file.good()) { + throw std::runtime_error(std::format( + "FileLogger: flush failure on '{}'", m_path.string())); + } } void FileLogger::on_flush(std::span entries) @@ -52,17 +143,37 @@ namespace Void::Logging append(e); } m_file.flush(); + if (!m_file.good()) { + throw std::runtime_error(std::format( + "FileLogger: batch flush failure on '{}'", m_path.string())); + } } void FileLogger::append(const Entry& entry) { - if (m_formatter) { - m_file << m_formatter->format(entry) << '\n'; + if (!m_file.is_open()) { + throw std::runtime_error(std::format( + "FileLogger: file not open for '{}'", m_path.string())); } - else { - m_file << std::format( - "[{}] {}\n", to_string(entry.level), entry.message); + std::string line; + if (m_formatter) { + auto bounded = format_bounded( + *m_formatter, + entry, + delivery_limits().max_format_scratch_bytes, + delivery_limits().truncate_oversize); + if (!bounded) { + throw std::runtime_error(bounded.error().message()); + } + line = std::move(*bounded); + } else { + line = std::format("[{}] {}", to_string(entry.level), entry.message); + } + m_file << line << '\n'; + if (!m_file.good()) { + throw std::runtime_error(std::format( + "FileLogger: write failure on '{}'", m_path.string())); } } -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/src/Log/Formatter.cpp b/src/Log/Formatter.cpp index e48d9e3..0cf04f9 100644 --- a/src/Log/Formatter.cpp +++ b/src/Log/Formatter.cpp @@ -1,9 +1,11 @@ #include +#include #include #include #include #include +#include #include #include #include @@ -12,8 +14,6 @@ namespace Void::Logging { - // ── colour ──────────────────────────────────────────────────────────── - AnsiColor parse_color(std::string_view name) noexcept { struct Pair { @@ -43,7 +43,6 @@ namespace Void::Logging return c; } } - // "dim"/"gray" aliases if (name == "dim" || name == "gray" || name == "grey") { return AnsiColor::BrightBlack; } @@ -53,40 +52,23 @@ namespace Void::Logging std::string_view ansi_code(AnsiColor color) noexcept { switch (color) { - case AnsiColor::Default: - return ""; - case AnsiColor::Black: - return "\x1b[30m"; - case AnsiColor::Red: - return "\x1b[31m"; - case AnsiColor::Green: - return "\x1b[32m"; - case AnsiColor::Yellow: - return "\x1b[33m"; - case AnsiColor::Blue: - return "\x1b[34m"; - case AnsiColor::Magenta: - return "\x1b[35m"; - case AnsiColor::Cyan: - return "\x1b[36m"; - case AnsiColor::White: - return "\x1b[37m"; - case AnsiColor::BrightBlack: - return "\x1b[90m"; - case AnsiColor::BrightRed: - return "\x1b[91m"; - case AnsiColor::BrightGreen: - return "\x1b[92m"; - case AnsiColor::BrightYellow: - return "\x1b[93m"; - case AnsiColor::BrightBlue: - return "\x1b[94m"; - case AnsiColor::BrightMagenta: - return "\x1b[95m"; - case AnsiColor::BrightCyan: - return "\x1b[96m"; - case AnsiColor::BrightWhite: - return "\x1b[97m"; + case AnsiColor::Default: return ""; + case AnsiColor::Black: return "\x1b[30m"; + case AnsiColor::Red: return "\x1b[31m"; + case AnsiColor::Green: return "\x1b[32m"; + case AnsiColor::Yellow: return "\x1b[33m"; + case AnsiColor::Blue: return "\x1b[34m"; + case AnsiColor::Magenta: return "\x1b[35m"; + case AnsiColor::Cyan: return "\x1b[36m"; + case AnsiColor::White: return "\x1b[37m"; + case AnsiColor::BrightBlack: return "\x1b[90m"; + case AnsiColor::BrightRed: return "\x1b[91m"; + case AnsiColor::BrightGreen: return "\x1b[92m"; + case AnsiColor::BrightYellow: return "\x1b[93m"; + case AnsiColor::BrightBlue: return "\x1b[94m"; + case AnsiColor::BrightMagenta: return "\x1b[95m"; + case AnsiColor::BrightCyan: return "\x1b[96m"; + case AnsiColor::BrightWhite: return "\x1b[97m"; } return ""; } @@ -103,13 +85,10 @@ namespace Void::Logging {Level::Error, AnsiColor::BrightRed}, {Level::Fatal, AnsiColor::BrightMagenta}, }; - // The level token defaults to the level's own colour. p.token_colors = {}; return p; } - // ── FormatDetail ────────────────────────────────────────────────────── - namespace FormatDetail { @@ -143,12 +122,9 @@ namespace Void::Logging std::string_view kind_str(Kind kind) { switch (kind) { - case Kind::Message: - return "Message"; - case Kind::ScopeEnter: - return "ScopeEnter"; - case Kind::ScopeExit: - return "ScopeExit"; + case Kind::Message: return "Message"; + case Kind::ScopeEnter: return "ScopeEnter"; + case Kind::ScopeExit: return "ScopeExit"; } return "?"; } @@ -168,7 +144,7 @@ namespace Void::Logging const std::string* found = nullptr; for (const auto& [k, v] : entry.fields) { if (k == key) { - found = &v; // later duplicates win + found = &v; } } return found; @@ -177,8 +153,6 @@ namespace Void::Logging } // namespace FormatDetail - // ── PatternFormatter ────────────────────────────────────────────────── - PatternFormatter::PatternFormatter(std::string pattern) { std::string literal; @@ -206,10 +180,9 @@ namespace Void::Logging literal += rest; break; } - const auto body = rest.substr(1, close - 1); // inside braces + const auto body = rest.substr(1, close - 1); rest.remove_prefix(close + 1); - // Split "token:spec". std::string_view token = body; std::string_view spec; if (const auto colon = body.find(':'); @@ -222,7 +195,6 @@ namespace Void::Logging seg.literal = false; seg.text = std::string{token}; - // spec = [align][width][,colour] std::string_view color_name; if (const auto comma = spec.find(','); comma != std::string_view::npos) { @@ -292,15 +264,18 @@ namespace Void::Logging if (name == "kind") { return std::string{kind_str(entry.kind)}; } - // Custom token? if (const auto it = m_custom.find(name); it != m_custom.end()) { return it->second(entry); } - // Structured field? if (const auto* v = find_field(entry, name)) { + if (!m_fields.allows(name)) { + return {}; + } + if (m_fields.is_redacted(name)) { + return m_fields.redaction_mask; + } return *v; } - // Unknown — keep literal so misspellings are visible. return "{" + name + "}"; } @@ -315,7 +290,6 @@ namespace Void::Logging std::string text = render_token(seg, entry); - // Width / alignment. if (seg.width > text.size()) { const std::size_t pad = seg.width - text.size(); switch (seg.align) { @@ -337,7 +311,6 @@ namespace Void::Logging } } - // Colour. if (m_colors.enabled && seg.color_mode != ColorMode::None) { AnsiColor color = AnsiColor::Default; if (seg.color_mode == ColorMode::Auto) { @@ -355,7 +328,6 @@ namespace Void::Logging continue; } } - // Per-token colour from the policy (no inline ,colour spec). if (m_colors.enabled && seg.color_mode == ColorMode::None) { if (const auto it = m_colors.token_colors.find(seg.text); it != m_colors.token_colors.end() && @@ -371,8 +343,6 @@ namespace Void::Logging return out; } - // ── JsonLinesFormatter ──────────────────────────────────────────────── - std::string JsonLinesFormatter::format(const Entry& entry) const { auto obj = Json::object(); @@ -383,6 +353,9 @@ namespace Void::Logging o.emplace_back("kind", Json::Value{FormatDetail::kind_str(entry.kind)}); o.emplace_back("thread", Json::Value{FormatDetail::thread_str(entry.thread_id)}); + if (entry.truncated) { + o.emplace_back("truncated", Json::Value{true}); + } if (!entry.scopes.empty()) { auto arr = Json::array(); arr.as_array().reserve(entry.scopes.size()); @@ -397,7 +370,11 @@ namespace Void::Logging if (!m_fields.allows(k)) { continue; } - fobj.as_object().emplace_back(k, Json::Value{v}); + fobj.as_object().emplace_back( + k, + Json::Value{m_fields.is_redacted(k) + ? m_fields.redaction_mask + : v}); } if (!fobj.as_object().empty()) { o.emplace_back("fields", std::move(fobj)); @@ -408,26 +385,56 @@ namespace Void::Logging o.emplace_back("file", Json::Value{file}); o.emplace_back( "line", - Json::Value{static_cast(entry.location.line())}); + Json::Value{static_cast(entry.location.line())}); } return Json::serialize(obj); } - // ── LogfmtFormatter ─────────────────────────────────────────────────── - namespace { void append_quoted(std::string& out, std::string_view value) { out += '"'; - for (const char c : value) { - if (c == '"' || c == '\\') { - out += '\\'; + for (const unsigned char uc : value) { + switch (uc) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (uc < 0x20 || uc == 0x7F) { + out += std::format("\\u{:04x}", uc); + } else { + out += static_cast(uc); + } + break; } - out += c; } out += '"'; } + + [[nodiscard]] bool is_safe_bare_token(std::string_view sv) noexcept + { + if (sv.empty()) { + return false; + } + for (const unsigned char uc : sv) { + if (uc <= 0x20 || uc == 0x7F || uc == '=' || uc == '"') { + return false; + } + } + return true; + } + + void append_key_or_token(std::string& out, std::string_view token) + { + if (is_safe_bare_token(token)) { + out += token; + } else { + append_quoted(out, token); + } + } } // namespace std::string LogfmtFormatter::format(const Entry& entry) const @@ -439,23 +446,27 @@ namespace Void::Logging out += to_string(entry.level); out += " thread="; out += FormatDetail::thread_str(entry.thread_id); + if (entry.truncated) { + out += " truncated=true"; + } if (auto crumb = FormatDetail::scope_breadcrumb(entry.scopes); !crumb.empty()) { out += " scopes="; - out += crumb; + append_key_or_token(out, crumb); } for (const auto& [k, v] : entry.fields) { if (!m_fields.allows(k)) { continue; } out += ' '; - out += k; + append_key_or_token(out, k); out += '='; - append_quoted(out, v); + append_quoted( + out, m_fields.is_redacted(k) ? m_fields.redaction_mask : v); } if (auto file = FormatDetail::file_basename(entry); !file.empty()) { out += " file="; - out += file; + append_key_or_token(out, file); out += ':'; out += std::to_string(entry.location.line()); } @@ -464,4 +475,34 @@ namespace Void::Logging return out; } -} // namespace Void::Logging + Void::Result::Result + format_bounded(const Formatter& formatter, + const Entry& entry, + std::size_t max_bytes, + bool truncate) + { + if (max_bytes == 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "format_bounded requires max_bytes > 0")); + } + std::string rendered = formatter.format(entry); + if (rendered.size() <= max_bytes) { + return rendered; + } + if (!truncate) { + return Void::Result::fail(make_log_error( + LogErrorCode::entry_too_large, + "Formatted log entry exceeds max_format_scratch_bytes")); + } + constexpr std::string_view kMarker = "...[truncated]"; + if (max_bytes <= kMarker.size()) { + rendered.resize(max_bytes); + return rendered; + } + rendered.resize(max_bytes - kMarker.size()); + rendered += kMarker; + return rendered; + } + +} // namespace Void::Logging \ No newline at end of file diff --git a/src/Log/FromConfig.cpp b/src/Log/FromConfig.cpp deleted file mode 100644 index 605bf8b..0000000 --- a/src/Log/FromConfig.cpp +++ /dev/null @@ -1,325 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -namespace Void::Logging -{ - - namespace - { - std::vector split_list(std::string_view csv) - { - std::vector out; - std::size_t start = 0; - while (start <= csv.size()) { - auto comma = csv.find(',', start); - if (comma == std::string_view::npos) { - comma = csv.size(); - } - auto item = csv.substr(start, comma - start); - while (!item.empty() && item.front() == ' ') { - item.remove_prefix(1); - } - while (!item.empty() && item.back() == ' ') { - item.remove_suffix(1); - } - if (!item.empty()) { - out.emplace_back(item); - } - start = comma + 1; - } - return out; - } - - std::optional parse_level(std::string_view name) - { - std::string lower; - for (const char c : name) { - lower += static_cast( - std::tolower(static_cast(c))); - } - if (lower == "trace") { - return Level::Trace; - } - if (lower == "debug") { - return Level::Debug; - } - if (lower == "info") { - return Level::Info; - } - if (lower == "warning" || lower == "warn") { - return Level::Warning; - } - if (lower == "error") { - return Level::Error; - } - if (lower == "fatal") { - return Level::Fatal; - } - if (lower == "disabled" || lower == "off") { - return Level::Disabled; - } - return std::nullopt; - } - - std::optional - parse_facade_level(std::string_view name) - { - const auto l = parse_level(name); - if (!l.has_value()) { - return std::nullopt; - } - switch (*l) { - case Level::Trace: - return Void::Log::Level::Trace; - case Level::Debug: - return Void::Log::Level::Debug; - case Level::Info: - return Void::Log::Level::Info; - case Level::Warning: - return Void::Log::Level::Warning; - case Level::Error: - return Void::Log::Level::Error; - case Level::Fatal: - return Void::Log::Level::Fatal; - case Level::Disabled: - return Void::Log::Level::Disabled; - } - return std::nullopt; - } - - // Field allow/deny lists for the structured (json/logfmt) sinks, from - // the per-sink keys `fields.include` / `fields.exclude` (comma lists). - FieldFilter make_field_filter(const Configuration::Config& cfg) - { - FieldFilter f; - f.include = split_list(cfg.get_or("fields.include", "")); - f.exclude = split_list(cfg.get_or("fields.exclude", "")); - return f; - } - - std::shared_ptr - make_formatter(const Configuration::Config& cfg) - { - const auto format = cfg.get_or("format", "default"); - if (format == "pattern") { - auto fmt = - std::make_shared(std::string{cfg.get_or( - "pattern", "{time} [{level}] {scopes}{message}")}); - if (cfg.get_or_as("color", false)) { - fmt->set_color_policy(ColorPolicy::defaults()); - } - return fmt; - } - if (format == "json") { - auto fmt = std::make_shared(); - fmt->set_field_filter(make_field_filter(cfg)); - return fmt; - } - if (format == "logfmt") { - auto fmt = std::make_shared(); - fmt->set_field_filter(make_field_filter(cfg)); - return fmt; - } - return nullptr; // "default": per-sink built-in rendering - } - - struct Dispatch { - Mode mode = Mode::Async; - std::size_t capacity = 512; - OverflowPolicy policy = OverflowPolicy::Block; - }; - - Dispatch make_dispatch(const Configuration::Config& cfg) - { - Dispatch d; - if (!cfg.get_or_as("async", true)) { - d.mode = Mode::Immediate; - } - d.capacity = cfg.get_or_as("capacity", 512); - const auto overflow = cfg.get_or("overflow", "block"); - if (overflow == "drop_newest") { - d.policy = OverflowPolicy::DropNewest; - } else if (overflow == "drop_oldest") { - d.policy = OverflowPolicy::DropOldest; - } - return d; - } - } // namespace - - Void::Result::Result, Void::Result::Error> - from_config(const Configuration::Config& cfg, std::string_view prefix) - { - const auto sub = cfg.subtree(prefix); - const auto dispatch = make_dispatch(sub); - const auto formatter = make_formatter(sub); - - std::vector> sinks; - for (const auto& name : split_list(sub.get_or("sinks", "console"))) { - if (name == "console") { - const bool to_stdout = - sub.get_or("console.stream", "stderr") == "stdout"; - auto sink = std::make_shared( - to_stdout ? std::cout : std::cerr, dispatch.mode, - dispatch.capacity); - if (formatter) { - sink->set_formatter(formatter); - } - sinks.push_back(std::move(sink)); - } else if (name == "file") { - const auto path = sub.get_or("file.path"); - if (path.empty()) { - return Void::Result::fail( - "Logging::from_config: sink 'file' needs " - "file.path"); - } - auto sink = FileLogger::open(std::filesystem::path{path}, - dispatch.mode, - dispatch.capacity); - if (!sink.has_value()) { - return Void::Result::fail(std::move(sink).error()); - } - if (formatter) { - (*sink)->set_formatter(formatter); - } - sinks.push_back(std::shared_ptr{std::move(*sink)}); - } else if (name == "rotating") { - const auto path = sub.get_or("rotating.path"); - if (path.empty()) { - return Void::Result::fail( - "Logging::from_config: sink 'rotating' needs " - "rotating.path"); - } - RotatingFileLogger::Options opt; - opt.max_bytes = - sub.get_or_as("rotating.max_kb", 1024) * 1024; - opt.max_files = - sub.get_or_as("rotating.max_files", 5); - opt.mode = dispatch.mode; - opt.capacity = dispatch.capacity; - opt.policy = dispatch.policy; - auto sink = - RotatingFileLogger::open(std::filesystem::path{path}, opt); - if (!sink.has_value()) { - return Void::Result::fail(std::move(sink).error()); - } - if (formatter) { - (*sink)->set_formatter(formatter); - } - sinks.push_back(std::shared_ptr{std::move(*sink)}); - } else if (name == "split") { - const auto dir = sub.get_or("split.dir"); - if (dir.empty()) { - return Void::Result::fail( - "Logging::from_config: sink 'split' needs " - "split.dir"); - } - SplitFileLogger::Options opt; - opt.combined = sub.get_or_as("split.combined", true); - opt.max_bytes = - sub.get_or_as("split.max_kb", 1024) * 1024; - opt.max_files = - sub.get_or_as("split.max_files", 5); - opt.mode = dispatch.mode; - opt.capacity = dispatch.capacity; - opt.policy = dispatch.policy; - auto sink = - SplitFileLogger::open(std::filesystem::path{dir}, opt); - if (!sink.has_value()) { - return Void::Result::fail(std::move(sink).error()); - } - if (formatter) { - (*sink)->set_formatter(formatter); - } - sinks.push_back(std::shared_ptr{std::move(*sink)}); - } else if (name == "history") { - const auto path = sub.get_or("history.path"); - if (path.empty()) { - return Void::Result::fail( - "Logging::from_config: sink 'history' needs " - "history.path"); - } - HistoryLogger::Options opt; - opt.max_bytes = - sub.get_or_as("history.max_kb", 8192) * 1024; - opt.max_files = - sub.get_or_as("history.max_files", 10); - opt.mode = dispatch.mode; - opt.capacity = dispatch.capacity; - opt.policy = dispatch.policy; - auto sink = - HistoryLogger::open(std::filesystem::path{path}, opt); - if (!sink.has_value()) { - return Void::Result::fail(std::move(sink).error()); - } - sinks.push_back(std::shared_ptr{std::move(*sink)}); - } else if (name == "syslog") { -#ifdef VOID_HAS_SYSLOG - const auto identity = sub.get_or("syslog.identity"); - if (identity.empty()) { - return Void::Result::fail( - "Logging::from_config: sink 'syslog' needs " - "syslog.identity"); - } - sinks.push_back(std::make_shared( - std::string{identity}, dispatch.mode, dispatch.capacity)); -#else - return Void::Result::fail( - "Logging::from_config: syslog is not available on " - "this platform"); -#endif - } else { - return Void::Result::fail(std::format( - "Logging::from_config: unknown sink '{}'", name)); - } - } - - std::shared_ptr root; - if (sinks.empty()) { - root = std::make_shared(); - } else if (sinks.size() == 1) { - root = std::move(sinks.front()); - } else { - root = std::make_shared(std::move(sinks)); - } - - if (const auto level = parse_level(sub.get_or("level", "trace")); - level.has_value()) { - root->set_level(*level); - } - - Void::Log::debug("Logging", "from_config: built logger tree"); - return Void::Result::ok(std::move(root)); - } - - void apply_facade_config(const Configuration::Config& cfg, - std::string_view prefix) - { - const auto sub = cfg.subtree(prefix); - if (const auto level = parse_facade_level(sub.get_or("level", "")); - level.has_value()) { - Void::Log::set_min_level(*level); - } - for (const auto& key : sub.subtree("module_levels").keys()) { - const auto value = sub.get_or(std::string{"module_levels."} + key); - if (const auto level = parse_facade_level(value); - level.has_value()) { - Void::Log::set_module_level(key, *level); - } - } - } - -} // namespace Void::Logging diff --git a/src/Log/Logger.cpp b/src/Log/Logger.cpp index d6ba3a3..460e74e 100644 --- a/src/Log/Logger.cpp +++ b/src/Log/Logger.cpp @@ -1,38 +1,95 @@ #include #include -#include // std::exchange +#include +#include +#include +#include +#include +#include namespace Void::Logging { - // ============================================================================= - // Thread-local definition - // ============================================================================= + namespace + { + constexpr std::size_t kEntryOverheadBytes = 128; + constexpr std::size_t kMaxErrorSummaryBytes = 256; + constexpr std::size_t kMaxNestedLoggerDepth = 8; + + thread_local std::vector t_active_loggers; + + struct ActiveLoggerGuard { + const Logger* logger{nullptr}; + bool pushed{false}; + + explicit ActiveLoggerGuard(const Logger* l) : logger(l) + { + t_active_loggers.push_back(logger); + pushed = true; + } + + ~ActiveLoggerGuard() noexcept + { + if (pushed && !t_active_loggers.empty()) { + t_active_loggers.pop_back(); + } + } + + ActiveLoggerGuard(const ActiveLoggerGuard&) = delete; + ActiveLoggerGuard& operator=(const ActiveLoggerGuard&) = delete; + }; + + LoggerOptions make_legacy_options(Mode mode, + std::size_t capacity, + OverflowPolicy policy) noexcept + { + LoggerOptions opt; + opt.mode = mode; + opt.policy = policy; + const std::size_t cap = capacity > 0 ? capacity : 1; + opt.limits.entries = cap; + opt.limits.owned_bytes = + std::max(8ULL * 1024ULL * 1024ULL, cap * 1024ULL); + opt.limits.max_scopes = 64; + opt.limits.max_fields = 64; + opt.suppress_reentrancy = false; + return opt; + } + } // namespace + + Void::Result::Result DeliveryLimits::validate() const + { + if (entries == 0 || owned_bytes == 0 || max_entry_bytes == 0 || + batch_entries == 0 || batch_bytes == 0 || max_fields == 0 || + max_scopes == 0 || max_field_key_bytes == 0 || + max_field_value_bytes == 0 || max_format_scratch_bytes == 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "DeliveryLimits bounds must all be non-zero")); + } + if (max_entry_bytes > owned_bytes) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "DeliveryLimits::max_entry_bytes cannot exceed owned_bytes")); + } + return {}; + } thread_local std::vector Logger::s_scope_stack; - // ============================================================================= - // ScopedContext - // ============================================================================= - Logger::ScopedContext::ScopedContext(Logger& owner, std::string name, Level level, std::source_location loc) noexcept : m_owner(&owner), m_name(std::move(name)), m_level(level) { - // push_back can technically throw; if it does we mark inactive so - // the destructor does not attempt a mismatched pop or spurious exit - // entry. try { s_scope_stack.push_back(m_name); } catch (...) { m_active = false; return; } - // Emit the ScopeEnter entry after the push so Entry::scopes already - // contains the new scope (innermost = last). owner.emit_scope_boundary(Kind::ScopeEnter, m_name, m_level, loc); } @@ -41,15 +98,11 @@ namespace Void::Logging if (!m_active || m_owner == nullptr) { return; } - // Emit the exit entry while the scope is still on the stack so that - // Entry::scopes reflects the stack *including* this scope, matching the - // ScopeEnter entry. m_owner->emit_scope_boundary( Kind::ScopeExit, m_name, m_level, - std::source_location{}); // no meaningful caller site - + std::source_location{}); if (!s_scope_stack.empty()) { s_scope_stack.pop_back(); } @@ -62,37 +115,42 @@ namespace Void::Logging { } - // ============================================================================= - // Logger — lifetime - // ============================================================================= - - Logger::Logger(Mode mode, std::size_t capacity, + Logger::Logger(Mode mode, + std::size_t capacity, OverflowPolicy policy) noexcept - : m_mode(mode), m_async_capacity(capacity > 0 ? capacity : 1), - m_policy(policy), m_buffer_capacity(capacity > 0 ? capacity : 1), - m_space(static_cast(capacity > 0 ? capacity : 1)) + : m_mode(mode), + m_options(make_legacy_options(mode, capacity, policy)), + m_buffer_capacity(capacity > 0 ? capacity : 1) { - if (mode == Mode::Buffered) { - m_buffer.reserve(m_buffer_capacity); + } + + Logger::Logger(LoggerOptions options) + : m_mode(options.mode), + m_options(std::move(options)), + m_buffer_capacity( + m_options.limits.entries > 0 ? m_options.limits.entries : 1) + { + if (m_options.clock == nullptr) { + m_options.clock = &Void::Time::SystemMonotonicClock::instance(); } } Logger::~Logger() noexcept { - // Only stop and join the worker. Virtual extension points must not - // be touched here — the derived class is already destroyed. Pending - // entries are freed (silently dropped) by the queue's destructor. - m_stop.store(true, std::memory_order_release); - wake_worker(); + { + std::lock_guard lock{m_mutex}; + m_stop_admission = true; + m_closed = true; + } + m_stop_worker.store(true, std::memory_order_release); + m_space_cv.notify_all(); + m_work_cv.notify_all(); + m_done_cv.notify_all(); if (m_worker.joinable()) { m_worker.join(); } } - // ============================================================================= - // Configuration - // ============================================================================= - void Logger::set_level(Level level) noexcept { m_level.store(level, std::memory_order_relaxed); @@ -105,32 +163,42 @@ namespace Void::Logging void Logger::set_mode(Mode mode) noexcept { + std::unique_lock lock{m_mutex}; const Mode old = m_mode.load(std::memory_order_acquire); if (old == mode) { return; } + m_mode_changing = true; + const Ticket target = m_next_ticket; + m_space_cv.notify_all(); - // Deliver everything pending under the old strategy first so no - // entry is stranded in a queue/buffer nobody drains anymore. - if (old == Mode::Async) { - drain_async(); - } else if (old == Mode::Buffered) { - std::vector to_flush; - { - std::lock_guard lock(m_mutex); - to_flush = std::move(m_buffer); - m_buffer = {}; - } - if (!to_flush.empty()) { - on_flush(to_flush); + if (old == Mode::Buffered && !m_queue.empty()) { + std::vector batch; + std::size_t batch_bytes = m_queued_bytes; + batch.reserve(m_queue.size()); + while (!m_queue.empty()) { + batch.push_back(std::move(m_queue.front())); + m_queue.pop_front(); } + m_queued_entries = 0; + m_queued_bytes = 0; + m_in_flight_entries += batch.size(); + m_in_flight_bytes += batch_bytes; + lock.unlock(); + deliver_batch_unlocked(batch, false, batch_bytes); + lock.lock(); + } else { + m_work_cv.notify_all(); + m_done_cv.wait(lock, [this, target] { + return m_completed_watermark >= target || + m_stop_worker.load(std::memory_order_acquire); + }); } - if (mode == Mode::Buffered) { - std::lock_guard lock(m_mutex); - m_buffer.reserve(m_buffer_capacity); - } m_mode.store(mode, std::memory_order_release); + m_mode_changing = false; + lock.unlock(); + m_space_cv.notify_all(); } Mode Logger::mode() const noexcept @@ -140,59 +208,319 @@ namespace Void::Logging void Logger::set_buffer_capacity(std::size_t n) noexcept { - std::lock_guard lock(m_mutex); + std::lock_guard lock{m_mutex}; m_buffer_capacity = n > 0 ? n : 1; } std::size_t Logger::buffer_capacity() const noexcept { - std::lock_guard lock(m_mutex); + std::lock_guard lock{m_mutex}; return m_buffer_capacity; } - OverflowPolicy Logger::overflow_policy() const noexcept { return m_policy; } - - // ============================================================================= - // Scoped context - // ============================================================================= - - Logger::ScopedContext Logger::push_scope(std::string name, - Level level, - std::source_location loc) noexcept + OverflowPolicy Logger::overflow_policy() const noexcept { - return ScopedContext(*this, std::move(name), level, loc); + return m_options.policy; } - void Logger::scope(std::string_view name, - Level level, - std::source_location loc) + std::size_t Logger::estimate_entry_bytes(const Entry& entry) noexcept { - // Emit a pair of scope boundary entries back-to-back. - // The scope stack is NOT modified — this is the "lightweight" variant. - emit_scope_boundary(Kind::ScopeEnter, name, level, loc); - emit_scope_boundary(Kind::ScopeExit, name, level, - std::source_location{}); + std::size_t total = kEntryOverheadBytes + entry.message.size(); + for (const auto& sc : entry.scopes) { + total += 32 + sc.size(); + } + for (const auto& [k, v] : entry.fields) { + total += 48 + k.size() + v.size(); + } + return total; } - std::span Logger::current_scopes() noexcept + Void::Result::Result Logger::prepare_entry(Entry& entry) const { - return s_scope_stack; + const auto& lim = m_options.limits; + if (auto v = lim.validate(); !v) { + return v; + } + + auto reject_or_truncate = [&](std::string_view reason) -> Void::Result::Result { + if (!lim.truncate_oversize) { + return Void::Result::fail(make_log_error( + LogErrorCode::entry_too_large, std::string{reason})); + } + entry.truncated = true; + return {}; + }; + + if (entry.scopes.size() > lim.max_scopes) { + if (auto r = reject_or_truncate("Log entry exceeds max_scopes"); !r) { + return r; + } + entry.scopes.resize(lim.max_scopes); + } + if (entry.fields.size() > lim.max_fields) { + if (auto r = reject_or_truncate("Log entry exceeds max_fields"); !r) { + return r; + } + entry.fields.resize(lim.max_fields); + } + for (auto& [k, v] : entry.fields) { + if (k.size() > lim.max_field_key_bytes) { + if (auto r = reject_or_truncate("Log field key exceeds bound"); !r) { + return r; + } + k.resize(lim.max_field_key_bytes); + } + if (v.size() > lim.max_field_value_bytes) { + if (auto r = reject_or_truncate("Log field value exceeds bound"); !r) { + return r; + } + v.resize(lim.max_field_value_bytes); + } + } + + const std::size_t msg_cap = lim.max_entry_bytes; + if (entry.message.size() > msg_cap || + estimate_entry_bytes(entry) > lim.max_entry_bytes + kEntryOverheadBytes + 1024) { + if (estimate_entry_bytes(entry) > lim.max_entry_bytes + kEntryOverheadBytes * 4) { + if (auto r = reject_or_truncate("Log entry exceeds max_entry_bytes"); !r) { + return r; + } + if (entry.message.size() > msg_cap) { + entry.message.resize(msg_cap); + } + } + } + if (entry.message.size() > lim.max_entry_bytes) { + if (auto r = reject_or_truncate("Log message exceeds max_entry_bytes"); !r) { + return r; + } + entry.message.resize(lim.max_entry_bytes); + } + return {}; } - // ============================================================================= - // Preset factory - // ============================================================================= - - Logger::Preset Logger::make_preset(Level level, std::string prefix) noexcept + bool Logger::is_active_logger_on_thread() const noexcept { - return Preset(*this, level, std::move(prefix)); + for (const auto* l : t_active_loggers) { + if (l == this) { + return true; + } + } + return false; } - // ============================================================================= - // Core logging - // ============================================================================= + Void::Result::Result + Logger::try_submit(Entry entry, Void::Async::OperationOptions options) + { + if (entry.level < m_level.load(std::memory_order_relaxed)) { + return SubmitReceipt{SubmitState::Filtered, std::nullopt, entry.truncated}; + } - void Logger::relay(Entry entry) { submit(std::move(entry)); } + if (t_active_loggers.size() >= kMaxNestedLoggerDepth || + (m_options.suppress_reentrancy && is_active_logger_on_thread())) { + m_reentrant_dropped.fetch_add(1, std::memory_order_relaxed); + return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated}; + } + + if (m_quarantined.load(std::memory_order_acquire)) { + return Void::Result::fail(make_log_error( + LogErrorCode::quarantined, last_error_summary())); + } + + if (auto prep = prepare_entry(entry); !prep) { + return Void::Result::fail(std::move(prep).error()); + } + + const std::size_t entry_bytes = estimate_entry_bytes(entry); + if (entry_bytes > m_options.limits.owned_bytes) { + return Void::Result::fail(make_log_error( + LogErrorCode::entry_too_large, + "Log entry byte cost exceeds Logger DeliveryLimits::owned_bytes")); + } + + if (options.stop.stop_requested()) { + return Void::Result::fail(make_log_error( + LogErrorCode::cancelled, + "Log submission cancelled before admission")); + } + if (Void::Async::is_deadline_expired(options, *m_options.clock)) { + return Void::Result::fail(make_log_error( + LogErrorCode::timeout, + "Log submission deadline expired before admission")); + } + + const Mode active_mode = m_mode.load(std::memory_order_acquire); + if (active_mode == Mode::Async) { + start_worker(); + } + + std::unique_lock lock{m_mutex}; + if (m_stop_admission || m_closed || + m_next_ticket == std::numeric_limits::max()) { + m_stop_admission = true; + return SubmitReceipt{SubmitState::Closed, std::nullopt, entry.truncated}; + } + + auto fits_budget = [this, entry_bytes]() noexcept { + return (m_queued_entries + m_in_flight_entries + 1 <= + m_options.limits.entries) && + (entry_bytes <= + m_options.limits.owned_bytes - + std::min(m_queued_bytes + m_in_flight_bytes, + m_options.limits.owned_bytes)); + }; + + if (active_mode == Mode::Immediate) { + if (!fits_budget()) { + ++m_dropped_count; + return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated}; + } + const Ticket t = ++m_next_ticket; + ++m_admitted_count; + ++m_in_flight_entries; + m_in_flight_bytes += entry_bytes; + const bool trunc = entry.truncated; + std::vector single; + single.push_back(QueuedItem{t, entry_bytes, std::move(entry)}); + lock.unlock(); + deliver_batch_unlocked(single, false, entry_bytes); + return SubmitReceipt{SubmitState::Accepted, t, trunc}; + } + + if (active_mode == Mode::Buffered) { + while (!fits_budget() && m_options.policy == OverflowPolicy::DropOldest && + !m_queue.empty()) { + auto evicted = std::move(m_queue.front()); + m_queue.pop_front(); + --m_queued_entries; + m_queued_bytes -= std::min(m_queued_bytes, evicted.bytes); + ++m_dropped_count; + mark_terminal_locked(evicted.ticket, TerminalOutcome::Dropped); + } + if (!fits_budget()) { + ++m_dropped_count; + return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated}; + } + const Ticket t = ++m_next_ticket; + ++m_admitted_count; + ++m_queued_entries; + m_queued_bytes += entry_bytes; + const bool trunc = entry.truncated; + m_queue.push_back(QueuedItem{t, entry_bytes, std::move(entry)}); + + if (m_queue.size() >= m_buffer_capacity) { + std::vector batch; + const std::size_t batch_bytes = m_queued_bytes; + batch.reserve(m_queue.size()); + while (!m_queue.empty()) { + batch.push_back(std::move(m_queue.front())); + m_queue.pop_front(); + } + m_queued_entries = 0; + m_queued_bytes = 0; + m_in_flight_entries += batch.size(); + m_in_flight_bytes += batch_bytes; + lock.unlock(); + deliver_batch_unlocked(batch, false, batch_bytes); + } + return SubmitReceipt{SubmitState::Accepted, t, trunc}; + } + + // Mode::Async + switch (m_options.policy) { + case OverflowPolicy::DropNewest: + if (m_mode_changing || !fits_budget()) { + ++m_dropped_count; + return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated}; + } + break; + + case OverflowPolicy::DropOldest: + while ((m_mode_changing || !fits_budget()) && !m_queue.empty()) { + auto evicted = std::move(m_queue.front()); + m_queue.pop_front(); + --m_queued_entries; + m_queued_bytes -= std::min(m_queued_bytes, evicted.bytes); + ++m_dropped_count; + mark_terminal_locked(evicted.ticket, TerminalOutcome::Dropped); + } + if (m_mode_changing || !fits_budget()) { + // All capacity is in flight -> drop new arrival. + ++m_dropped_count; + return SubmitReceipt{SubmitState::Dropped, std::nullopt, entry.truncated}; + } + m_done_cv.notify_all(); + break; + + case OverflowPolicy::Block: { + if (std::this_thread::get_id() == m_worker_id.load(std::memory_order_acquire) || + is_active_logger_on_thread()) { + return Void::Result::fail(make_log_error( + LogErrorCode::would_deadlock, + "Blocking submit from inside logger delivery/worker would deadlock")); + } + + struct StopNotifier { + std::condition_variable* cv; + void operator()() const noexcept { cv->notify_all(); } + }; + std::optional> stop_cb; + if (options.stop.stop_possible()) { + stop_cb.emplace(options.stop, StopNotifier{&m_space_cv}); + } + + while (!m_stop_admission && !m_closed && + !m_quarantined.load(std::memory_order_acquire) && + (m_mode_changing || !fits_budget())) { + if (options.stop.stop_requested()) { + return Void::Result::fail(make_log_error( + LogErrorCode::cancelled, + "Blocked log submission cancelled")); + } + if (Void::Async::is_deadline_expired(options, *m_options.clock)) { + return Void::Result::fail(make_log_error( + LogErrorCode::timeout, + "Blocked log submission timed out")); + } + if (options.deadline.has_value()) { + const auto rem = *options.deadline - m_options.clock->now(); + const auto slice = std::min( + rem, std::chrono::milliseconds{5}); + if (slice.count() > 0) { + m_space_cv.wait_for(lock, slice); + } + } else { + m_space_cv.wait(lock); + } + } + if (m_stop_admission || m_closed) { + return SubmitReceipt{SubmitState::Closed, std::nullopt, entry.truncated}; + } + if (m_quarantined.load(std::memory_order_acquire)) { + return Void::Result::fail(make_log_error( + LogErrorCode::quarantined, m_last_error)); + } + break; + } + } + + if (m_next_ticket == std::numeric_limits::max()) { + m_stop_admission = true; + return SubmitReceipt{SubmitState::Closed, std::nullopt, entry.truncated}; + } + + const Ticket t = ++m_next_ticket; + ++m_admitted_count; + ++m_queued_entries; + m_queued_bytes += entry_bytes; + const bool trunc = entry.truncated; + m_queue.push_back(QueuedItem{t, entry_bytes, std::move(entry)}); + lock.unlock(); + m_work_cv.notify_one(); + return SubmitReceipt{SubmitState::Accepted, t, trunc}; + } + + void Logger::relay(Entry entry) { (void)try_submit(std::move(entry)); } void Logger::trace(std::string_view msg, std::source_location loc) { @@ -219,27 +547,202 @@ namespace Void::Logging log(Level::Fatal, msg, loc); } - // ============================================================================= - // Flush - // ============================================================================= - - void Logger::flush() + Void::Result::Result + Logger::flush_through(Ticket target, FlushOptions options) { - if (m_mode.load(std::memory_order_acquire) == Mode::Async) { - drain_async(); - return; + if (std::this_thread::get_id() == m_worker_id.load(std::memory_order_acquire) || + is_active_logger_on_thread()) { + return Void::Result::fail(make_log_error( + LogErrorCode::would_deadlock, + "flush_through cannot run from inside active delivery callback or worker")); } - std::vector to_flush; + + std::unique_lock lock{m_mutex}; + const Ticket resolved_target = target == 0 ? m_next_ticket : target; + + if (m_mode.load(std::memory_order_acquire) == Mode::Buffered && + !m_queue.empty()) { + std::vector batch; + const std::size_t batch_bytes = m_queued_bytes; + batch.reserve(m_queue.size()); + while (!m_queue.empty()) { + batch.push_back(std::move(m_queue.front())); + m_queue.pop_front(); + } + m_queued_entries = 0; + m_queued_bytes = 0; + m_in_flight_entries += batch.size(); + m_in_flight_bytes += batch_bytes; + lock.unlock(); + deliver_batch_unlocked(batch, false, batch_bytes); + lock.lock(); + } + + struct StopNotifier { + std::condition_variable* cv; + void operator()() const noexcept { cv->notify_all(); } + }; + std::optional> stop_cb; + if (options.async.stop.stop_possible()) { + stop_cb.emplace(options.async.stop, StopNotifier{&m_done_cv}); + } + + FlushReport report; + while (m_completed_watermark < resolved_target && + !m_stop_worker.load(std::memory_order_acquire)) { + if (options.async.stop.stop_requested()) { + report.cancelled = true; + break; + } + if (Void::Async::is_deadline_expired(options.async, *m_options.clock)) { + report.timed_out = true; + break; + } + m_work_cv.notify_all(); + if (options.async.deadline.has_value()) { + const auto rem = *options.async.deadline - m_options.clock->now(); + const auto slice = std::min( + rem, std::chrono::milliseconds{5}); + if (slice.count() > 0) { + m_done_cv.wait_for(lock, slice); + } + } else { + m_done_cv.wait(lock); + } + } + + report.delivered = m_wm_delivered; + report.dropped = m_wm_dropped; + report.failed = m_wm_failed; + report.watermark = m_completed_watermark; + lock.unlock(); + + if (!report.cancelled && !report.timed_out && + options.durability == FlushDurability::SyncFiles) { + if (auto sres = sync_files(); !sres) { + return Void::Result::fail(std::move(sres).error()); + } + } + return report; + } + + Void::Result::Result Logger::close(CloseOptions options) + { + if (std::this_thread::get_id() == m_worker_id.load(std::memory_order_acquire) || + is_active_logger_on_thread()) { + return Void::Result::fail(make_log_error( + LogErrorCode::would_deadlock, + "Logger::close cannot self-join from active callback or worker")); + } + + Ticket target = 0; { - std::lock_guard lock(m_mutex); - to_flush = std::move(m_buffer); - m_buffer = {}; + std::lock_guard lock{m_mutex}; + m_stop_admission = true; + target = m_next_ticket; + if (options.drop_pending) { + while (!m_queue.empty()) { + auto item = std::move(m_queue.front()); + m_queue.pop_front(); + --m_queued_entries; + m_queued_bytes -= std::min(m_queued_bytes, item.bytes); + ++m_dropped_count; + mark_terminal_locked(item.ticket, TerminalOutcome::Dropped); + } + } + m_space_cv.notify_all(); + m_work_cv.notify_all(); + m_done_cv.notify_all(); } - // Call the virtual method outside the lock so derived classes can - // safely do blocking I/O, acquire their own mutexes, etc. - if (!to_flush.empty()) { - on_flush(to_flush); + + auto rep = flush_through( + target, FlushOptions{FlushDurability::BufferFlush, options.async}); + if (!rep) { + return rep; } + if (!rep->timed_out && !rep->cancelled) { + m_stop_worker.store(true, std::memory_order_release); + m_work_cv.notify_all(); + if (m_worker.joinable()) { + m_worker.join(); + } + std::lock_guard lock{m_mutex}; + m_closed = true; + } + return rep; + } + + void Logger::request_close() noexcept + { + std::lock_guard lock{m_mutex}; + m_stop_admission = true; + m_space_cv.notify_all(); + } + + void Logger::flush() { (void)flush_through(0, {}); } + + LoggerStats Logger::stats() const + { + std::lock_guard lock{m_mutex}; + return LoggerStats{ + .queued_entries = m_queued_entries, + .queued_bytes = m_queued_bytes, + .in_flight_entries = m_in_flight_entries, + .in_flight_bytes = m_in_flight_bytes, + .admitted = m_admitted_count, + .delivered = m_delivered_count, + .dropped = m_dropped_count, + .failed = m_failed_count, + .reentrant_dropped = + m_reentrant_dropped.load(std::memory_order_relaxed), + .completed_watermark = m_completed_watermark, + .quarantined = m_quarantined.load(std::memory_order_acquire), + .closed = m_closed}; + } + + bool Logger::is_quarantined() const noexcept + { + return m_quarantined.load(std::memory_order_acquire); + } + + std::string Logger::last_error_summary() const + { + std::lock_guard lock{m_mutex}; + return m_last_error; + } + + void Logger::reset_quarantine() noexcept + { + std::lock_guard lock{m_mutex}; + m_quarantined.store(false, std::memory_order_release); + m_last_error.clear(); + m_space_cv.notify_all(); + } + + Logger::ScopedContext Logger::push_scope(std::string name, + Level level, + std::source_location loc) noexcept + { + return ScopedContext(*this, std::move(name), level, loc); + } + + void Logger::scope(std::string_view name, + Level level, + std::source_location loc) + { + emit_scope_boundary(Kind::ScopeEnter, name, level, loc); + emit_scope_boundary( + Kind::ScopeExit, name, level, std::source_location{}); + } + + std::span Logger::current_scopes() noexcept + { + return s_scope_stack; + } + + Logger::Preset Logger::make_preset(Level level, std::string prefix) noexcept + { + return Preset(*this, level, std::move(prefix)); } void Logger::on_flush(std::span entries) @@ -249,23 +752,21 @@ namespace Void::Logging } } - // ============================================================================= - // Private — emit_scope_boundary - // ============================================================================= + Void::Result::Result Logger::sync_files() + { + return Void::Result::fail(make_log_error( + LogErrorCode::unsupported_capability, + "Logger sink does not support durable file syncing")); + } void Logger::emit_scope_boundary(Kind kind, std::string_view name, Level level, std::source_location loc) { - // Respect the configured minimum level for scope entries too. - { - 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, @@ -274,83 +775,87 @@ namespace Void::Logging .timestamp = std::chrono::system_clock::now(), .location = loc, .thread_id = std::this_thread::get_id(), - .scopes = s_scope_stack, // snapshot at boundary time + .scopes = s_scope_stack, .fields = {fields.begin(), fields.end()}, }; - - submit(std::move(entry)); + (void)try_submit(std::move(entry)); } - // ============================================================================= - // Private — submit - // ============================================================================= - - void Logger::submit(Entry entry) + void Logger::mark_terminal_locked(Ticket t, TerminalOutcome outcome) { - if (entry.level < m_level.load(std::memory_order_relaxed)) { - return; - } + m_pending_terminals.emplace(t, outcome); + advance_watermark_locked(); + } - switch (m_mode.load(std::memory_order_acquire)) { - case Mode::Async: - async_submit(std::move(entry)); - return; - - case Mode::Immediate: - // Virtual call outside any lock (see class documentation). - write(entry); - return; - - case Mode::Buffered: - { - std::vector batch; - { - std::lock_guard lock(m_mutex); - m_buffer.push_back(std::move(entry)); - if (m_buffer.size() >= m_buffer_capacity) { - batch = std::move(m_buffer); - m_buffer = {}; - m_buffer.reserve(m_buffer_capacity); - } - } - if (!batch.empty()) { - on_flush(batch); - } - return; - } + void Logger::advance_watermark_locked() + { + while (!m_pending_terminals.empty() && + m_pending_terminals.begin()->first == m_completed_watermark + 1) { + const auto [ticket, outcome] = *m_pending_terminals.begin(); + m_pending_terminals.erase(m_pending_terminals.begin()); + m_completed_watermark = ticket; + switch (outcome) { + case TerminalOutcome::Delivered: ++m_wm_delivered; break; + case TerminalOutcome::Dropped: ++m_wm_dropped; break; + case TerminalOutcome::Failed: ++m_wm_failed; break; + } } } - // ============================================================================= - // Private — async machinery - // ============================================================================= - - void Logger::async_submit(Entry entry) + void Logger::deliver_batch_unlocked( + std::vector& items, + bool stopping, + std::size_t total_bytes) { - start_worker(); - - switch (m_policy) { - case OverflowPolicy::Block: - // Wait for queue space; the worker releases one slot per - // popped entry. Nothing is ever dropped. - m_space.acquire(); - break; - - case OverflowPolicy::DropNewest: - if (!m_space.try_acquire()) { - return; // full — discard the incoming entry - } - break; - - case OverflowPolicy::DropOldest: - // Unbounded enqueue; the worker trims the oldest entries - // down to capacity when it falls behind. - break; + std::vector raw_entries; + raw_entries.reserve(items.size()); + for (const auto& item : items) { + raw_entries.push_back(item.entry); } - m_submitted.fetch_add(1, std::memory_order_release); - m_queue.push(std::move(entry)); - wake_worker(); + bool failed = false; + std::string err_summary; + if (!stopping && !m_quarantined.load(std::memory_order_acquire)) { + ActiveLoggerGuard guard{this}; + try { + on_flush(raw_entries); + } catch (const std::exception& e) { + failed = true; + err_summary = e.what(); + } catch (...) { + failed = true; + err_summary = "Unknown sink exception"; + } + } + + if (err_summary.size() > kMaxErrorSummaryBytes) { + err_summary.resize(kMaxErrorSummaryBytes); + } + + std::lock_guard lock{m_mutex}; + m_in_flight_entries -= std::min(m_in_flight_entries, items.size()); + m_in_flight_bytes -= std::min(m_in_flight_bytes, total_bytes); + + for (const auto& item : items) { + if (stopping) { + ++m_dropped_count; + mark_terminal_locked(item.ticket, TerminalOutcome::Dropped); + } else if (failed) { + ++m_failed_count; + mark_terminal_locked(item.ticket, TerminalOutcome::Failed); + } else { + ++m_delivered_count; + mark_terminal_locked(item.ticket, TerminalOutcome::Delivered); + } + } + if (failed) { + m_last_error = std::move(err_summary); + if (m_options.failure_policy == FailurePolicy::Quarantine) { + m_quarantined.store(true, std::memory_order_release); + } + } + m_space_cv.notify_all(); + m_done_cv.notify_all(); } void Logger::start_worker() @@ -364,78 +869,44 @@ namespace Void::Logging }); } - void Logger::wake_worker() noexcept - { - if (m_sleeping.exchange(false, std::memory_order_acq_rel)) { - m_wakeup.release(); - } - } - void Logger::worker_loop() { - std::vector batch; - const bool counts_space = m_policy != OverflowPolicy::DropOldest; + m_worker_id.store(std::this_thread::get_id(), std::memory_order_release); + std::vector batch; for (;;) { - // Drain everything currently queued. - while (auto e = m_queue.try_pop()) { - batch.push_back(std::move(*e)); - if (counts_space) { - m_space.release(); + std::size_t batch_bytes = 0; + bool stopping = false; + { + std::unique_lock lock{m_mutex}; + m_work_cv.wait(lock, [this] { + return !m_queue.empty() || + m_stop_worker.load(std::memory_order_acquire); + }); + stopping = m_stop_worker.load(std::memory_order_acquire); + if (m_queue.empty() && stopping) { + return; } - } - - if (!batch.empty()) { - const bool stopping = m_stop.load(std::memory_order_acquire); - - std::size_t dropped = 0; - if (m_policy == OverflowPolicy::DropOldest && - batch.size() > m_async_capacity) { - dropped = batch.size() - m_async_capacity; - batch.erase(batch.begin(), - batch.begin() + - static_cast(dropped)); + const std::size_t max_n = m_options.limits.batch_entries; + const std::size_t max_b = m_options.limits.batch_bytes; + while (!m_queue.empty() && batch.size() < max_n) { + const std::size_t item_bytes = m_queue.front().bytes; + if (!batch.empty() && batch_bytes + item_bytes > max_b) { + break; + } + batch_bytes += item_bytes; + batch.push_back(std::move(m_queue.front())); + m_queue.pop_front(); } - - // After stop the derived class may already be destroyed — - // never touch the virtuals; just account and discard. - if (!stopping) { - on_flush(batch); - } - m_completed.fetch_add(batch.size() + dropped, - std::memory_order_release); - m_completed.notify_all(); - batch.clear(); - continue; // re-poll before considering a park + m_queued_entries -= std::min(m_queued_entries, batch.size()); + m_queued_bytes -= std::min(m_queued_bytes, batch_bytes); + m_in_flight_entries += batch.size(); + m_in_flight_bytes += batch_bytes; } - if (m_stop.load(std::memory_order_acquire)) { - return; - } - - // Park. Producers re-check m_sleeping after pushing, so a wake - // between the store and acquire below cannot be missed. - m_sleeping.store(true, std::memory_order_release); - if (!m_queue.empty() || m_stop.load(std::memory_order_acquire)) { - m_sleeping.store(false, std::memory_order_release); - continue; - } - m_wakeup.acquire(); - m_sleeping.store(false, std::memory_order_release); + deliver_batch_unlocked(batch, stopping, batch_bytes); + batch.clear(); } } - void Logger::drain_async() - { - const auto target = m_submitted.load(std::memory_order_acquire); - for (;;) { - const auto done = m_completed.load(std::memory_order_acquire); - if (done >= target) { - return; - } - wake_worker(); - m_completed.wait(done, std::memory_order_acquire); - } - } - -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/src/Log/RollingFile.cpp b/src/Log/RollingFile.cpp index 5fdb532..58ee073 100644 --- a/src/Log/RollingFile.cpp +++ b/src/Log/RollingFile.cpp @@ -1,9 +1,18 @@ #include +#include + +#ifndef _WIN32 +#include +#include +#include +#include +#endif #include #include #include #include +#include #include #include #include @@ -46,25 +55,46 @@ namespace Void::Logging::Detail bool RollingFile::open() { std::error_code ec; - if (m_path.has_parent_path()) { + if (m_opt.create_directories && m_path.has_parent_path()) { std::filesystem::create_directories(m_path.parent_path(), ec); + if (ec) { + return false; + } } if (std::filesystem::exists(m_path, ec)) { m_current_bytes = static_cast( std::filesystem::file_size(m_path, ec)); + } else { + m_current_bytes = 0; } + m_file.clear(); m_file.open(m_path, std::ios::app); m_creationTime = std::chrono::system_clock::now(); return m_file.is_open(); } + bool RollingFile::reopen() + { + if (m_file.is_open()) { + m_file.flush(); + m_file.close(); + } + m_file.clear(); + return open(); + } + void RollingFile::write(std::string_view line) { if (!m_file.is_open()) { - return; + throw std::runtime_error(std::format( + "RollingFile: stream closed for '{}'", m_path.string())); } m_file.write(line.data(), static_cast(line.size())); m_file.put('\n'); + if (!m_file.good()) { + throw std::runtime_error(std::format( + "RollingFile: write failure on '{}'", m_path.string())); + } m_current_bytes += line.size() + 1; if (m_self_rotate && m_current_bytes >= m_opt.max_bytes) { rotate(); @@ -73,9 +103,46 @@ namespace Void::Logging::Detail void RollingFile::flush() { - if (m_file.is_open()) { - m_file.flush(); + if (!m_file.is_open()) { + return; } + m_file.flush(); + if (!m_file.good()) { + throw std::runtime_error(std::format( + "RollingFile: flush failure on '{}'", m_path.string())); + } + } + + Void::Result::Result RollingFile::sync() + { + try { + flush(); + } catch (const std::exception& e) { + return Void::Result::fail( + make_log_error(LogErrorCode::io_error, e.what())); + } +#ifndef _WIN32 + const int fd = ::open(m_path.c_str(), O_RDONLY); + if (fd < 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("RollingFile::sync open('{}') failed: {}", + m_path.string(), std::strerror(errno)))); + } + int rc = 0; + do { + rc = ::fsync(fd); + } while (rc < 0 && errno == EINTR); + const int saved_err = errno; + ::close(fd); + if (rc < 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("RollingFile::sync fsync('{}') failed: {}", + m_path.string(), std::strerror(saved_err)))); + } +#endif + return {}; } void RollingFile::rotate() @@ -85,12 +152,15 @@ namespace Void::Logging::Detail std::error_code ec; if (m_opt.max_files > 0) { - // Create the history/ subdirectory next to the original file auto parent = m_path.parent_path(); auto history_dir = parent / "history"; std::filesystem::create_directories(history_dir, ec); + if (ec) { + throw std::runtime_error(std::format( + "RollingFile: cannot create history dir '{}'", + history_dir.string())); + } - // Build new name: -. auto stem = m_path.stem(); auto ext = m_path.extension(); auto new_filename = stem.string() + "-" + @@ -98,19 +168,24 @@ namespace Void::Logging::Detail auto archived = history_dir / new_filename; std::filesystem::rename(m_path, archived, ec); - prune_archives(); // now looks inside history/ + prune_archives(); } else { std::filesystem::remove(m_path, ec); } + m_file.clear(); m_file.open(m_path, std::ios::trunc); + if (!m_file.is_open()) { + throw std::runtime_error(std::format( + "RollingFile: reopen after rotate failed on '{}'", + m_path.string())); + } m_current_bytes = 0; m_creationTime = m_rotationTime; } void RollingFile::prune_archives() { - // Prune only from the history/ subdirectory auto parent = m_path.parent_path(); auto history_dir = parent / "history"; if (!std::filesystem::exists(history_dir)) { @@ -132,7 +207,7 @@ namespace Void::Logging::Detail } } } catch (const std::filesystem::filesystem_error&) { - return; // best-effort pruning only + return; } std::sort(archives.begin(), archives.end()); @@ -150,9 +225,10 @@ namespace Void::Logging::Detail std::filesystem::create_directories(dir, ec); std::filesystem::rename(m_path, dir / m_path.filename(), ec); + m_file.clear(); m_file.open(m_path, std::ios::trunc); m_current_bytes = 0; m_creationTime = m_rotationTime; } -} // namespace Void::Logging::Detail +} // namespace Void::Logging::Detail \ No newline at end of file diff --git a/src/Log/RotatingFileLogger.cpp b/src/Log/RotatingFileLogger.cpp index 4c83657..3dec5f1 100644 --- a/src/Log/RotatingFileLogger.cpp +++ b/src/Log/RotatingFileLogger.cpp @@ -9,9 +9,23 @@ namespace Void::Logging RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path, Options options) - : Logger(options.mode, options.capacity, options.policy), m_path(path), - m_file(path, Detail::RollingFileOptions{options.max_bytes, - options.max_files}) + : Logger(LoggerOptions{ + .mode = options.mode, + .policy = options.policy, + .limits = DeliveryLimits{ + .entries = options.capacity > 0 ? options.capacity : 1, + .owned_bytes = std::max( + 8ULL * 1024ULL * 1024ULL, + (options.capacity > 0 ? options.capacity : 1) * 1024ULL), + .max_fields = 64, + .max_scopes = 64}, + .failure_policy = FailurePolicy::Quarantine, + .suppress_reentrancy = false}), + m_path(path), + m_file(path, + Detail::RollingFileOptions{options.max_bytes, + options.max_files, + options.create_directories}) { if (!m_file.open()) { throw std::runtime_error(std::format( @@ -29,12 +43,35 @@ namespace Void::Logging return Void::Result::ok( std::make_unique(path, options)); } catch (const std::exception& e) { - return Void::Result::fail(std::string{e.what()}); + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, std::string{e.what()})); } } RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); } + Void::Result::Result RotatingFileLogger::reopen() + { + flush(); + if (!m_file.reopen()) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, + std::format("RotatingFileLogger::reopen failed for '{}'", + m_path.string()))); + } + return {}; + } + + Void::Result::Result RotatingFileLogger::sync_files() + { + flush(); + if (is_quarantined()) { + return Void::Result::fail(make_log_error( + LogErrorCode::io_error, last_error_summary())); + } + return m_file.sync(); + } + void RotatingFileLogger::write(const Entry& entry) { append(entry); @@ -52,11 +89,19 @@ namespace Void::Logging void RotatingFileLogger::append(const Entry& entry) { if (m_formatter) { - m_file.write(m_formatter->format(entry)); + auto bounded = format_bounded( + *m_formatter, + entry, + delivery_limits().max_format_scratch_bytes, + delivery_limits().truncate_oversize); + if (!bounded) { + throw std::runtime_error(bounded.error().message()); + } + m_file.write(*bounded); } else { m_file.write( std::format("[{}] {}", to_string(entry.level), entry.message)); } } -} // namespace Void::Logging +} // namespace Void::Logging \ No newline at end of file diff --git a/src/Log/module.cmake b/src/Log/module.cmake index 07e9a90..19533e8 100644 --- a/src/Log/module.cmake +++ b/src/Log/module.cmake @@ -1,5 +1,5 @@ void_add_module(Log - INTERNAL_DEPS Async Core Data Functional Configuration LogState + INTERNAL_DEPS Async Core Data Functional Memory Time LogState OPTIONAL_DEPS Stacktrace - EXCLUDE_HEADERS Void/Log/Log.hpp + EXCLUDE_HEADERS Void/Log/Log.hpp Void/Log/FromConfig.hpp ) diff --git a/src/LogConfig/FromConfig.cpp b/src/LogConfig/FromConfig.cpp new file mode 100644 index 0000000..73df396 --- /dev/null +++ b/src/LogConfig/FromConfig.cpp @@ -0,0 +1,449 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Logging +{ + + namespace + { + std::vector split_list(std::string_view csv) + { + std::vector out; + std::size_t start = 0; + while (start <= csv.size()) { + auto comma = csv.find(',', start); + if (comma == std::string_view::npos) { + comma = csv.size(); + } + auto item = csv.substr(start, comma - start); + while (!item.empty() && item.front() == ' ') { + item.remove_prefix(1); + } + while (!item.empty() && item.back() == ' ') { + item.remove_suffix(1); + } + if (!item.empty()) { + out.emplace_back(item); + } + start = comma + 1; + } + return out; + } + + std::optional parse_level(std::string_view name) + { + std::string lower; + for (const char c : name) { + lower += static_cast( + std::tolower(static_cast(c))); + } + if (lower == "trace") { + return Level::Trace; + } + if (lower == "debug") { + return Level::Debug; + } + if (lower == "info") { + return Level::Info; + } + if (lower == "warning" || lower == "warn") { + return Level::Warning; + } + if (lower == "error") { + return Level::Error; + } + if (lower == "fatal") { + return Level::Fatal; + } + if (lower == "disabled" || lower == "off") { + return Level::Disabled; + } + return std::nullopt; + } + + std::optional + parse_facade_level(std::string_view name) + { + const auto l = parse_level(name); + if (!l.has_value()) { + return std::nullopt; + } + switch (*l) { + case Level::Trace: return Void::Log::Level::Trace; + case Level::Debug: return Void::Log::Level::Debug; + case Level::Info: return Void::Log::Level::Info; + case Level::Warning: return Void::Log::Level::Warning; + case Level::Error: return Void::Log::Level::Error; + case Level::Fatal: return Void::Log::Level::Fatal; + case Level::Disabled: return Void::Log::Level::Disabled; + } + return std::nullopt; + } + + FieldFilter make_field_filter(const Configuration::Config& cfg) + { + FieldFilter f; + f.include = split_list(cfg.get_or("fields.include", "")); + f.exclude = split_list(cfg.get_or("fields.exclude", "")); + f.redact = split_list(cfg.get_or("fields.redact", "")); + return f; + } + + Void::Result::Result, + Void::Result::Error> + make_formatter(const Configuration::Config& cfg) + { + const auto format = cfg.get_or("format", "default"); + if (format == "default") { + return Void::Result::ok>(nullptr); + } + if (format == "pattern") { + auto fmt = std::make_shared(std::string{ + cfg.get_or("pattern", + "{time} [{level}] {scopes}{message}")}); + if (const auto col = cfg.get_as("color"); + col.has_value()) { + const auto parsed = cfg.get_as("color"); + if (!parsed.has_value()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: invalid bool " + "'{}' for color", + *col))); + } + if (*parsed) { + fmt->set_color_policy(ColorPolicy::defaults()); + } + } + fmt->set_field_filter(make_field_filter(cfg)); + return Void::Result::ok>( + std::move(fmt)); + } + if (format == "json") { + auto fmt = std::make_shared(); + fmt->set_field_filter(make_field_filter(cfg)); + return Void::Result::ok>( + std::move(fmt)); + } + if (format == "logfmt") { + auto fmt = std::make_shared(); + fmt->set_field_filter(make_field_filter(cfg)); + return Void::Result::ok>( + std::move(fmt)); + } + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: unknown format '{}'", + format))); + } + + struct Dispatch { + Mode mode = Mode::Async; + std::size_t capacity = 512; + OverflowPolicy policy = OverflowPolicy::DropNewest; + }; + + Void::Result::Result + make_dispatch(const Configuration::Config& cfg) + { + Dispatch d; + if (cfg.get_as("async").has_value()) { + const auto async_val = cfg.get_as("async"); + if (!async_val.has_value()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: invalid async bool")); + } + d.mode = *async_val ? Mode::Async : Mode::Immediate; + } + if (cfg.get_as("capacity").has_value()) { + const auto cap_val = cfg.get_as("capacity"); + if (!cap_val.has_value() || *cap_val == 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: capacity must be positive")); + } + d.capacity = *cap_val; + } + if (const auto overflow = cfg.get_as("overflow"); + overflow.has_value()) { + if (*overflow == "block") { + d.policy = OverflowPolicy::Block; + } else if (*overflow == "drop_newest") { + d.policy = OverflowPolicy::DropNewest; + } else if (*overflow == "drop_oldest") { + d.policy = OverflowPolicy::DropOldest; + } else { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: unknown overflow " + "policy '{}'", + *overflow))); + } + } + return d; + } + + Void::Result::Result + positive_size_or(const Configuration::Config& cfg, + std::string_view key, + std::size_t fallback) + { + if (!cfg.get_as(key).has_value()) { + return fallback; + } + const auto parsed = cfg.get_as(key); + if (!parsed.has_value() || *parsed == 0) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: '{}' must be > 0", + key))); + } + return *parsed; + } + } // namespace + + Void::Result::Result, Void::Result::Error> + from_config(const Configuration::Config& cfg, std::string_view prefix) + { + const auto sub = cfg.subtree(prefix); + + Level parsed_level = Level::Trace; + if (const auto raw_lvl = sub.get_as("level"); + raw_lvl.has_value()) { + const auto lvl = parse_level(*raw_lvl); + if (!lvl.has_value()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: unknown level '{}'", + *raw_lvl))); + } + parsed_level = *lvl; + } + + auto dispatch_res = make_dispatch(sub); + if (!dispatch_res.has_value()) { + return Void::Result::fail(std::move(dispatch_res).error()); + } + const auto dispatch = *dispatch_res; + + auto formatter_res = make_formatter(sub); + if (!formatter_res.has_value()) { + return Void::Result::fail(std::move(formatter_res).error()); + } + const auto formatter = std::move(*formatter_res); + + const LoggerOptions base_opts{ + .mode = dispatch.mode, + .policy = dispatch.policy, + .limits = DeliveryLimits{ + .entries = dispatch.capacity, + .owned_bytes = std::max( + 8ULL * 1024ULL * 1024ULL, dispatch.capacity * 1024ULL), + .max_fields = 64, + .max_scopes = 64}, + .failure_policy = FailurePolicy::Quarantine, + .suppress_reentrancy = true}; + + std::vector> sinks; + for (const auto& name : split_list(sub.get_or("sinks", "console"))) { + if (name == "console") { + const auto stream = sub.get_or("console.stream", "stderr"); + if (stream != "stderr" && stream != "stdout") { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: unknown " + "console.stream '{}'", + stream))); + } + auto sink = std::make_shared( + stream == "stdout" ? std::cout : std::cerr, dispatch.mode, + dispatch.capacity); + if (formatter) { + sink->set_formatter(formatter); + } + sinks.push_back(std::move(sink)); + } else if (name == "file") { + const auto path = sub.get_or("file.path"); + if (path.empty()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: sink 'file' needs file.path")); + } + auto sink = + FileLogger::open(std::filesystem::path{path}, base_opts); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + if (formatter) { + (*sink)->set_formatter(formatter); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "rotating") { + const auto path = sub.get_or("rotating.path"); + if (path.empty()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: sink 'rotating' needs " + "rotating.path")); + } + auto max_kb = positive_size_or(sub, "rotating.max_kb", 1024); + if (!max_kb) { + return Void::Result::fail(std::move(max_kb).error()); + } + auto max_files = + positive_size_or(sub, "rotating.max_files", 5); + if (!max_files) { + return Void::Result::fail(std::move(max_files).error()); + } + RotatingFileLogger::Options opt; + opt.max_bytes = *max_kb * 1024; + opt.max_files = *max_files; + opt.mode = dispatch.mode; + opt.capacity = dispatch.capacity; + opt.policy = dispatch.policy; + auto sink = + RotatingFileLogger::open(std::filesystem::path{path}, opt); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + if (formatter) { + (*sink)->set_formatter(formatter); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "split") { + const auto dir = sub.get_or("split.dir"); + if (dir.empty()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: sink 'split' needs split.dir")); + } + auto max_kb = positive_size_or(sub, "split.max_kb", 1024); + if (!max_kb) { + return Void::Result::fail(std::move(max_kb).error()); + } + auto max_files = positive_size_or(sub, "split.max_files", 5); + if (!max_files) { + return Void::Result::fail(std::move(max_files).error()); + } + SplitFileLogger::Options opt; + opt.combined = sub.get_or_as("split.combined", true); + opt.max_bytes = *max_kb * 1024; + opt.max_files = *max_files; + opt.mode = dispatch.mode; + opt.capacity = dispatch.capacity; + opt.policy = dispatch.policy; + auto sink = + SplitFileLogger::open(std::filesystem::path{dir}, opt); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + if (formatter) { + (*sink)->set_formatter(formatter); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "history") { + const auto path = sub.get_or("history.path"); + if (path.empty()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: sink 'history' needs " + "history.path")); + } + auto max_kb = positive_size_or(sub, "history.max_kb", 8192); + if (!max_kb) { + return Void::Result::fail(std::move(max_kb).error()); + } + auto max_files = + positive_size_or(sub, "history.max_files", 10); + if (!max_files) { + return Void::Result::fail(std::move(max_files).error()); + } + HistoryLogger::Options opt; + opt.max_bytes = *max_kb * 1024; + opt.max_files = *max_files; + opt.mode = dispatch.mode; + opt.capacity = dispatch.capacity; + opt.policy = dispatch.policy; + auto sink = + HistoryLogger::open(std::filesystem::path{path}, opt); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "syslog") { +#ifdef VOID_HAS_SYSLOG + const auto identity = sub.get_or("syslog.identity"); + if (identity.empty()) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: sink 'syslog' needs " + "syslog.identity")); + } + sinks.push_back(std::make_shared( + std::string{identity}, dispatch.mode, dispatch.capacity)); +#else + return Void::Result::fail(make_log_error( + LogErrorCode::unsupported_capability, + "Logging::from_config: syslog is not available on " + "this platform")); +#endif + } else { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + std::format("Logging::from_config: unknown sink '{}'", + name))); + } + } + + std::shared_ptr root; + if (sinks.empty()) { + root = std::make_shared(base_opts); + } else if (sinks.size() == 1) { + root = std::move(sinks.front()); + } else { + if (sinks.size() > kDefaultMaxFanoutChildren) { + return Void::Result::fail(make_log_error( + LogErrorCode::invalid_argument, + "Logging::from_config: too many sinks")); + } + root = std::make_shared(std::move(sinks)); + } + + root->set_level(parsed_level); + Void::Log::debug("Logging", "from_config: built logger tree"); + return Void::Result::ok(std::move(root)); + } + + void apply_facade_config(const Configuration::Config& cfg, + std::string_view prefix) + { + const auto sub = cfg.subtree(prefix); + if (const auto level = parse_facade_level(sub.get_or("level", "")); + level.has_value()) { + Void::Log::set_min_level(*level); + } + for (const auto& key : sub.subtree("module_levels").keys()) { + const auto value = sub.get_or(std::string{"module_levels."} + key); + if (const auto level = parse_facade_level(value); + level.has_value()) { + Void::Log::set_module_level(key, *level); + } + } + } + +} // namespace Void::Logging \ No newline at end of file diff --git a/src/LogConfig/module.cmake b/src/LogConfig/module.cmake new file mode 100644 index 0000000..0d8c848 --- /dev/null +++ b/src/LogConfig/module.cmake @@ -0,0 +1,4 @@ +void_add_module(LogConfig + INTERNAL_DEPS Log Configuration Functional + EXTRA_HEADERS Void/Log/FromConfig.hpp +) diff --git a/src/LogState/State.cpp b/src/LogState/State.cpp index 19f3b6c..d383678 100644 --- a/src/LogState/State.cpp +++ b/src/LogState/State.cpp @@ -12,4 +12,10 @@ namespace Void::Log::Detail static State s; return s; } -} // namespace Void::Log::Detail + + std::vector& active_registrations_tls() noexcept + { + static thread_local std::vector stack; + return stack; + } +} // namespace Void::Log::Detail \ No newline at end of file diff --git a/tests/package/InstalledComponents.cmake b/tests/package/InstalledComponents.cmake index a33ed33..e9c6905 100644 --- a/tests/package/InstalledComponents.cmake +++ b/tests/package/InstalledComponents.cmake @@ -131,6 +131,11 @@ if(_has_resilience) run_consumer(ResilienceOnly "${install_prefix}" "ResilienceOnly" ${_no_external_deps}) endif() +has_modules(_has_log Log Async Data Time Memory Functional Core LogState) +if(_has_log) + run_consumer(LogOnly "${install_prefix}" "LogOnly" ${_no_external_deps}) +endif() + # Foundation consumer with Core-formatting bridge and zero external packages. has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core) if(_has_foundation) diff --git a/tests/package/LogOnly/CMakeLists.txt b/tests/package/LogOnly/CMakeLists.txt new file mode 100644 index 0000000..9b80fd5 --- /dev/null +++ b/tests/package/LogOnly/CMakeLists.txt @@ -0,0 +1,10 @@ +cmake_minimum_required(VERSION 4.0) +project(VoidLogOnlyConsumer LANGUAGES CXX) + +find_package(Void CONFIG REQUIRED COMPONENTS Log) + +add_executable(void_log_only_consumer main.cpp) +target_link_libraries(void_log_only_consumer PRIVATE Void::Log) + +enable_testing() +add_test(NAME VoidLogOnlyConsumer COMMAND void_log_only_consumer) diff --git a/tests/package/LogOnly/main.cpp b/tests/package/LogOnly/main.cpp new file mode 100644 index 0000000..0294268 --- /dev/null +++ b/tests/package/LogOnly/main.cpp @@ -0,0 +1,26 @@ +#include +#include +#include + +#include + +int main() +{ + std::atomic seen{0}; + auto sink = std::make_shared( + [&](const Void::Logging::Entry&) { + seen.fetch_add(1, std::memory_order_relaxed); + }, + Void::Logging::LoggerOptions{ + .mode = Void::Logging::Mode::Immediate, + .policy = Void::Logging::OverflowPolicy::DropNewest}); + + const auto reg = Void::Log::register_sink(Void::Log::make_sink(sink), sink); + Void::Log::info("LogOnly", "hello consumer"); + const auto dr = Void::Log::detach_and_drain(reg); + const auto rep = sink->close({}); + return (dr == Void::Log::DrainResult::drained && rep.has_value() && + seen.load() == 1) + ? 0 + : 1; +} diff --git a/tests/standalone/Log/LogHardening.cpp b/tests/standalone/Log/LogHardening.cpp new file mode 100644 index 0000000..04477bf --- /dev/null +++ b/tests/standalone/Log/LogHardening.cpp @@ -0,0 +1,372 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +using namespace Void::Logging; +using namespace std::chrono_literals; +using Void::Testing::expect; +using Void::Testing::expect_eq; +using Void::Testing::require; + +struct FacadeGuard { + ~FacadeGuard() + { + (void)Void::Log::detach_and_drain(0); + Void::Log::set_emergency_handler(nullptr); + Void::Log::set_min_level(Void::Log::Level::Trace); + } +}; + +std::atomic g_emergency_calls{0}; +void record_emergency(std::string_view) noexcept +{ + g_emergency_calls.fetch_add(1, std::memory_order_relaxed); +} + +} // namespace + +Void::Testing::Test log_facade_reentrant_replace_drain_and_suppression() +{ + FacadeGuard guard; + g_emergency_calls.store(0, std::memory_order_relaxed); + Void::Log::set_emergency_handler(&record_emergency); + + const auto before_drops = Void::Log::reentrant_dropped(); + std::atomic destroyed{false}; + struct OwnerFlag { + std::atomic* flag; + ~OwnerFlag() { flag->store(true, std::memory_order_release); } + }; + auto owner = std::make_shared(&destroyed); + + std::mutex mu; + std::condition_variable cv; + bool in_cb = false; + bool release_cb = false; + std::atomic self_drain_blocked{false}; + std::atomic secondary_calls{0}; + + const auto id = Void::Log::register_sink( + [&](Void::Log::Level, + std::string_view, + std::string_view, + const std::source_location&) { + // Reentrant log into same registration is suppressed & routed to emergency hook. + Void::Log::info("LogHardening", "recursive call"); + + // Synchronous self-drain detects active registration -> would_deadlock. + if (Void::Log::detach_and_drain(0) == Void::Log::DrainResult::would_deadlock) { + self_drain_blocked.store(true, std::memory_order_release); + } + + // Reentrant sink replacement must NOT deadlock; old registration stays + // alive via Hook/ActiveRegistrationGuard until callback exits. + Void::Log::set_sink([&](auto, auto, auto, auto) { + secondary_calls.fetch_add(1, std::memory_order_relaxed); + }); + + { + std::unique_lock lock{mu}; + in_cb = true; + cv.notify_all(); + cv.wait(lock, [&] { return release_cb; }); + } + }, + owner); + owner.reset(); + + std::thread emitter{[&] { + Void::Log::info("LogHardening", "outer event"); + }}; + { + std::unique_lock lock{mu}; + cv.wait(lock, [&] { return in_cb; }); + } + + // Even after callback called set_sink(secondary), original owner must stay alive + // until detach_and_drain(id) finishes waiting on active_calls == 0. + std::atomic dr{Void::Log::DrainResult::not_found}; + std::atomic drain_done{false}; + std::thread drainer{[&] { + dr.store(Void::Log::detach_and_drain(id), std::memory_order_release); + drain_done.store(true, std::memory_order_release); + }}; + std::this_thread::sleep_for(10ms); + expect(!drain_done.load(std::memory_order_acquire)); + expect(!destroyed.load(std::memory_order_acquire)); + + { + std::lock_guard lock{mu}; + release_cb = true; + } + cv.notify_all(); + emitter.join(); + drainer.join(); + + expect(self_drain_blocked.load()); + expect(dr.load() == Void::Log::DrainResult::drained); + expect(destroyed.load(std::memory_order_acquire)); + expect(Void::Log::reentrant_dropped() > before_drops); + expect(g_emergency_calls.load() >= 1); + + Void::Log::info("LogHardening", "after replace"); + expect_eq(secondary_calls.load(), 1); +} + +Void::Testing::Test log_bounded_permits_drop_oldest_and_tickets() +{ + std::mutex mu; + std::condition_variable cv; + bool stalled = true; + std::atomic in_sink{false}; + std::vector delivered; + + LoggerOptions opt; + opt.mode = Mode::Async; + opt.policy = OverflowPolicy::DropOldest; + opt.limits.entries = 3; + opt.limits.batch_entries = 1; + opt.limits.owned_bytes = 64 * 1024; + opt.suppress_reentrancy = true; + + auto sink = std::make_shared( + [&](const Entry& e) { + in_sink.store(true, std::memory_order_release); + { + std::unique_lock lock{mu}; + cv.wait(lock, [&] { return !stalled; }); + } + delivered.push_back(e.message); + }, + opt); + + // 1st entry starts executing in worker immediately and occupies in-flight permit (1/3). + auto r1 = sink->try_submit(Entry{.level = Level::Info, .message = "first"}); + require(r1.has_value() && r1->state == SubmitState::Accepted); + while (!in_sink.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(1ms); + } + + // Queue 2 more -> now queued(2) + in_flight(1) == 3 (at capacity!). + auto r2 = sink->try_submit(Entry{.level = Level::Info, .message = "second"}); + auto r3 = sink->try_submit(Entry{.level = Level::Info, .message = "third"}); + auto r4 = sink->try_submit(Entry{.level = Level::Info, .message = "fourth"}); + require(r2.has_value() && r3.has_value() && r4.has_value()); + expect(r4->state == SubmitState::Accepted); + + // Total active (queued + in_flight) never exceeds capacity 3; "second" was evicted. + const auto st_stall = sink->stats(); + expect(st_stall.queued_entries + st_stall.in_flight_entries <= 3); + expect_eq(st_stall.dropped, std::uint64_t{1}); + + // Release stalled worker and verify contiguous watermark & report include evicted loss. + { + std::lock_guard lock{mu}; + stalled = false; + } + cv.notify_all(); + + auto rep = sink->flush_through(*r4->ticket, {}); + require(rep.has_value()); + expect_eq(rep->delivered, std::uint64_t{3}); + expect_eq(rep->dropped, std::uint64_t{1}); + expect_eq(rep->watermark, *r4->ticket); + expect_eq(delivered.size(), std::size_t{3}); + expect_eq(delivered[0], std::string{"first"}); + expect_eq(delivered[1], std::string{"third"}); + expect_eq(delivered[2], std::string{"fourth"}); + + // Non-file sink must report unsupported_capability for SyncFiles durability. + auto sync_res = sink->flush_through(0, FlushOptions{FlushDurability::SyncFiles, {}}); + expect(!sync_res.has_value()); + expect_eq(sync_res.error().code().value, + static_cast(LogErrorCode::unsupported_capability)); + + auto close_rep = sink->close({}); + require(close_rep.has_value()); + auto after_close = sink->try_submit(Entry{.level = Level::Info, .message = "late"}); + require(after_close.has_value()); + expect(after_close->state == SubmitState::Closed); +} + +Void::Testing::Test log_quarantine_reentrancy_and_block_cancel() +{ + int attempts = 0; + LoggerOptions qopt; + qopt.mode = Mode::Immediate; + qopt.failure_policy = FailurePolicy::Quarantine; + qopt.suppress_reentrancy = true; + + std::shared_ptr qsink; + bool trigger_reenter = true; + qsink = std::make_shared( + [&](const Entry&) { + ++attempts; + if (trigger_reenter) { + trigger_reenter = false; + auto sub = qsink->try_submit(Entry{.level = Level::Info, .message = "inner"}); + expect(sub.has_value() && sub->state == SubmitState::Dropped); + // Synchronous self-flush must return would_deadlock. + auto sf = qsink->flush_through(0, {}); + expect(!sf.has_value()); + expect_eq(sf.error().code().value, + static_cast(LogErrorCode::would_deadlock)); + } + throw std::runtime_error{"disk fault"}; + }, + qopt); + + auto r = qsink->try_submit(Entry{.level = Level::Error, .message = "fail"}); + require(r.has_value()); + expect(qsink->is_quarantined()); + expect(qsink->last_error_summary().find("disk fault") != std::string::npos); + expect_eq(qsink->stats().failed, std::uint64_t{1}); + expect_eq(qsink->stats().reentrant_dropped, std::uint64_t{1}); + + // Subsequent submissions fail with quarantined until operator resets quarantine. + auto blocked = qsink->try_submit(Entry{.level = Level::Error, .message = "next"}); + expect(!blocked.has_value()); + expect_eq(blocked.error().code().value, + static_cast(LogErrorCode::quarantined)); + + qsink->reset_quarantine(); + expect(!qsink->is_quarantined()); + + // Cancellable Block submit stops cleanly when stalled. + std::mutex mu; + std::condition_variable cv; + bool hold = true; + std::atomic entered{false}; + LoggerOptions bopt; + bopt.mode = Mode::Async; + bopt.policy = OverflowPolicy::Block; + bopt.limits.entries = 1; + bopt.limits.batch_entries = 1; + + CallbackLogger blocker{ + [&](const Entry&) { + entered.store(true, std::memory_order_release); + std::unique_lock lock{mu}; + cv.wait(lock, [&] { return !hold; }); + }, + bopt}; + expect(blocker.try_submit(Entry{.level = Level::Info, .message = "fill"})->state == + SubmitState::Accepted); + while (!entered.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(1ms); + } + + std::stop_source stop_src; + std::thread stopper{[&] { + std::this_thread::sleep_for(10ms); + stop_src.request_stop(); + }}; + auto cancelled = blocker.try_submit( + Entry{.level = Level::Info, .message = "wait"}, + Void::Async::OperationOptions{.stop = stop_src.get_token()}); + stopper.join(); + expect(!cancelled.has_value()); + expect_eq(cancelled.error().code().value, + static_cast(LogErrorCode::cancelled)); + + { + std::lock_guard lock{mu}; + hold = false; + } + cv.notify_all(); + expect(blocker.close({}).has_value()); +} + +Void::Testing::Test log_formatters_multilogger_and_file_sync_reopen() +{ + // 1. Logfmt escaping + redaction + format_bounded. + Entry e; + e.level = Level::Warning; + e.message = "line1\nline2\t\"q\""; + e.truncated = true; + e.fields = {{"secret", "s3cr3t"}, {"note", "a\nb\rc"}}; + + LogfmtFormatter logfmt; + logfmt.set_field_filter(FieldFilter{.redact = {"secret"}}); + const std::string line = logfmt.format(e); + expect(line.find("truncated=true") != std::string::npos); + expect(line.find("secret=\"[REDACTED]\"") != std::string::npos); + expect(line.find("s3cr3t") == std::string::npos); + expect(line.find("\\n") != std::string::npos); + expect(line.find("\\r") != std::string::npos); + expect(line.find("\\t") != std::string::npos); + + const auto too_big = format_bounded(logfmt, e, 16, false); + expect(!too_big.has_value()); + const auto trunc_ok = format_bounded(logfmt, e, 24, true); + require(trunc_ok.has_value()); + expect_eq(trunc_ok->size(), std::size_t{24}); + expect(trunc_ok->ends_with("...[truncated]")); + + // 2. MultiLogger fanout cap (8) + cycle rejection. + auto root = std::make_shared(); + auto child = std::make_shared(); + expect(root->try_add(child).has_value()); + auto self_cycle = child->try_add(root); + expect(!self_cycle.has_value()); + expect_eq(self_cycle.error().code().value, + static_cast(LogErrorCode::cycle_detected)); + for (int i = 0; i < 7; ++i) { + expect(root->try_add(std::make_shared()).has_value()); + } + auto ninth = root->try_add(std::make_shared()); + expect(!ninth.has_value()); + expect_eq(ninth.error().code().value, + static_cast(LogErrorCode::queue_full)); + + // 3. RotatingFileOptions::roadmap_defaults rejects missing dir + FileLogger sync/reopen. + const auto base = std::filesystem::temp_directory_path() / "void_log_hardening_test"; + std::filesystem::remove_all(base); + auto missing_rot = RotatingFileLogger::open( + base / "no_such_dir" / "app.log", + RotatingFileOptions::roadmap_defaults()); + expect(!missing_rot.has_value()); + + std::filesystem::create_directories(base); + const auto file_path = base / "durable.log"; + { + auto fl_res = FileLogger::open(file_path, LoggerOptions{.mode = Mode::Immediate}); + require(fl_res.has_value()); + auto& fl = *fl_res; + auto ticket = fl->try_submit(Entry{.level = Level::Info, .message = "before-reopen"}); + require(ticket.has_value() && ticket->ticket.has_value()); + auto synced = fl->flush_through(*ticket->ticket, FlushOptions{FlushDurability::SyncFiles, {}}); + expect(synced.has_value()); + + expect(fl->reopen().has_value()); + expect(fl->try_submit(Entry{.level = Level::Info, .message = "after-reopen"}).has_value()); + expect(fl->close({}).has_value()); + } + std::ifstream ifs{file_path}; + std::string content{(std::istreambuf_iterator(ifs)), {}}; + expect(content.find("before-reopen") != std::string::npos); + expect(content.find("after-reopen") != std::string::npos); + std::filesystem::remove_all(base); +} diff --git a/tests/standalone/Log/FromConfig.cpp b/tests/standalone/LogConfig/FromConfig.cpp similarity index 63% rename from tests/standalone/Log/FromConfig.cpp rename to tests/standalone/LogConfig/FromConfig.cpp index 069c8e7..936e914 100644 --- a/tests/standalone/Log/FromConfig.cpp +++ b/tests/standalone/LogConfig/FromConfig.cpp @@ -15,11 +15,10 @@ using Void::Configuration::Config; Void::Testing::Test from_config_defaults_to_console() { - Config cfg; // empty: console sink, trace level, async + Config cfg; const auto logger = Void::Logging::from_config(cfg); Void::Testing::expect(logger.has_value()); - Void::Testing::expect((*logger)->mode() == - Void::Logging::Mode::Async); + Void::Testing::expect((*logger)->mode() == Void::Logging::Mode::Async); } Void::Testing::Test from_config_builds_multi_sink_tree() @@ -33,17 +32,14 @@ Void::Testing::Test from_config_builds_multi_sink_tree() const auto logger = Void::Logging::from_config(cfg); Void::Testing::expect(logger.has_value()); - Void::Testing::expect((*logger)->mode() == - Void::Logging::Mode::Immediate); - Void::Testing::expect((*logger)->level() == - Void::Logging::Level::Warning); + Void::Testing::expect((*logger)->mode() == Void::Logging::Mode::Immediate); + Void::Testing::expect((*logger)->level() == Void::Logging::Level::Warning); (*logger)->warning("to both sinks"); (*logger)->flush(); std::ifstream f(tmp.path() / "a.log"); std::string content((std::istreambuf_iterator(f)), {}); - Void::Testing::expect(content.find("to both sinks") != - std::string::npos); + Void::Testing::expect(content.find("to both sinks") != std::string::npos); } Void::Testing::Test from_config_split_and_history_sinks() @@ -62,13 +58,11 @@ Void::Testing::Test from_config_split_and_history_sinks() std::ifstream err(tmp.path() / "split" / "error.log"); std::string err_content((std::istreambuf_iterator(err)), {}); - Void::Testing::expect(err_content.find("split me") != - std::string::npos); + Void::Testing::expect(err_content.find("split me") != std::string::npos); std::ifstream hist(tmp.path() / "history.jsonl"); std::string hist_content((std::istreambuf_iterator(hist)), {}); - Void::Testing::expect(hist_content.find("split me") != - std::string::npos); + Void::Testing::expect(hist_content.find("split me") != std::string::npos); } Void::Testing::Test from_config_json_format_applies() @@ -78,11 +72,15 @@ Void::Testing::Test from_config_json_format_applies() cfg.set("log.sinks", "file"); cfg.set("log.file.path", (tmp.path() / "j.log").string()); cfg.set("log.format", "json"); + cfg.set("log.fields.redact", "token"); cfg.set("log.async", "false"); const auto logger = Void::Logging::from_config(cfg); Void::Testing::expect(logger.has_value()); - (*logger)->info("structured"); + { + Void::Logging::FieldScope fs{"token", "top-secret"}; + (*logger)->info("structured"); + } (*logger)->flush(); std::ifstream f(tmp.path() / "j.log"); @@ -90,6 +88,8 @@ Void::Testing::Test from_config_json_format_applies() std::getline(f, line); Void::Testing::expect(line.find("\"message\":\"structured\"") != std::string::npos); + Void::Testing::expect(line.find("top-secret") == std::string::npos); + Void::Testing::expect(line.find("[REDACTED]") != std::string::npos); } Void::Testing::Test from_config_missing_file_path_is_error() @@ -106,6 +106,38 @@ Void::Testing::Test from_config_unknown_sink_is_error() Void::Testing::expect(!Void::Logging::from_config(cfg).has_value()); } +Void::Testing::Test from_config_rejects_invalid_values() +{ + { + Config cfg; + cfg.set("log.level", "loud"); + Void::Testing::expect(!Void::Logging::from_config(cfg).has_value()); + } + { + Config cfg; + cfg.set("log.format", "xml"); + Void::Testing::expect(!Void::Logging::from_config(cfg).has_value()); + } + { + Config cfg; + cfg.set("log.overflow", "drop_middle"); + Void::Testing::expect(!Void::Logging::from_config(cfg).has_value()); + } + { + Config cfg; + cfg.set("log.capacity", "0"); + Void::Testing::expect(!Void::Logging::from_config(cfg).has_value()); + } + { + Void::FileSystem::TempDir tmp{"void_fromcfg_bad"}; + Config cfg; + cfg.set("log.sinks", "rotating"); + cfg.set("log.rotating.path", (tmp.path() / "r.log").string()); + cfg.set("log.rotating.max_kb", "0"); + Void::Testing::expect(!Void::Logging::from_config(cfg).has_value()); + } +} + Void::Testing::Test apply_facade_config_sets_levels() { struct Reset { @@ -122,9 +154,7 @@ Void::Testing::Test apply_facade_config_sets_levels() Void::Logging::apply_facade_config(cfg); Void::Log::set_sink([](auto, auto, auto, auto) {}); - Void::Testing::expect( - !Void::Log::enabled(Void::Log::Level::Info, "Other")); - Void::Testing::expect( - Void::Log::enabled(Void::Log::Level::Trace, "Fsm")); + Void::Testing::expect(!Void::Log::enabled(Void::Log::Level::Info, "Other")); + Void::Testing::expect(Void::Log::enabled(Void::Log::Level::Trace, "Fsm")); Void::Log::set_sink({}); }