feat(Log): harden LogState facade, bounded Logger delivery/tickets/quarantine, file sync/reopen, redaction, and separate LogConfig (M-LOG-01..05)
This commit is contained in:
1 parent
18a623aa62
commit
a74a402938
23 files changed
+2656
-1197
No files matched your search
@@ -1,5 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
@@ -12,37 +14,12 @@ namespace Void::Logging::Detail
|
||||
struct RollingFileOptions {
|
||||
std::size_t max_bytes = 1024 * 1024;
|
||||
std::size_t max_files = 5;
|
||||
bool create_directories = true;
|
||||
};
|
||||
|
||||
/// Format a time point as a filesystem-safe, lexicographically (and
|
||||
/// therefore chronologically) sortable UTC timestamp:
|
||||
/// `YYYYMMDD-HHMMSS-ffffff` (microseconds).
|
||||
[[nodiscard]] std::string
|
||||
format_timestamp(std::chrono::system_clock::time_point tp);
|
||||
|
||||
/// A single append-only log file with size-based rotation. Not thread
|
||||
/// safe — each sink owns one and drives it from its single worker.
|
||||
///
|
||||
/// Two rotation modes, selected by the `self_rotate` constructor
|
||||
/// argument:
|
||||
///
|
||||
/// - self_rotate = true (default), "solo": write() rotates on its
|
||||
/// own once the file exceeds max_bytes. The live file is closed
|
||||
/// and renamed in place to `<name>-<rotation_time>` — same
|
||||
/// directory, no subfolder. At most max_files such archives are
|
||||
/// kept; the oldest (by name, which sorts chronologically) is
|
||||
/// deleted. With max_files == 0 nothing is kept — the file is
|
||||
/// just truncated.
|
||||
///
|
||||
/// - self_rotate = false, "grouped": write() only tracks size and
|
||||
/// never rotates by itself. The owner polls exceeds_limit()
|
||||
/// across a set of RollingFiles and, once any one of them crosses
|
||||
/// the threshold, calls snapshot_into(dir) on every file in that
|
||||
/// set so they all land — under their original names — in the
|
||||
/// same directory at the same moment (e.g. so several files can
|
||||
/// roll together into one shared `history/<creation_time>/`).
|
||||
/// max_files does not apply to this path: nothing is ever deleted,
|
||||
/// every snapshot is kept.
|
||||
class RollingFile
|
||||
{
|
||||
public:
|
||||
@@ -50,32 +27,18 @@ namespace Void::Logging::Detail
|
||||
RollingFile(std::filesystem::path path, RollingFileOptions opt,
|
||||
bool self_rotate = true);
|
||||
|
||||
/// Open for append (creating parent dirs). False on failure.
|
||||
[[nodiscard]] bool open();
|
||||
[[nodiscard]] bool reopen();
|
||||
|
||||
/// Append a line (a trailing '\n' is added). In solo mode,
|
||||
/// rotates automatically once max_bytes is exceeded; in
|
||||
/// grouped mode this only updates the byte count — the
|
||||
/// caller drives rotation via exceeds_limit()/snapshot_into().
|
||||
/// No-op if not open.
|
||||
void write(std::string_view line);
|
||||
|
||||
void flush();
|
||||
[[nodiscard]] Void::Result::Result<void> sync();
|
||||
|
||||
/// True once the current file has reached max_bytes. Meant
|
||||
/// for grouped (self_rotate == false) use, so an owner can
|
||||
/// check a whole set of files and decide when to roll them
|
||||
/// together.
|
||||
[[nodiscard]] bool exceeds_limit() const noexcept
|
||||
{
|
||||
return m_current_bytes >= m_opt.max_bytes;
|
||||
}
|
||||
|
||||
/// Move the live file — same name, unmodified — into `dir`
|
||||
/// (created if needed), then continue with a fresh file at
|
||||
/// path(). Ignores max_files; nothing is ever deleted here.
|
||||
/// Intended to be called on every file in a group so they
|
||||
/// land together.
|
||||
void snapshot_into(const std::filesystem::path& dir);
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept
|
||||
@@ -102,4 +65,4 @@ namespace Void::Logging::Detail
|
||||
std::chrono::time_point<std::chrono::system_clock> m_rotationTime;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging::Detail
|
||||
} // namespace Void::Logging::Detail
|
||||
@@ -11,14 +11,6 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Distinguishes regular messages from scope boundary markers.
|
||||
///
|
||||
/// Sinks may use Kind to render scope entries differently —
|
||||
/// e.g. with indentation, brackets, or a dedicated colour.
|
||||
///
|
||||
/// Message — a regular log record
|
||||
/// ScopeEnter — emitted when a named scope opens (scope() call)
|
||||
/// ScopeExit — emitted when a named scope closes (RAII destructor)
|
||||
enum class Kind { Message, ScopeEnter, ScopeExit };
|
||||
|
||||
/// A single, immutable log record produced by Logger and handed to
|
||||
@@ -44,18 +36,15 @@ namespace Void::Logging
|
||||
std::thread::id thread_id{std::this_thread::get_id()};
|
||||
|
||||
/// Frozen snapshot of the thread-local ScopedContext stack at log
|
||||
/// time. Ordered outermost → innermost (index 0 is the root
|
||||
/// scope). For ScopeEnter this already includes the new scope as
|
||||
/// the last element; for ScopeExit it reflects the stack *before*
|
||||
/// the pop.
|
||||
/// time.
|
||||
std::vector<std::string> scopes{};
|
||||
|
||||
/// Structured key/value fields attached to this entry — a frozen
|
||||
/// snapshot of the thread-local FieldScope stack at log time.
|
||||
/// Formatters expose them as custom pattern tokens
|
||||
/// (`{field:key}`) and in JSON/logfmt output. Later duplicate
|
||||
/// keys win.
|
||||
/// Structured key/value fields attached to this entry.
|
||||
std::vector<std::pair<std::string, std::string>> fields{};
|
||||
|
||||
/// True when explicit oversize-truncation policy clipped message,
|
||||
/// fields, scopes, or formatted payload.
|
||||
bool truncated{false};
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
@@ -12,21 +12,6 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Logger sink that appends formatted entries to a file on disk.
|
||||
///
|
||||
/// Defaults to Mode::Async — entries are queued lock-free and written
|
||||
/// in batches by the logger's worker thread (one ofstream flush per
|
||||
/// batch). The destructor flushes any remaining entries. Pass
|
||||
/// Mode::Immediate/Buffered to opt out of the worker thread.
|
||||
///
|
||||
/// Two construction paths:
|
||||
/// - `FileLogger::open(path)` returns
|
||||
/// `Result<unique_ptr<FileLogger>, Error>` and never throws —
|
||||
/// prefer this in code that already uses Void::Result for error
|
||||
/// plumbing.
|
||||
/// - The throwing constructor stays for callers that prefer
|
||||
/// exceptions; it throws std::runtime_error if the path cannot
|
||||
/// be opened for append.
|
||||
class FileLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
@@ -35,6 +20,9 @@ namespace Void::Logging
|
||||
Mode mode = Mode::Async,
|
||||
std::size_t capacity = 512);
|
||||
|
||||
explicit FileLogger(const std::filesystem::path& path,
|
||||
LoggerOptions options);
|
||||
|
||||
~FileLogger() noexcept override;
|
||||
|
||||
FileLogger(const FileLogger&) = delete;
|
||||
@@ -42,21 +30,30 @@ namespace Void::Logging
|
||||
FileLogger(FileLogger&&) = delete;
|
||||
FileLogger& operator=(FileLogger&&) = delete;
|
||||
|
||||
/// Non-throwing factory. On failure returns
|
||||
/// `Failure<Error>{Error{"FileLogger: cannot open '<path>'"}}`.
|
||||
[[nodiscard]] static Void::Result::
|
||||
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path,
|
||||
Mode mode = Mode::Async,
|
||||
std::size_t capacity = 512);
|
||||
|
||||
/// Install a formatter replacing the default "[Level] message"
|
||||
/// rendering. Call before logging starts.
|
||||
[[nodiscard]] static Void::Result::
|
||||
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path,
|
||||
LoggerOptions options);
|
||||
|
||||
void set_formatter(std::shared_ptr<const Formatter> formatter)
|
||||
{
|
||||
m_formatter = std::move(formatter);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> reopen();
|
||||
[[nodiscard]] Void::Result::Result<void> sync_files() override;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
void write(const Entry& entry) override;
|
||||
@@ -71,4 +68,4 @@ namespace Void::Logging
|
||||
std::shared_ptr<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
@@ -1,8 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
@@ -11,11 +13,6 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Renders one Entry into a single output line (no trailing newline —
|
||||
/// the sink appends its own record separator).
|
||||
///
|
||||
/// Formatters must be safe to share between sinks: format() is const
|
||||
/// and implementations hold no mutable state.
|
||||
class Formatter
|
||||
{
|
||||
public:
|
||||
@@ -26,8 +23,6 @@ namespace Void::Logging
|
||||
format(const Entry& entry) const = 0;
|
||||
};
|
||||
|
||||
// ── colour ────────────────────────────────────────────────────────────
|
||||
|
||||
enum class AnsiColor {
|
||||
Default,
|
||||
Black,
|
||||
@@ -48,99 +43,24 @@ namespace Void::Logging
|
||||
BrightWhite,
|
||||
};
|
||||
|
||||
/// Parse a colour name ("red", "bright_black", "cyan", ...). Returns
|
||||
/// AnsiColor::Default for unknown names.
|
||||
[[nodiscard]] AnsiColor parse_color(std::string_view name) noexcept;
|
||||
|
||||
/// SGR escape for a colour ("\x1b[31m"); empty for Default.
|
||||
[[nodiscard]] std::string_view ansi_code(AnsiColor color) noexcept;
|
||||
|
||||
inline constexpr std::string_view kAnsiReset = "\x1b[0m";
|
||||
|
||||
/// Colour configuration for a PatternFormatter. Disabled by default;
|
||||
/// ConsoleLogger turns it on when the stream is a colour-capable TTY.
|
||||
struct ColorPolicy {
|
||||
bool enabled = false;
|
||||
std::unordered_map<Level, AnsiColor> level_colors;
|
||||
std::unordered_map<std::string, AnsiColor> token_colors;
|
||||
|
||||
/// Sensible per-level defaults (Trace dim → Fatal bright magenta).
|
||||
[[nodiscard]] static ColorPolicy defaults();
|
||||
};
|
||||
|
||||
// ── PatternFormatter ──────────────────────────────────────────────────
|
||||
//
|
||||
// Placeholder pattern with per-token appearance and colour.
|
||||
//
|
||||
// {token} — substitute the token
|
||||
// {token:spec} — spec = [align][width][,colour]
|
||||
// align : '<' left (default), '>' right, '^'
|
||||
// centre width : decimal field width (padded with
|
||||
// spaces) colour: a name ("cyan") or "auto" (=
|
||||
// level colour)
|
||||
//
|
||||
// Built-in tokens: time, level, thread, scopes, message, file, line,
|
||||
// kind. An unknown token resolves against registered custom tokens
|
||||
// (register_token), then against Entry::fields by key, and otherwise
|
||||
// stays literal — so `{request_id:>8}` prints a structured field.
|
||||
//
|
||||
// Default pattern: "{time} [{level}] {scopes}{message}"
|
||||
class PatternFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
|
||||
explicit PatternFormatter(
|
||||
std::string pattern = "{time} [{level}] {scopes}{message}");
|
||||
|
||||
[[nodiscard]] std::string format(const Entry& entry) const override;
|
||||
|
||||
/// Add a custom token. `name` becomes usable as `{name}`.
|
||||
/// Overrides a built-in of the same name.
|
||||
void register_token(std::string name,
|
||||
std::function<std::string(const Entry&)>
|
||||
renderer);
|
||||
|
||||
void set_color_policy(ColorPolicy policy)
|
||||
{
|
||||
m_colors = std::move(policy);
|
||||
}
|
||||
|
||||
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
|
||||
{
|
||||
return m_colors;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
enum class Align { Left, Right, Center };
|
||||
enum class ColorMode { None, Auto, Fixed };
|
||||
|
||||
struct Segment {
|
||||
bool literal{true};
|
||||
std::string text; // literal text, or the token name
|
||||
Align align{Align::Left};
|
||||
std::size_t width{0};
|
||||
ColorMode color_mode{ColorMode::None};
|
||||
AnsiColor color{AnsiColor::Default};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string render_token(const Segment& seg,
|
||||
const Entry& entry) const;
|
||||
|
||||
std::vector<Segment> m_segments;
|
||||
std::unordered_map<std::string,
|
||||
std::function<std::string(const Entry&)>>
|
||||
m_custom;
|
||||
ColorPolicy m_colors;
|
||||
};
|
||||
|
||||
/// An allow/deny list applied to an entry's structured fields by the
|
||||
/// json/logfmt sinks. `include` empty means "all keys" (still subject to
|
||||
/// `exclude`); a non-empty `include` admits only those keys. `exclude`
|
||||
/// always wins.
|
||||
struct FieldFilter {
|
||||
std::vector<std::string> include;
|
||||
std::vector<std::string> exclude;
|
||||
std::vector<std::string> include{};
|
||||
std::vector<std::string> exclude{};
|
||||
std::vector<std::string> redact{};
|
||||
std::string redaction_mask{"[REDACTED]"};
|
||||
|
||||
[[nodiscard]] bool allows(std::string_view key) const
|
||||
{
|
||||
@@ -159,9 +79,68 @@ namespace Void::Logging
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_redacted(std::string_view key) const
|
||||
{
|
||||
for (const auto& r : redact) {
|
||||
if (r == key) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
class PatternFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
|
||||
explicit PatternFormatter(
|
||||
std::string pattern = "{time} [{level}] {scopes}{message}");
|
||||
|
||||
[[nodiscard]] std::string format(const Entry& entry) const override;
|
||||
|
||||
void register_token(std::string name,
|
||||
std::function<std::string(const Entry&)>
|
||||
renderer);
|
||||
|
||||
void set_color_policy(ColorPolicy policy)
|
||||
{
|
||||
m_colors = std::move(policy);
|
||||
}
|
||||
|
||||
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
|
||||
{
|
||||
return m_colors;
|
||||
}
|
||||
|
||||
void set_field_filter(FieldFilter f) { m_fields = std::move(f); }
|
||||
|
||||
private:
|
||||
|
||||
enum class Align { Left, Right, Center };
|
||||
enum class ColorMode { None, Auto, Fixed };
|
||||
|
||||
struct Segment {
|
||||
bool literal{true};
|
||||
std::string text;
|
||||
Align align{Align::Left};
|
||||
std::size_t width{0};
|
||||
ColorMode color_mode{ColorMode::None};
|
||||
AnsiColor color{AnsiColor::Default};
|
||||
};
|
||||
|
||||
[[nodiscard]] std::string render_token(const Segment& seg,
|
||||
const Entry& entry) const;
|
||||
|
||||
std::vector<Segment> m_segments;
|
||||
std::unordered_map<std::string,
|
||||
std::function<std::string(const Entry&)>>
|
||||
m_custom;
|
||||
ColorPolicy m_colors;
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
/// One compact JSON object per entry (includes fields when present).
|
||||
class JsonLinesFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
@@ -175,7 +154,6 @@ namespace Void::Logging
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
/// logfmt: time=... level=... thread=... msg="..." plus scopes/fields.
|
||||
class LogfmtFormatter final : public Formatter
|
||||
{
|
||||
public:
|
||||
@@ -189,15 +167,19 @@ namespace Void::Logging
|
||||
FieldFilter m_fields;
|
||||
};
|
||||
|
||||
[[nodiscard]] Void::Result::Result<std::string>
|
||||
format_bounded(const Formatter& formatter,
|
||||
const Entry& entry,
|
||||
std::size_t max_bytes = 64ULL * 1024ULL,
|
||||
bool truncate = false);
|
||||
|
||||
namespace FormatDetail
|
||||
{
|
||||
/// ISO-8601 UTC with milliseconds, e.g. "2026-06-12T10:30:00.123Z".
|
||||
[[nodiscard]] std::string
|
||||
iso8601(std::chrono::system_clock::time_point tp);
|
||||
|
||||
/// Dotted scope breadcrumb ("net.tls"); empty when no scopes.
|
||||
[[nodiscard]] std::string
|
||||
scope_breadcrumb(const std::vector<std::string>& scopes);
|
||||
} // namespace FormatDetail
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
+208
-53
@@ -1,8 +1,12 @@
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <concepts>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <shared_mutex>
|
||||
#include <source_location>
|
||||
@@ -11,6 +15,7 @@
|
||||
#include <type_traits>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// ── Void::Log — the emission facade
|
||||
// ─────────────────────────────────────────── Header-only apart from its
|
||||
@@ -18,18 +23,6 @@
|
||||
// once per process, so every module (including INTERFACE libraries) can log by
|
||||
// linking only that. The full sink framework lives in Void::Logging
|
||||
// (Logger.hpp); bridge with Void/Log/LoggingAdapter.hpp.
|
||||
//
|
||||
// Integration contract:
|
||||
// * No sink installed (the default) — every call is a single relaxed
|
||||
// atomic load; format arguments are NOT formatted. This is the
|
||||
// "no logging at all" path.
|
||||
// * set_sink(...) routes everything to any callable — your own logging
|
||||
// library plugs in here.
|
||||
// * set_min_level(Level::Disabled) silences without removing the sink.
|
||||
// * Per-module overrides: set_module_level("Fsm", Level::Trace).
|
||||
//
|
||||
// The API is deliberately macro-free: leveled function templates take a
|
||||
// std::format_string and only format after the level/sink gate passes.
|
||||
|
||||
namespace Void::Log
|
||||
{
|
||||
@@ -44,23 +37,24 @@ namespace Void::Log
|
||||
Disabled
|
||||
};
|
||||
|
||||
/// Signature for any log consumer. Four arguments:
|
||||
/// level — severity of the event
|
||||
/// module — short library-internal label (e.g. "System.Process")
|
||||
/// message — human-readable description
|
||||
/// location — the call site that emitted the event (file/line/function)
|
||||
/// Signature for any log consumer.
|
||||
using Sink =
|
||||
std::function<void(Level level, std::string_view module,
|
||||
std::string_view message,
|
||||
const std::source_location& location)>;
|
||||
|
||||
using RegistrationId = std::uint64_t;
|
||||
|
||||
enum class DrainResult : std::uint8_t {
|
||||
drained = 0,
|
||||
not_found,
|
||||
would_deadlock
|
||||
};
|
||||
|
||||
using EmergencyHandler = void (*)(std::string_view message) noexcept;
|
||||
|
||||
namespace Detail
|
||||
{
|
||||
// std::source_location cannot follow a variadic pack in a parameter
|
||||
// list, so this wrapper captures the format string together with the
|
||||
// caller's source location in its (consteval) constructor.
|
||||
// std::type_identity_t<Args>... keeps Args non-deduced here, so they
|
||||
// are deduced solely from the trailing argument pack.
|
||||
template <typename... Args> struct FmtLoc {
|
||||
std::format_string<Args...> fmt;
|
||||
std::source_location location;
|
||||
@@ -74,36 +68,176 @@ namespace Void::Log
|
||||
}
|
||||
};
|
||||
|
||||
struct SinkRegistration {
|
||||
RegistrationId id{0};
|
||||
Sink sink{};
|
||||
std::shared_ptr<const void> owner{};
|
||||
std::atomic<bool> detached{false};
|
||||
std::atomic<std::size_t> active_calls{0};
|
||||
std::mutex drain_mutex;
|
||||
std::condition_variable drain_cv;
|
||||
};
|
||||
|
||||
struct State {
|
||||
// Fast-path gates (checked before any locking or formatting).
|
||||
std::atomic<bool> has_sink{false};
|
||||
std::atomic<Level> min_level{Level::Trace};
|
||||
std::atomic<bool> has_module_levels{false};
|
||||
std::atomic<std::uint64_t> reentrant_dropped{0};
|
||||
std::atomic<EmergencyHandler> emergency_handler{nullptr};
|
||||
|
||||
// Slow path.
|
||||
Sink sink;
|
||||
// Slow path (registration is immutable after creation;
|
||||
// invoked and destroyed strictly outside `mutex`).
|
||||
std::shared_ptr<SinkRegistration> registration{};
|
||||
RegistrationId next_id{0};
|
||||
std::unordered_map<RegistrationId, std::weak_ptr<SinkRegistration>> known;
|
||||
std::unordered_map<std::string, Level> module_levels;
|
||||
std::shared_mutex mutex;
|
||||
};
|
||||
|
||||
// The process's one State, defined in Void::LogState (a static in an
|
||||
// inline function would be one per DLL on Windows).
|
||||
inline constexpr std::size_t kMaxNestedFacadeSinks = 8;
|
||||
|
||||
// Process-wide singleton accessors defined in Void::LogState.
|
||||
State& state();
|
||||
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept;
|
||||
|
||||
struct ActiveRegistrationGuard {
|
||||
std::shared_ptr<SinkRegistration> reg;
|
||||
std::vector<const SinkRegistration*>& stack;
|
||||
|
||||
ActiveRegistrationGuard(std::shared_ptr<SinkRegistration> r,
|
||||
std::vector<const SinkRegistration*>& st)
|
||||
: reg(std::move(r)), stack(st)
|
||||
{
|
||||
stack.push_back(reg.get());
|
||||
}
|
||||
|
||||
~ActiveRegistrationGuard() noexcept
|
||||
{
|
||||
if (!stack.empty()) {
|
||||
stack.pop_back();
|
||||
}
|
||||
if (reg->active_calls.fetch_sub(
|
||||
1, std::memory_order_acq_rel) == 1) {
|
||||
std::lock_guard lock{reg->drain_mutex};
|
||||
reg->drain_cv.notify_all();
|
||||
}
|
||||
}
|
||||
|
||||
ActiveRegistrationGuard(const ActiveRegistrationGuard&) = delete;
|
||||
ActiveRegistrationGuard&
|
||||
operator=(const ActiveRegistrationGuard&) = delete;
|
||||
};
|
||||
} // namespace Detail
|
||||
|
||||
/// Install the global sink. Any previously installed sink is replaced.
|
||||
/// Pass a default-constructed (empty) Sink to silence all output.
|
||||
/// Thread-safe: the new sink is visible to all threads after this returns.
|
||||
inline void set_sink(Sink sink)
|
||||
/// Install a sink alongside an optional lifetime-keepalive owner and return
|
||||
/// its registration ID for explicit detach_and_drain().
|
||||
inline RegistrationId
|
||||
register_sink(Sink sink, std::shared_ptr<const void> owner = {})
|
||||
{
|
||||
auto& s = Detail::state();
|
||||
std::unique_lock lock{s.mutex};
|
||||
s.sink = std::move(sink);
|
||||
s.has_sink.store(static_cast<bool>(s.sink), std::memory_order_release);
|
||||
std::shared_ptr<Detail::SinkRegistration> prev;
|
||||
RegistrationId id = 0;
|
||||
|
||||
if (sink) {
|
||||
auto next = std::make_shared<Detail::SinkRegistration>();
|
||||
next->sink = std::move(sink);
|
||||
next->owner = std::move(owner);
|
||||
std::unique_lock lock{s.mutex};
|
||||
id = ++s.next_id;
|
||||
next->id = id;
|
||||
s.known.emplace(id, next);
|
||||
for (auto it = s.known.begin(); it != s.known.end();) {
|
||||
if (it->second.expired()) {
|
||||
it = s.known.erase(it);
|
||||
} else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
prev = std::exchange(s.registration, std::move(next));
|
||||
if (prev) {
|
||||
prev->detached.store(true, std::memory_order_release);
|
||||
}
|
||||
s.has_sink.store(true, std::memory_order_release);
|
||||
} else {
|
||||
std::unique_lock lock{s.mutex};
|
||||
prev = std::exchange(s.registration, nullptr);
|
||||
if (prev) {
|
||||
prev->detached.store(true, std::memory_order_release);
|
||||
}
|
||||
s.has_sink.store(false, std::memory_order_release);
|
||||
}
|
||||
|
||||
// Destroy previous callback/owner outside s.mutex.
|
||||
prev.reset();
|
||||
return id;
|
||||
}
|
||||
|
||||
/// Install the global sink. Any previously installed sink is replaced
|
||||
/// outside the facade lock (does not block waiting for in-flight calls).
|
||||
inline void set_sink(Sink sink)
|
||||
{
|
||||
(void)register_sink(std::move(sink), {});
|
||||
}
|
||||
|
||||
/// Detach a registered sink (or active sink when id == 0) and wait until
|
||||
/// all already-admitted invocations using that registration complete.
|
||||
/// Returns would_deadlock if called synchronously from that registration's
|
||||
/// own active callback.
|
||||
[[nodiscard]] inline DrainResult detach_and_drain(RegistrationId id = 0)
|
||||
{
|
||||
auto& s = Detail::state();
|
||||
std::shared_ptr<Detail::SinkRegistration> target;
|
||||
{
|
||||
std::unique_lock lock{s.mutex};
|
||||
if (id == 0) {
|
||||
target = s.registration;
|
||||
} else if (s.registration && s.registration->id == id) {
|
||||
target = s.registration;
|
||||
} else if (const auto it = s.known.find(id); it != s.known.end()) {
|
||||
target = it->second.lock();
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
return DrainResult::not_found;
|
||||
}
|
||||
|
||||
const auto& active = Detail::active_registrations_tls();
|
||||
for (const auto* entry : active) {
|
||||
if (entry == target.get()) {
|
||||
return DrainResult::would_deadlock;
|
||||
}
|
||||
}
|
||||
|
||||
target->detached.store(true, std::memory_order_release);
|
||||
if (target == s.registration) {
|
||||
s.registration.reset();
|
||||
s.has_sink.store(false, std::memory_order_release);
|
||||
}
|
||||
s.known.erase(target->id);
|
||||
}
|
||||
|
||||
{
|
||||
std::unique_lock drain_lock{target->drain_mutex};
|
||||
target->drain_cv.wait(drain_lock, [&target] {
|
||||
return target->active_calls.load(std::memory_order_acquire) == 0;
|
||||
});
|
||||
}
|
||||
target.reset();
|
||||
return DrainResult::drained;
|
||||
}
|
||||
|
||||
[[nodiscard]] inline std::uint64_t reentrant_dropped() noexcept
|
||||
{
|
||||
return Detail::state().reentrant_dropped.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
inline void set_emergency_handler(EmergencyHandler handler) noexcept
|
||||
{
|
||||
Detail::state().emergency_handler.store(
|
||||
handler, std::memory_order_release);
|
||||
}
|
||||
|
||||
/// Global minimum level. Events below it are discarded before
|
||||
/// formatting. Default: Trace (everything passes; the sink filters).
|
||||
inline void set_min_level(Level level) noexcept
|
||||
{
|
||||
Detail::state().min_level.store(level, std::memory_order_relaxed);
|
||||
@@ -114,8 +248,6 @@ namespace Void::Log
|
||||
return Detail::state().min_level.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/// Per-module minimum level override (exact label match). Overrides take
|
||||
/// precedence over the global minimum — they can both raise and lower it.
|
||||
inline void set_module_level(std::string_view module, Level level)
|
||||
{
|
||||
auto& s = Detail::state();
|
||||
@@ -124,7 +256,6 @@ namespace Void::Log
|
||||
s.has_module_levels.store(true, std::memory_order_release);
|
||||
}
|
||||
|
||||
/// Remove a per-module override.
|
||||
inline void clear_module_level(std::string_view module)
|
||||
{
|
||||
auto& s = Detail::state();
|
||||
@@ -134,7 +265,6 @@ namespace Void::Log
|
||||
std::memory_order_release);
|
||||
}
|
||||
|
||||
/// Would an event at `level` from `module` currently be emitted?
|
||||
[[nodiscard]] inline bool enabled(Level level, std::string_view module)
|
||||
{
|
||||
auto& s = Detail::state();
|
||||
@@ -154,15 +284,8 @@ namespace Void::Log
|
||||
return level >= s.min_level.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
/// Emit one pre-formatted log event through the global sink.
|
||||
/// No-op (zero allocation) when disabled.
|
||||
namespace Detail
|
||||
{
|
||||
// Single, non-overloaded dispatch to the sink. The formatted paths
|
||||
// must forward through this rather than through log() itself: a
|
||||
// log(level, module, std::string, source_location) call would also
|
||||
// match the variadic log() overload (deducing source_location as a
|
||||
// format argument) and fail in FmtLoc's consteval constructor.
|
||||
inline void emit(Level level, std::string_view module,
|
||||
std::string_view message,
|
||||
const std::source_location& location)
|
||||
@@ -171,10 +294,45 @@ namespace Void::Log
|
||||
if (!::Void::Log::enabled(level, module)) {
|
||||
return;
|
||||
}
|
||||
std::shared_lock lock{s.mutex};
|
||||
if (s.sink) {
|
||||
s.sink(level, module, message, location);
|
||||
|
||||
std::shared_ptr<SinkRegistration> reg;
|
||||
bool reentrant = false;
|
||||
{
|
||||
std::shared_lock lock{s.mutex};
|
||||
reg = s.registration;
|
||||
if (!reg || reg->detached.load(std::memory_order_acquire) ||
|
||||
!reg->sink) {
|
||||
return;
|
||||
}
|
||||
const auto& active = active_registrations_tls();
|
||||
if (active.size() >= kMaxNestedFacadeSinks) {
|
||||
reentrant = true;
|
||||
} else {
|
||||
for (const auto* entry : active) {
|
||||
if (entry == reg.get()) {
|
||||
reentrant = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!reentrant) {
|
||||
reg->active_calls.fetch_add(1, std::memory_order_acq_rel);
|
||||
}
|
||||
}
|
||||
|
||||
if (reentrant) {
|
||||
s.reentrant_dropped.fetch_add(1, std::memory_order_relaxed);
|
||||
if (const auto eh =
|
||||
s.emergency_handler.load(std::memory_order_acquire);
|
||||
eh != nullptr) {
|
||||
eh(message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
ActiveRegistrationGuard guard{
|
||||
std::move(reg), active_registrations_tls()};
|
||||
guard.reg->sink(level, module, message, location);
|
||||
}
|
||||
} // namespace Detail
|
||||
|
||||
@@ -186,9 +344,6 @@ namespace Void::Log
|
||||
Detail::emit(level, module, message, location);
|
||||
}
|
||||
|
||||
/// Leveled, lazily-formatted emission: arguments are formatted only
|
||||
/// after the level/sink gate passes. The call-site source location is
|
||||
/// captured transparently via FmtLoc.
|
||||
template <typename... Args>
|
||||
void log(Level level, std::string_view module,
|
||||
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
|
||||
@@ -243,4 +398,4 @@ namespace Void::Log
|
||||
log(Level::Fatal, module, fmt, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
} // namespace Void::Log
|
||||
} // namespace Void::Log
|
||||
+244
-263
@@ -1,18 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include "Void/Log/Field.hpp"
|
||||
#include <Void/Async/MpscQueue.hpp>
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Log/Entry.hpp>
|
||||
#include <Void/Log/Level.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <concepts>
|
||||
#include <condition_variable>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <deque>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <semaphore>
|
||||
#include <optional>
|
||||
#include <set>
|
||||
#include <source_location>
|
||||
#include <span>
|
||||
#include <string>
|
||||
@@ -23,104 +30,159 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Dispatch strategy.
|
||||
/// Async — (default) entries are queued lock-free and delivered in
|
||||
/// batches by a logger-owned worker thread.
|
||||
/// Immediate — write() is called inline on the logging thread.
|
||||
/// Buffered — entries accumulate and flush at capacity / on flush().
|
||||
enum class Mode { Async, Immediate, Buffered };
|
||||
|
||||
/// What happens in Async mode when pending entries reach capacity.
|
||||
/// Block — (default) the logging thread waits for space; nothing
|
||||
/// is ever lost.
|
||||
/// DropNewest — the incoming entry is discarded.
|
||||
/// DropOldest — the oldest pending entries are discarded by the worker
|
||||
/// when it falls behind (soft bound: memory can briefly
|
||||
/// exceed capacity until the next drain).
|
||||
enum class OverflowPolicy { Block, DropNewest, DropOldest };
|
||||
|
||||
/// Abstract base class for all Void loggers.
|
||||
///
|
||||
/// ## Responsibilities
|
||||
/// - Level filtering (thread-safe, lock-free gate)
|
||||
/// - Entry construction: timestamp, thread_id, scope snapshot
|
||||
/// - Dispatch: Async (default, lock-free queue + owned worker thread
|
||||
/// delivering batches), Immediate (inline), or Buffered (flush at
|
||||
/// capacity). Switch at runtime with set_mode() — no separate
|
||||
/// async/sync classes.
|
||||
/// - Thread-safe submission — virtual extension points are called
|
||||
/// *outside* any internal lock (from the worker thread in Async
|
||||
/// mode) so derived classes may perform blocking I/O or acquire
|
||||
/// their own resources freely.
|
||||
/// - Scoped context via per-thread RAII guards (Logger::ScopedContext)
|
||||
/// - Named scope logging: scope() emits ScopeEnter/ScopeExit entries
|
||||
/// - Logger presets via make_preset() — bake in a level (and optional
|
||||
/// message prefix) and later call with only the message/format args.
|
||||
///
|
||||
/// ## Async mode notes
|
||||
/// - capacity bounds the pending-entry queue; OverflowPolicy decides
|
||||
/// what happens at the bound (Block by default — nothing is lost).
|
||||
/// - flush() blocks until every entry submitted *before* the call has
|
||||
/// been delivered.
|
||||
/// - In Async mode write()/on_flush() run on the worker thread; sinks
|
||||
/// need no additional synchronization of their own state.
|
||||
///
|
||||
/// ## Deriving a logger
|
||||
/// 1. Override `write(const Entry&)` — called once per entry in
|
||||
/// Immediate mode and by the default `on_flush` implementation.
|
||||
/// 2. Optionally override `on_flush(std::span<const Entry>)` — useful
|
||||
/// for sinks that benefit from batch writes (e.g. file loggers).
|
||||
/// 3. **Call `flush()` in your own destructor** before the base
|
||||
/// destructor runs. Calling a pure virtual from `~Logger` is
|
||||
/// undefined behaviour, so the base destructor does *not* flush;
|
||||
/// any unflushed entries that remain after your destructor will be
|
||||
/// silently discarded (the base destructor only stops and joins
|
||||
/// the worker — it never invokes the virtuals).
|
||||
/// 4. Stop logging from other threads before destroying the logger;
|
||||
/// entries submitted concurrently with destruction are dropped.
|
||||
///
|
||||
/// ## Example — minimal derived logger
|
||||
/// @code
|
||||
/// class StdoutLogger final : public Void::Logging::Logger
|
||||
/// {
|
||||
/// public:
|
||||
/// ~StdoutLogger() noexcept override { flush(); }
|
||||
/// protected:
|
||||
/// void write(const Void::Logging::Entry& e) override
|
||||
/// {
|
||||
/// std::println("[{}] {}", e.level, e.message);
|
||||
/// }
|
||||
/// };
|
||||
/// @endcode
|
||||
enum class LogErrorCode : std::int32_t {
|
||||
invalid_argument = 1,
|
||||
queue_full = 2,
|
||||
entry_too_large = 3,
|
||||
closed = 4,
|
||||
cancelled = 5,
|
||||
timeout = 6,
|
||||
would_deadlock = 7,
|
||||
quarantined = 8,
|
||||
unsupported_capability = 9,
|
||||
io_error = 10,
|
||||
cycle_detected = 11
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Void::Result::Error
|
||||
make_log_error(LogErrorCode code, std::string message = {})
|
||||
{
|
||||
using Void::Result::Error;
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case LogErrorCode::invalid_argument:
|
||||
case LogErrorCode::entry_too_large:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case LogErrorCode::queue_full:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
case LogErrorCode::closed:
|
||||
case LogErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case LogErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case LogErrorCode::would_deadlock:
|
||||
case LogErrorCode::cycle_detected:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case LogErrorCode::quarantined:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case LogErrorCode::unsupported_capability:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case LogErrorCode::io_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
}
|
||||
return Error{kind,
|
||||
std::move(message),
|
||||
ErrorCode{Void::Result::kLogErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct DeliveryLimits {
|
||||
std::size_t entries = 4096;
|
||||
std::size_t owned_bytes = 8ULL * 1024ULL * 1024ULL;
|
||||
std::size_t max_entry_bytes = 64ULL * 1024ULL;
|
||||
std::size_t batch_entries = 128;
|
||||
std::size_t batch_bytes = 256ULL * 1024ULL;
|
||||
std::size_t max_fields = 32;
|
||||
std::size_t max_scopes = 16;
|
||||
std::size_t max_field_key_bytes = 256;
|
||||
std::size_t max_field_value_bytes = 2048;
|
||||
std::size_t max_format_scratch_bytes = 1024ULL * 1024ULL;
|
||||
bool truncate_oversize = false;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> validate() const;
|
||||
};
|
||||
|
||||
enum class FailurePolicy : std::uint8_t {
|
||||
Quarantine = 0,
|
||||
Continue
|
||||
};
|
||||
|
||||
struct LoggerOptions {
|
||||
Mode mode = Mode::Async;
|
||||
OverflowPolicy policy = OverflowPolicy::DropNewest;
|
||||
DeliveryLimits limits{};
|
||||
FailurePolicy failure_policy = FailurePolicy::Quarantine;
|
||||
bool suppress_reentrancy = true;
|
||||
const Void::Time::MonotonicClock* clock =
|
||||
&Void::Time::SystemMonotonicClock::instance();
|
||||
};
|
||||
|
||||
enum class SubmitState : std::uint8_t {
|
||||
Accepted = 0,
|
||||
Filtered,
|
||||
Dropped,
|
||||
Closed
|
||||
};
|
||||
|
||||
using Ticket = std::uint64_t;
|
||||
|
||||
struct SubmitReceipt {
|
||||
SubmitState state{SubmitState::Dropped};
|
||||
std::optional<Ticket> ticket{};
|
||||
bool truncated{false};
|
||||
};
|
||||
|
||||
enum class FlushDurability : std::uint8_t {
|
||||
BufferFlush = 0,
|
||||
SyncFiles
|
||||
};
|
||||
|
||||
struct FlushOptions {
|
||||
FlushDurability durability = FlushDurability::BufferFlush;
|
||||
Void::Async::OperationOptions async{};
|
||||
};
|
||||
|
||||
struct CloseOptions {
|
||||
bool drop_pending = false;
|
||||
Void::Async::OperationOptions async{};
|
||||
};
|
||||
|
||||
struct FlushReport {
|
||||
std::uint64_t delivered{0};
|
||||
std::uint64_t dropped{0};
|
||||
std::uint64_t failed{0};
|
||||
Ticket watermark{0};
|
||||
bool timed_out{false};
|
||||
bool cancelled{false};
|
||||
};
|
||||
|
||||
struct LoggerStats {
|
||||
std::size_t queued_entries{0};
|
||||
std::size_t queued_bytes{0};
|
||||
std::size_t in_flight_entries{0};
|
||||
std::size_t in_flight_bytes{0};
|
||||
std::uint64_t admitted{0};
|
||||
std::uint64_t delivered{0};
|
||||
std::uint64_t dropped{0};
|
||||
std::uint64_t failed{0};
|
||||
std::uint64_t reentrant_dropped{0};
|
||||
Ticket completed_watermark{0};
|
||||
bool quarantined{false};
|
||||
bool closed{false};
|
||||
};
|
||||
|
||||
/// Abstract base class for all Void loggers with bounded entry/byte
|
||||
/// admission, ticket completion watermarks, failure quarantine, and flush
|
||||
/// durability controls.
|
||||
class Logger
|
||||
{
|
||||
public:
|
||||
|
||||
// =========================================================================
|
||||
// ScopedContext — RAII, per-thread, named scope push/pop
|
||||
//
|
||||
// Pushing a scope has two effects:
|
||||
// 1. The scope name is appended to this thread's scope stack so
|
||||
// all subsequent entries carry it in Entry::scopes.
|
||||
// 2. A ScopeEnter entry is emitted at the level supplied to
|
||||
// push_scope() (or Trace by default).
|
||||
// 3. On destruction a ScopeExit entry is emitted at the same
|
||||
// level.
|
||||
//
|
||||
// Usage:
|
||||
// {
|
||||
// auto s = logger.push_scope("network"); // →
|
||||
// ScopeEnter logger.info("connecting …"); //
|
||||
// scopes={"network"}
|
||||
// {
|
||||
// auto t = logger.push_scope("tls"); // →
|
||||
// ScopeEnter logger.debug("handshake"); //
|
||||
// scopes={"network","tls"}
|
||||
// } // → ScopeExit
|
||||
// "tls"
|
||||
// } // → ScopeExit
|
||||
// "network"
|
||||
// =========================================================================
|
||||
class ScopedContext
|
||||
{
|
||||
public:
|
||||
@@ -131,8 +193,6 @@ namespace Void::Logging
|
||||
std::source_location loc) noexcept;
|
||||
~ScopedContext() noexcept;
|
||||
|
||||
// Non-copyable; move transfers ownership so the moved-from
|
||||
// guard does not emit a spurious ScopeExit on destruction.
|
||||
ScopedContext(const ScopedContext&) = delete;
|
||||
ScopedContext& operator=(const ScopedContext&) = delete;
|
||||
ScopedContext(ScopedContext&&) noexcept;
|
||||
@@ -146,23 +206,6 @@ namespace Void::Logging
|
||||
bool m_active{true};
|
||||
};
|
||||
|
||||
// =========================================================================
|
||||
// Preset — a partially-applied logger
|
||||
//
|
||||
// A Preset captures a reference to the owning Logger together with
|
||||
// a fixed Level (and optional message prefix). Call it with just
|
||||
// the message / format args; the level is already baked in.
|
||||
//
|
||||
// Lifetime: a Preset must not outlive the Logger it was made from.
|
||||
//
|
||||
// Usage:
|
||||
// auto net_err = logger.make_preset(Level::Error, "[network] ");
|
||||
// net_err("connection refused"); // same as:
|
||||
// // logger.error("[network] connection refused");
|
||||
//
|
||||
// auto dbg = logger.make_preset(Level::Debug);
|
||||
// dbg("value = {}", 42);
|
||||
// =========================================================================
|
||||
class Preset
|
||||
{
|
||||
public:
|
||||
@@ -174,16 +217,11 @@ namespace Void::Logging
|
||||
{
|
||||
}
|
||||
|
||||
// Non-owning; copyable so presets can be stored / passed
|
||||
// around.
|
||||
Preset(const Preset&) = default;
|
||||
Preset& operator=(const Preset&) = default;
|
||||
Preset(Preset&&) = default;
|
||||
Preset& operator=(Preset&&) = default;
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Plain string overload
|
||||
// -----------------------------------------------------------------
|
||||
void operator()(std::string_view message,
|
||||
std::source_location loc =
|
||||
std::source_location::current()) const
|
||||
@@ -197,22 +235,6 @@ namespace Void::Logging
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FormatWithLocation helper
|
||||
//
|
||||
// std::source_location cannot share a parameter list with
|
||||
// a variadic pack, so this wrapper type captures both the
|
||||
// format string and the caller's source location in its
|
||||
// constructor.
|
||||
//
|
||||
// std::type_identity_t<Args>... prevents Args from being
|
||||
// deduced from the wrapper; they are deduced solely from
|
||||
// the trailing pack.
|
||||
//
|
||||
// Usage — source location is captured transparently:
|
||||
// logger.info("player {} scored {} points", name,
|
||||
// score);
|
||||
// =========================================================================
|
||||
template <typename... Args> struct FormatWithLocation {
|
||||
std::format_string<Args...> fmt;
|
||||
std::source_location location;
|
||||
@@ -227,12 +249,6 @@ namespace Void::Logging
|
||||
}
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Formatted overload
|
||||
// Uses the same FormatWithLocation trick as Logger itself
|
||||
// so the call-site source location is captured
|
||||
// transparently.
|
||||
// -----------------------------------------------------------------
|
||||
template <typename... Args>
|
||||
void operator()(
|
||||
FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
@@ -249,7 +265,6 @@ namespace Void::Logging
|
||||
m_owner->log(m_level, msg, fwl.location);
|
||||
}
|
||||
|
||||
// Accessors
|
||||
[[nodiscard]] Level level() const noexcept
|
||||
{
|
||||
return m_level;
|
||||
@@ -273,18 +288,13 @@ namespace Void::Logging
|
||||
// =========================================================================
|
||||
// Lifetime
|
||||
// =========================================================================
|
||||
/// @param mode Dispatch strategy; Async by default.
|
||||
/// @param capacity Async: pending-queue bound (fixed for the
|
||||
/// logger's lifetime). Buffered: auto-flush
|
||||
/// threshold (adjustable).
|
||||
/// @param policy Async overflow behaviour at capacity.
|
||||
explicit Logger(
|
||||
Mode mode = Mode::Async,
|
||||
std::size_t capacity = 512,
|
||||
OverflowPolicy policy = OverflowPolicy::Block) noexcept;
|
||||
|
||||
/// Stops and joins the worker thread (Async). Does NOT flush
|
||||
/// remaining entries — see class-level note.
|
||||
explicit Logger(LoggerOptions options);
|
||||
|
||||
virtual ~Logger() noexcept;
|
||||
|
||||
Logger(const Logger&) = delete;
|
||||
@@ -293,103 +303,75 @@ namespace Void::Logging
|
||||
Logger& operator=(Logger&&) = delete;
|
||||
|
||||
// =========================================================================
|
||||
// Configuration (all setters are thread-safe)
|
||||
// Configuration
|
||||
// =========================================================================
|
||||
|
||||
/// Set the minimum level. Entries below this level are dropped.
|
||||
/// Level::Disabled suppresses all output.
|
||||
void set_level(Level level) noexcept;
|
||||
[[nodiscard]] Level level() const noexcept;
|
||||
|
||||
/// Switch dispatch strategy at runtime (e.g. Async → Immediate
|
||||
/// to make the logger synchronous). Pending entries are flushed
|
||||
/// before the switch takes effect.
|
||||
void set_mode(Mode mode) noexcept;
|
||||
[[nodiscard]] Mode mode() const noexcept;
|
||||
|
||||
/// Maximum number of entries held before an automatic flush
|
||||
/// (Buffered mode only; the Async queue bound is fixed at
|
||||
/// construction).
|
||||
void set_buffer_capacity(std::size_t n) noexcept;
|
||||
[[nodiscard]] std::size_t buffer_capacity() const noexcept;
|
||||
|
||||
[[nodiscard]] OverflowPolicy overflow_policy() const noexcept;
|
||||
[[nodiscard]] const DeliveryLimits& delivery_limits() const noexcept
|
||||
{
|
||||
return m_options.limits;
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// Flush
|
||||
// P2 Checked Submission, Flush, Close, and Quarantine Controls
|
||||
// =========================================================================
|
||||
[[nodiscard]] Void::Result::Result<SubmitReceipt>
|
||||
try_submit(Entry entry,
|
||||
Void::Async::OperationOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FlushReport>
|
||||
flush_through(Ticket target = 0, FlushOptions options = {});
|
||||
|
||||
[[nodiscard]] Void::Result::Result<FlushReport>
|
||||
close(CloseOptions options = {});
|
||||
|
||||
void request_close() noexcept;
|
||||
|
||||
/// Deliver all pending entries. Async: blocks until everything
|
||||
/// submitted before this call has been written. Buffered: drains
|
||||
/// the buffer via on_flush(). Immediate: no-op. Thread-safe.
|
||||
/// Virtual so composite sinks can propagate the flush to
|
||||
/// children.
|
||||
virtual void flush();
|
||||
|
||||
// =========================================================================
|
||||
// Scoped context
|
||||
// =========================================================================
|
||||
[[nodiscard]] LoggerStats stats() const;
|
||||
[[nodiscard]] bool is_quarantined() const noexcept;
|
||||
[[nodiscard]] std::string last_error_summary() const;
|
||||
void reset_quarantine() noexcept;
|
||||
|
||||
/// Push a named scope onto this thread's scope stack AND emit a
|
||||
/// ScopeEnter entry at the given level. The returned ScopedContext
|
||||
/// emits a ScopeExit entry and pops the stack when it goes out of
|
||||
/// scope.
|
||||
///
|
||||
/// @param name Human-readable scope label.
|
||||
/// @param level Level used for the ScopeEnter/ScopeExit entries.
|
||||
/// Defaults to Trace so scope boundaries are usually
|
||||
/// invisible in production builds.
|
||||
/// @return A [[nodiscard]] RAII guard — assign it to a named
|
||||
/// local; do NOT discard (it would immediately exit).
|
||||
// =========================================================================
|
||||
// Scoped context & Presets
|
||||
// =========================================================================
|
||||
[[nodiscard]] ScopedContext
|
||||
push_scope(std::string name,
|
||||
Level level = Level::Trace,
|
||||
std::source_location loc =
|
||||
std::source_location::current()) noexcept;
|
||||
|
||||
/// Emit a named scope open/close pair as explicit log entries
|
||||
/// WITHOUT modifying the thread-local scope stack. Useful when you
|
||||
/// want scope boundaries in the log but don't want child entries
|
||||
/// annotated.
|
||||
///
|
||||
/// Both ScopeEnter and ScopeExit are emitted immediately (Immediate
|
||||
/// mode) or buffered together (Buffered mode).
|
||||
void scope(
|
||||
std::string_view name,
|
||||
Level level = Level::Trace,
|
||||
std::source_location loc = std::source_location::current());
|
||||
|
||||
/// Read-only view of the current thread's scope stack.
|
||||
/// Ordered outermost → innermost.
|
||||
[[nodiscard]] static std::span<const std::string>
|
||||
current_scopes() noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Preset factory
|
||||
// =========================================================================
|
||||
|
||||
/// Create a Preset that fixes the level and an optional message
|
||||
/// prefix. The Preset holds a non-owning reference to *this — do
|
||||
/// not outlive the logger.
|
||||
[[nodiscard]] Preset make_preset(Level level,
|
||||
std::string prefix = {}) noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Core (non-template) logging — canonical entry points
|
||||
// Core & Formatted Logging (legacy compatibility adapters)
|
||||
// =========================================================================
|
||||
inline void log(
|
||||
Level level, std::string_view message,
|
||||
std::source_location location = std::source_location::current())
|
||||
{
|
||||
// Early level check outside the lock to avoid allocations on
|
||||
// the hot path.
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
if (level < m_level) {
|
||||
return;
|
||||
}
|
||||
if (level < m_level.load(std::memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const auto fields = current_fields();
|
||||
Entry entry{
|
||||
.kind = Kind::Message,
|
||||
@@ -398,7 +380,6 @@ namespace Void::Logging
|
||||
.timestamp = std::chrono::system_clock::now(),
|
||||
.location = location,
|
||||
.thread_id = std::this_thread::get_id(),
|
||||
// Snapshot here through the existing DLL function boundary.
|
||||
.scopes = [] {
|
||||
const auto scopes = Logger::current_scopes();
|
||||
return std::vector<std::string>(
|
||||
@@ -406,14 +387,9 @@ namespace Void::Logging
|
||||
}(),
|
||||
.fields = {fields.begin(), fields.end()},
|
||||
};
|
||||
|
||||
submit(std::move(entry));
|
||||
(void)try_submit(std::move(entry));
|
||||
}
|
||||
|
||||
/// Route a fully-built Entry through this logger's level filter
|
||||
/// and dispatch (queue / buffer / inline write). Meant for
|
||||
/// composite sinks (e.g. MultiLogger) that fan entries out to
|
||||
/// children without re-stamping timestamp/thread/scopes.
|
||||
void relay(Entry entry);
|
||||
|
||||
void trace(
|
||||
@@ -435,10 +411,6 @@ namespace Void::Logging
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
|
||||
// =========================================================================
|
||||
// Formatted logging
|
||||
// =========================================================================
|
||||
|
||||
template <typename... Args>
|
||||
void log(Level level,
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...>
|
||||
@@ -498,81 +470,90 @@ namespace Void::Logging
|
||||
log(Level::Fatal, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
[[nodiscard]] virtual Void::Result::Result<void> sync_files();
|
||||
|
||||
protected:
|
||||
|
||||
// =========================================================================
|
||||
// Extension points
|
||||
//
|
||||
// Both methods are called OUTSIDE the internal mutex. Derived
|
||||
// classes may block, acquire their own locks, or call other Logger
|
||||
// methods without risk of deadlock.
|
||||
// =========================================================================
|
||||
|
||||
/// Deliver one entry to the sink.
|
||||
/// Called once per entry in Immediate mode, and by the default
|
||||
/// on_flush() for each entry in the batch.
|
||||
virtual void write(const Entry& entry) = 0;
|
||||
|
||||
/// Deliver a batch of buffered entries to the sink.
|
||||
/// The default implementation calls write() for each entry in
|
||||
/// order. Override to enable batched / vectored I/O.
|
||||
virtual void on_flush(std::span<const Entry> entries);
|
||||
|
||||
private:
|
||||
|
||||
/// Build an Entry and route it to the queue, write() or the
|
||||
/// buffer depending on the active mode.
|
||||
void submit(Entry entry);
|
||||
enum class TerminalOutcome : std::uint8_t {
|
||||
Delivered = 0,
|
||||
Dropped,
|
||||
Failed
|
||||
};
|
||||
|
||||
/// Async path: bounded enqueue honoring the overflow policy.
|
||||
void async_submit(Entry entry);
|
||||
struct QueuedItem {
|
||||
Ticket ticket{0};
|
||||
std::size_t bytes{0};
|
||||
Entry entry;
|
||||
};
|
||||
|
||||
[[nodiscard]] static std::size_t
|
||||
estimate_entry_bytes(const Entry& entry) noexcept;
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
prepare_entry(Entry& entry) const;
|
||||
|
||||
/// Start the worker thread on first use (Async mode).
|
||||
void start_worker();
|
||||
|
||||
/// Wake the worker if it parked itself.
|
||||
void wake_worker() noexcept;
|
||||
|
||||
/// Worker: drain → on_flush batches → park when idle.
|
||||
void worker_loop();
|
||||
|
||||
/// Async: block until everything submitted so far is written.
|
||||
void drain_async();
|
||||
|
||||
/// Emit a raw scope boundary entry; shared by push_scope and
|
||||
/// scope().
|
||||
void mark_terminal_locked(Ticket t, TerminalOutcome outcome);
|
||||
void advance_watermark_locked();
|
||||
void deliver_batch_unlocked(
|
||||
std::vector<QueuedItem>& items,
|
||||
bool stopping,
|
||||
std::size_t total_bytes);
|
||||
void emit_scope_boundary(Kind kind,
|
||||
std::string_view name,
|
||||
Level level,
|
||||
std::source_location loc);
|
||||
|
||||
[[nodiscard]] bool is_active_logger_on_thread() const noexcept;
|
||||
|
||||
std::atomic<Level> m_level{Level::Trace};
|
||||
std::atomic<Mode> m_mode;
|
||||
std::size_t m_async_capacity;
|
||||
OverflowPolicy m_policy;
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::vector<Entry> m_buffer; // Buffered mode only
|
||||
LoggerOptions m_options;
|
||||
std::size_t m_buffer_capacity;
|
||||
|
||||
// ── Async machinery ──────────────────────────────────────────
|
||||
Void::Async::MpscQueue<Entry> m_queue;
|
||||
std::counting_semaphore<> m_space; // Block policy bound
|
||||
// Counting (not binary): the worker's un-park path can leave a
|
||||
// stale token behind, and a fresh release on top of it must
|
||||
// not overflow. Extra tokens only cause spurious wakes, which
|
||||
// the worker loop absorbs.
|
||||
std::counting_semaphore<> m_wakeup{0};
|
||||
std::atomic<bool> m_sleeping{false};
|
||||
std::atomic<bool> m_stop{false};
|
||||
mutable std::mutex m_mutex;
|
||||
std::condition_variable m_work_cv;
|
||||
std::condition_variable m_space_cv;
|
||||
std::condition_variable m_done_cv;
|
||||
|
||||
std::deque<QueuedItem> m_queue;
|
||||
std::size_t m_queued_entries{0};
|
||||
std::size_t m_queued_bytes{0};
|
||||
std::size_t m_in_flight_entries{0};
|
||||
std::size_t m_in_flight_bytes{0};
|
||||
|
||||
Ticket m_next_ticket{0};
|
||||
Ticket m_completed_watermark{0};
|
||||
std::set<std::pair<Ticket, TerminalOutcome>> m_pending_terminals;
|
||||
|
||||
std::uint64_t m_admitted_count{0};
|
||||
std::uint64_t m_delivered_count{0};
|
||||
std::uint64_t m_dropped_count{0};
|
||||
std::uint64_t m_failed_count{0};
|
||||
std::uint64_t m_wm_delivered{0};
|
||||
std::uint64_t m_wm_dropped{0};
|
||||
std::uint64_t m_wm_failed{0};
|
||||
std::atomic<std::uint64_t> m_reentrant_dropped{0};
|
||||
|
||||
bool m_mode_changing{false};
|
||||
bool m_stop_admission{false};
|
||||
bool m_closed{false};
|
||||
std::atomic<bool> m_stop_worker{false};
|
||||
std::atomic<bool> m_quarantined{false};
|
||||
std::string m_last_error;
|
||||
|
||||
std::atomic<bool> m_worker_started{false};
|
||||
std::once_flag m_worker_once;
|
||||
std::thread m_worker;
|
||||
std::atomic<std::uint64_t> m_submitted{0};
|
||||
std::atomic<std::uint64_t> m_completed{0};
|
||||
std::atomic<std::thread::id> m_worker_id{};
|
||||
|
||||
/// Per-thread scope stack. ScopedContext pushes/pops into this.
|
||||
static thread_local std::vector<std::string> s_scope_stack;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
@@ -13,21 +13,25 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// File sink with size-based rotation.
|
||||
///
|
||||
/// When the current file reaches `max_bytes` after a batch, files are
|
||||
/// shifted (`app.log` → `app.log.1` → `app.log.2` …); at most
|
||||
/// `max_files` rotated files are kept, the oldest is deleted.
|
||||
///
|
||||
/// Defaults to Async dispatch — rotation and writes happen on the
|
||||
/// worker thread. An optional Formatter overrides the default
|
||||
/// "[Level] message" rendering; set it before logging starts.
|
||||
struct RotatingFileOptions {
|
||||
std::size_t max_bytes = 1024 * 1024;
|
||||
std::size_t max_files = 5;
|
||||
Mode mode = Mode::Async;
|
||||
std::size_t capacity = 512;
|
||||
OverflowPolicy policy = OverflowPolicy::Block;
|
||||
bool create_directories = true;
|
||||
|
||||
[[nodiscard]] static constexpr RotatingFileOptions
|
||||
roadmap_defaults() noexcept
|
||||
{
|
||||
return RotatingFileOptions{
|
||||
.max_bytes = 16ULL * 1024ULL * 1024ULL,
|
||||
.max_files = 5,
|
||||
.mode = Mode::Async,
|
||||
.capacity = 4096,
|
||||
.policy = OverflowPolicy::DropNewest,
|
||||
.create_directories = false};
|
||||
}
|
||||
};
|
||||
|
||||
class RotatingFileLogger final : public Logger
|
||||
@@ -46,17 +50,18 @@ namespace Void::Logging
|
||||
RotatingFileLogger(RotatingFileLogger&&) = delete;
|
||||
RotatingFileLogger& operator=(RotatingFileLogger&&) = delete;
|
||||
|
||||
/// Non-throwing factory.
|
||||
[[nodiscard]] static Void::Result::
|
||||
Result<std::unique_ptr<RotatingFileLogger>, Void::Result::Error>
|
||||
open(const std::filesystem::path& path, Options options = {});
|
||||
|
||||
/// Install a formatter. Call before logging starts.
|
||||
void set_formatter(std::shared_ptr<const Formatter> formatter)
|
||||
{
|
||||
m_formatter = std::move(formatter);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> reopen();
|
||||
[[nodiscard]] Void::Result::Result<void> sync_files() override;
|
||||
|
||||
[[nodiscard]] const std::filesystem::path& path() const noexcept
|
||||
{
|
||||
return m_path;
|
||||
@@ -76,4 +81,4 @@ namespace Void::Logging
|
||||
std::shared_ptr<const Formatter> m_formatter;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
+79
-13
@@ -9,12 +9,17 @@
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Discards everything. Useful as a placeholder or for benchmarks.
|
||||
inline constexpr std::size_t kDefaultMaxFanoutChildren = 8;
|
||||
|
||||
class NullLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
|
||||
explicit NullLogger(Mode mode = Mode::Immediate) : Logger(mode) {}
|
||||
explicit NullLogger(LoggerOptions options)
|
||||
: Logger(std::move(options))
|
||||
{
|
||||
}
|
||||
|
||||
~NullLogger() noexcept override { flush(); }
|
||||
|
||||
@@ -23,8 +28,6 @@ namespace Void::Logging
|
||||
void write(const Entry&) override {}
|
||||
};
|
||||
|
||||
/// Forwards every entry to a user callback. The simplest way to splice
|
||||
/// an external logging library into the Logger framework.
|
||||
class CallbackLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
@@ -41,6 +44,11 @@ namespace Void::Logging
|
||||
{
|
||||
}
|
||||
|
||||
explicit CallbackLogger(Callback callback, LoggerOptions options)
|
||||
: Logger(std::move(options)), m_callback(std::move(callback))
|
||||
{
|
||||
}
|
||||
|
||||
~CallbackLogger() noexcept override { flush(); }
|
||||
|
||||
protected:
|
||||
@@ -57,10 +65,6 @@ namespace Void::Logging
|
||||
Callback m_callback;
|
||||
};
|
||||
|
||||
/// Tee: relays every entry to each child logger. Children keep their
|
||||
/// own modes, levels, and formatters. The MultiLogger itself defaults
|
||||
/// to Immediate dispatch — the children already decide whether they
|
||||
/// queue asynchronously, so double-queueing only adds latency.
|
||||
class MultiLogger final : public Logger
|
||||
{
|
||||
public:
|
||||
@@ -72,15 +76,41 @@ namespace Void::Logging
|
||||
{
|
||||
}
|
||||
|
||||
explicit MultiLogger(
|
||||
std::vector<std::shared_ptr<Logger>> children,
|
||||
LoggerOptions options)
|
||||
: Logger(std::move(options)), m_children(std::move(children))
|
||||
{
|
||||
}
|
||||
|
||||
~MultiLogger() noexcept override { flush(); }
|
||||
|
||||
/// Add a child sink. Not thread-safe with concurrent logging —
|
||||
/// assemble the tree before use.
|
||||
void add(std::shared_ptr<Logger> child)
|
||||
{
|
||||
if (child) {
|
||||
m_children.push_back(std::move(child));
|
||||
(void)try_add(std::move(child));
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void>
|
||||
try_add(std::shared_ptr<Logger> child,
|
||||
std::size_t max_children = kDefaultMaxFanoutChildren)
|
||||
{
|
||||
if (!child) {
|
||||
return Void::Result::fail(make_log_error(
|
||||
LogErrorCode::invalid_argument,
|
||||
"MultiLogger::try_add: null child"));
|
||||
}
|
||||
if (m_children.size() >= max_children) {
|
||||
return Void::Result::fail(make_log_error(
|
||||
LogErrorCode::queue_full,
|
||||
"MultiLogger child fan-out limit exceeded"));
|
||||
}
|
||||
if (reaches_self(*child)) {
|
||||
return Void::Result::fail(make_log_error(
|
||||
LogErrorCode::cycle_detected,
|
||||
"MultiLogger fan-out cycle detected"));
|
||||
}
|
||||
m_children.push_back(std::move(child));
|
||||
return {};
|
||||
}
|
||||
|
||||
[[nodiscard]] std::size_t child_count() const noexcept
|
||||
@@ -88,7 +118,6 @@ namespace Void::Logging
|
||||
return m_children.size();
|
||||
}
|
||||
|
||||
/// Flush own pending entries, then every child.
|
||||
void flush() override
|
||||
{
|
||||
Logger::flush();
|
||||
@@ -97,6 +126,26 @@ namespace Void::Logging
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Result::Result<void> sync_files() override
|
||||
{
|
||||
if (m_children.empty()) {
|
||||
return Logger::sync_files();
|
||||
}
|
||||
bool any_synced = false;
|
||||
for (const auto& child : m_children) {
|
||||
auto res = child->sync_files();
|
||||
if (res) {
|
||||
any_synced = true;
|
||||
} else if (res.error().code().value !=
|
||||
static_cast<std::int32_t>(
|
||||
LogErrorCode::unsupported_capability)) {
|
||||
return res;
|
||||
}
|
||||
}
|
||||
return any_synced ? Void::Result::Result<void>{}
|
||||
: Logger::sync_files();
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
void write(const Entry& entry) override
|
||||
@@ -108,7 +157,24 @@ namespace Void::Logging
|
||||
|
||||
private:
|
||||
|
||||
[[nodiscard]] bool reaches_self(const Logger& candidate) const
|
||||
{
|
||||
if (&candidate == this) {
|
||||
return true;
|
||||
}
|
||||
const auto* nested = dynamic_cast<const MultiLogger*>(&candidate);
|
||||
if (nested == nullptr) {
|
||||
return false;
|
||||
}
|
||||
for (const auto& grandchild : nested->m_children) {
|
||||
if (grandchild && reaches_self(*grandchild)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<std::shared_ptr<Logger>> m_children;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
} // namespace Void::Logging
|
||||
+119
-8
@@ -1,7 +1,15 @@
|
||||
#include <Void/Log/FileLogger.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <format>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
|
||||
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<std::unique_ptr<FileLogger>, 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<FileLogger>(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<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
FileLogger::open(const std::filesystem::path& path,
|
||||
LoggerOptions options)
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(
|
||||
std::make_unique<FileLogger>(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<void> 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<void> 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<const Entry> 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
|
||||
+114
-73
@@ -1,9 +1,11 @@
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <array>
|
||||
#include <charconv>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
@@ -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<double>(entry.location.line())});
|
||||
Json::Value{static_cast<std::int64_t>(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<char>(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<std::string>
|
||||
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
|
||||
@@ -1,325 +0,0 @@
|
||||
#include <Void/Log/FromConfig.hpp>
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/FileLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/History.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/SplitFileLogger.hpp>
|
||||
#include <Void/Log/SyslogLogger.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
std::vector<std::string> split_list(std::string_view csv)
|
||||
{
|
||||
std::vector<std::string> 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<Level> parse_level(std::string_view name)
|
||||
{
|
||||
std::string lower;
|
||||
for (const char c : name) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<Void::Log::Level>
|
||||
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<const Formatter>
|
||||
make_formatter(const Configuration::Config& cfg)
|
||||
{
|
||||
const auto format = cfg.get_or("format", "default");
|
||||
if (format == "pattern") {
|
||||
auto fmt =
|
||||
std::make_shared<PatternFormatter>(std::string{cfg.get_or(
|
||||
"pattern", "{time} [{level}] {scopes}{message}")});
|
||||
if (cfg.get_or_as<bool>("color", false)) {
|
||||
fmt->set_color_policy(ColorPolicy::defaults());
|
||||
}
|
||||
return fmt;
|
||||
}
|
||||
if (format == "json") {
|
||||
auto fmt = std::make_shared<JsonLinesFormatter>();
|
||||
fmt->set_field_filter(make_field_filter(cfg));
|
||||
return fmt;
|
||||
}
|
||||
if (format == "logfmt") {
|
||||
auto fmt = std::make_shared<LogfmtFormatter>();
|
||||
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<bool>("async", true)) {
|
||||
d.mode = Mode::Immediate;
|
||||
}
|
||||
d.capacity = cfg.get_or_as<std::size_t>("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<std::shared_ptr<Logger>, 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<std::shared_ptr<Logger>> 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<ConsoleLogger>(
|
||||
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<Logger>{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<std::size_t>("rotating.max_kb", 1024) * 1024;
|
||||
opt.max_files =
|
||||
sub.get_or_as<std::size_t>("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<Logger>{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<bool>("split.combined", true);
|
||||
opt.max_bytes =
|
||||
sub.get_or_as<std::size_t>("split.max_kb", 1024) * 1024;
|
||||
opt.max_files =
|
||||
sub.get_or_as<std::size_t>("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<Logger>{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<std::size_t>("history.max_kb", 8192) * 1024;
|
||||
opt.max_files =
|
||||
sub.get_or_as<std::size_t>("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<Logger>{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<SyslogLogger>(
|
||||
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<Logger> root;
|
||||
if (sinks.empty()) {
|
||||
root = std::make_shared<NullLogger>();
|
||||
} else if (sinks.size() == 1) {
|
||||
root = std::move(sinks.front());
|
||||
} else {
|
||||
root = std::make_shared<MultiLogger>(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
|
||||
+712
-241
File diff suppressed because it is too large.
Load diff
+86
-10
@@ -1,9 +1,18 @@
|
||||
#include <Void/Log/Detail/RollingFile.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
|
||||
#ifndef _WIN32
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <unistd.h>
|
||||
#endif
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
@@ -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::size_t>(
|
||||
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<std::streamsize>(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<void> 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: <stem>-<timestamp>.<ext>
|
||||
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
|
||||
@@ -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<std::size_t>(
|
||||
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<RotatingFileLogger>(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<void> 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<void> 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
|
||||
@@ -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
|
||||
)
|
||||
@@ -0,0 +1,449 @@
|
||||
#include <Void/Log/FromConfig.hpp>
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/FileLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/History.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/SplitFileLogger.hpp>
|
||||
#include <Void/Log/SyslogLogger.hpp>
|
||||
|
||||
#include <cctype>
|
||||
#include <format>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
std::vector<std::string> split_list(std::string_view csv)
|
||||
{
|
||||
std::vector<std::string> 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<Level> parse_level(std::string_view name)
|
||||
{
|
||||
std::string lower;
|
||||
for (const char c : name) {
|
||||
lower += static_cast<char>(
|
||||
std::tolower(static_cast<unsigned char>(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<Void::Log::Level>
|
||||
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<std::shared_ptr<const Formatter>,
|
||||
Void::Result::Error>
|
||||
make_formatter(const Configuration::Config& cfg)
|
||||
{
|
||||
const auto format = cfg.get_or("format", "default");
|
||||
if (format == "default") {
|
||||
return Void::Result::ok<std::shared_ptr<const Formatter>>(nullptr);
|
||||
}
|
||||
if (format == "pattern") {
|
||||
auto fmt = std::make_shared<PatternFormatter>(std::string{
|
||||
cfg.get_or("pattern",
|
||||
"{time} [{level}] {scopes}{message}")});
|
||||
if (const auto col = cfg.get_as<std::string>("color");
|
||||
col.has_value()) {
|
||||
const auto parsed = cfg.get_as<bool>("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::shared_ptr<const Formatter>>(
|
||||
std::move(fmt));
|
||||
}
|
||||
if (format == "json") {
|
||||
auto fmt = std::make_shared<JsonLinesFormatter>();
|
||||
fmt->set_field_filter(make_field_filter(cfg));
|
||||
return Void::Result::ok<std::shared_ptr<const Formatter>>(
|
||||
std::move(fmt));
|
||||
}
|
||||
if (format == "logfmt") {
|
||||
auto fmt = std::make_shared<LogfmtFormatter>();
|
||||
fmt->set_field_filter(make_field_filter(cfg));
|
||||
return Void::Result::ok<std::shared_ptr<const Formatter>>(
|
||||
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<Dispatch, Void::Result::Error>
|
||||
make_dispatch(const Configuration::Config& cfg)
|
||||
{
|
||||
Dispatch d;
|
||||
if (cfg.get_as<std::string>("async").has_value()) {
|
||||
const auto async_val = cfg.get_as<bool>("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<std::string>("capacity").has_value()) {
|
||||
const auto cap_val = cfg.get_as<std::size_t>("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<std::string>("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<std::size_t, Void::Result::Error>
|
||||
positive_size_or(const Configuration::Config& cfg,
|
||||
std::string_view key,
|
||||
std::size_t fallback)
|
||||
{
|
||||
if (!cfg.get_as<std::string>(key).has_value()) {
|
||||
return fallback;
|
||||
}
|
||||
const auto parsed = cfg.get_as<std::size_t>(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<std::shared_ptr<Logger>, 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<std::string>("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<std::size_t>(
|
||||
8ULL * 1024ULL * 1024ULL, dispatch.capacity * 1024ULL),
|
||||
.max_fields = 64,
|
||||
.max_scopes = 64},
|
||||
.failure_policy = FailurePolicy::Quarantine,
|
||||
.suppress_reentrancy = true};
|
||||
|
||||
std::vector<std::shared_ptr<Logger>> 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<ConsoleLogger>(
|
||||
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<Logger>{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<Logger>{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<bool>("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<Logger>{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<Logger>{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<SyslogLogger>(
|
||||
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<Logger> root;
|
||||
if (sinks.empty()) {
|
||||
root = std::make_shared<NullLogger>(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<MultiLogger>(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
|
||||
@@ -0,0 +1,4 @@
|
||||
void_add_module(LogConfig
|
||||
INTERNAL_DEPS Log Configuration Functional
|
||||
EXTRA_HEADERS Void/Log/FromConfig.hpp
|
||||
)
|
||||
@@ -12,4 +12,10 @@ namespace Void::Log::Detail
|
||||
static State s;
|
||||
return s;
|
||||
}
|
||||
} // namespace Void::Log::Detail
|
||||
|
||||
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept
|
||||
{
|
||||
static thread_local std::vector<const SinkRegistration*> stack;
|
||||
return stack;
|
||||
}
|
||||
} // namespace Void::Log::Detail
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
@@ -0,0 +1,26 @@
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/LoggingAdapter.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
|
||||
#include <atomic>
|
||||
|
||||
int main()
|
||||
{
|
||||
std::atomic<int> seen{0};
|
||||
auto sink = std::make_shared<Void::Logging::CallbackLogger>(
|
||||
[&](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;
|
||||
}
|
||||
@@ -0,0 +1,372 @@
|
||||
#include <Void/Log/FileLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/Logger.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <stdexcept>
|
||||
#include <stop_token>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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<int> 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<bool> destroyed{false};
|
||||
struct OwnerFlag {
|
||||
std::atomic<bool>* flag;
|
||||
~OwnerFlag() { flag->store(true, std::memory_order_release); }
|
||||
};
|
||||
auto owner = std::make_shared<OwnerFlag>(&destroyed);
|
||||
|
||||
std::mutex mu;
|
||||
std::condition_variable cv;
|
||||
bool in_cb = false;
|
||||
bool release_cb = false;
|
||||
std::atomic<bool> self_drain_blocked{false};
|
||||
std::atomic<int> 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<Void::Log::DrainResult> dr{Void::Log::DrainResult::not_found};
|
||||
std::atomic<bool> 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<bool> in_sink{false};
|
||||
std::vector<std::string> 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<CallbackLogger>(
|
||||
[&](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<std::int32_t>(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<CallbackLogger> qsink;
|
||||
bool trigger_reenter = true;
|
||||
qsink = std::make_shared<CallbackLogger>(
|
||||
[&](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<std::int32_t>(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<std::int32_t>(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<bool> 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<std::int32_t>(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<MultiLogger>();
|
||||
auto child = std::make_shared<MultiLogger>();
|
||||
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<std::int32_t>(LogErrorCode::cycle_detected));
|
||||
for (int i = 0; i < 7; ++i) {
|
||||
expect(root->try_add(std::make_shared<NullLogger>()).has_value());
|
||||
}
|
||||
auto ninth = root->try_add(std::make_shared<NullLogger>());
|
||||
expect(!ninth.has_value());
|
||||
expect_eq(ninth.error().code().value,
|
||||
static_cast<std::int32_t>(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<char>(ifs)), {}};
|
||||
expect(content.find("before-reopen") != std::string::npos);
|
||||
expect(content.find("after-reopen") != std::string::npos);
|
||||
std::filesystem::remove_all(base);
|
||||
}
|
||||
@@ -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<char>(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<char>(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<char>(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({});
|
||||
}
|
||||
Reference in new issue
Block a user