diff --git a/CLAUDE.md b/CLAUDE.md index 8256a3f..6b910fd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -119,7 +119,9 @@ Deriving a sink: 2. **Optionally override `on_flush(std::span)`** — for batch I/O. 3. **Call `flush()` in your derived destructor** — the base destructor only stops/joins the worker (calling a pure virtual from `~Logger` is UB); entries left after your destructor are silently dropped. -Shipped sinks: `ConsoleLogger` (colors via Stacktrace), `FileLogger`, `RotatingFileLogger` (size rotation, max files), `NullLogger`, `CallbackLogger`, `MultiLogger` (tee; uses `Logger::relay`), `SyslogLogger` (POSIX). Sinks accept a `Formatter` (`PatternFormatter` with `{time}/{level}/{scopes}/{message}/...` placeholders, `JsonLinesFormatter`, `LogfmtFormatter`). +Shipped sinks: `ConsoleLogger` (color via a default colored `PatternFormatter`; `set_color_policy`), `FileLogger`, `RotatingFileLogger`, `SplitFileLogger` (one file per level under a dir + a combined `all.log`), `HistoryLogger` (always-on, never-filtered durable JSON-lines audit trail, rolling), `NullLogger`, `CallbackLogger`, `MultiLogger` (tee; uses `Logger::relay`), `SyslogLogger` (POSIX). File rotation is factored into `Detail::RollingFile` (size + max-files), shared by the rotating/split/history sinks. + +`Formatter`s: `PatternFormatter`, `JsonLinesFormatter`, `LogfmtFormatter`. The pattern grammar is `{token:spec}` where spec = `[align][width][,color]` (align `<`/`>`/`^`, width like std::format, color a name or `auto`=level color). Built-in tokens: `time/level/thread/scopes/message/file/line/kind`; unknown tokens resolve against `register_token(name, fn)` custom renderers, then `Entry::fields` by key, else stay literal. `ColorPolicy{enabled, level_colors, token_colors}` (`ColorPolicy::defaults()`) drives color; only `PatternFormatter` colorizes, never file/JSON/logfmt. Structured fields come from `Logging::FieldScope` (RAII, thread-local, snapshotted into `Entry::fields` like scopes). `from_config` sink keys: `console/file/rotating/split/history/syslog` plus `log.color`, `log.split.dir`, `log.split.combined`, `log.history.path`, etc. `Logging::from_config(cfg)` builds the whole tree from `Configuration::Config` keys (`log.sinks`, `log.level`, `log.format`, `log.async`, ...); `apply_facade_config` sets facade levels. diff --git a/include/Void/Log/ConsoleLogger.hpp b/include/Void/Log/ConsoleLogger.hpp index f5099b8..9c18447 100644 --- a/include/Void/Log/ConsoleLogger.hpp +++ b/include/Void/Log/ConsoleLogger.hpp @@ -37,12 +37,21 @@ namespace Void::Logging ConsoleLogger(ConsoleLogger&&) = delete; ConsoleLogger& operator=(ConsoleLogger&&) = delete; - /// Install a formatter. Call before logging starts. + /// Install a formatter. Call before logging starts. Replaces + /// the default colored "[level] message" rendering. void set_formatter(std::shared_ptr formatter) { m_formatter = std::move(formatter); } + /// Customize the default formatter's colors (level→color, + /// per-token colors, on/off). No effect once a custom + /// formatter is installed via set_formatter. + void set_color_policy(ColorPolicy policy) + { + m_default.set_color_policy(std::move(policy)); + } + protected: void write(const Entry& entry) override; @@ -51,6 +60,9 @@ namespace Void::Logging std::ostream& m_out; std::shared_ptr m_formatter; + // Used when no custom formatter is installed: "[level] message" + // with the level colorized by the level→color policy. + PatternFormatter m_default{"[{level:,auto}] {message}"}; }; } // namespace Void::Logging diff --git a/include/Void/Log/Detail/RollingFile.hpp b/include/Void/Log/Detail/RollingFile.hpp new file mode 100644 index 0000000..13b20a7 --- /dev/null +++ b/include/Void/Log/Detail/RollingFile.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include +#include +#include +#include + +namespace Void::Logging::Detail +{ + struct RollingFileOptions { + std::size_t max_bytes = 1024 * 1024; + std::size_t max_files = 5; + }; + + /// A single append-only log file with size-based rotation. Not thread + /// safe — each sink owns one and drives it from its single worker. + /// + /// On reaching max_bytes the files shift (`app.log` → `app.log.1` → …); + /// at most max_files rotated files are kept, the oldest is removed. With + /// max_files == 0 the file is truncated on rotation instead of kept. + class RollingFile + { + public: + + RollingFile(std::filesystem::path path, RollingFileOptions opt); + + /// Open for append (creating parent dirs). False on failure. + [[nodiscard]] bool open(); + + /// Append a line (a trailing '\n' is added) and rotate if the + /// file then exceeds max_bytes. No-op if not open. + void write(std::string_view line); + + void flush(); + + [[nodiscard]] bool is_open() const noexcept + { + return m_file.is_open(); + } + + [[nodiscard]] const std::filesystem::path& path() const noexcept + { + return m_path; + } + + private: + + void rotate(); + + std::filesystem::path m_path; + RollingFileOptions m_opt; + std::ofstream m_file; + std::size_t m_current_bytes{0}; + }; + +} // namespace Void::Logging::Detail diff --git a/include/Void/Log/Entry.hpp b/include/Void/Log/Entry.hpp index e464dad..5c63276 100644 --- a/include/Void/Log/Entry.hpp +++ b/include/Void/Log/Entry.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace Void::Logging @@ -48,6 +49,13 @@ namespace Void::Logging /// the last element; for ScopeExit it reflects the stack *before* /// the pop. std::vector scopes{}; + + /// Structured key/value fields attached to this entry — a frozen + /// snapshot of the thread-local FieldScope stack at log time. + /// Formatters expose them as custom pattern tokens + /// (`{field:key}`) and in JSON/logfmt output. Later duplicate + /// keys win. + std::vector> fields{}; }; } // namespace Void::Logging diff --git a/include/Void/Log/Field.hpp b/include/Void/Log/Field.hpp new file mode 100644 index 0000000..64526df --- /dev/null +++ b/include/Void/Log/Field.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace Void::Logging +{ + /// RAII structured-field context, per thread. While alive, the fields + /// it pushes are attached to every Entry produced on this thread (they + /// appear in Entry::fields and so in `{field:key}` pattern tokens and + /// JSON/logfmt output). Nest freely; later duplicate keys win. + /// + /// Logging::FieldScope req{"request_id", id}; + /// logger.info("handling"); // entry carries request_id= + class FieldScope + { + public: + + FieldScope(std::string key, std::string value); + explicit FieldScope( + std::initializer_list> + fields); + + ~FieldScope() noexcept; + + FieldScope(const FieldScope&) = delete; + FieldScope& operator=(const FieldScope&) = delete; + FieldScope(FieldScope&&) noexcept; + FieldScope& operator=(FieldScope&&) = delete; + + private: + + std::size_t m_count{0}; // how many entries to pop + bool m_active{true}; + }; + + /// Snapshot view of this thread's active fields, outermost first. + [[nodiscard]] std::span> + current_fields() noexcept; + +} // namespace Void::Logging diff --git a/include/Void/Log/Formatter.hpp b/include/Void/Log/Formatter.hpp index 60cbf58..1b4a573 100644 --- a/include/Void/Log/Formatter.hpp +++ b/include/Void/Log/Formatter.hpp @@ -3,9 +3,10 @@ #include #include -#include +#include #include #include +#include #include namespace Void::Logging @@ -25,20 +26,65 @@ namespace Void::Logging format(const Entry& entry) const = 0; }; - /// Placeholder-based text formatter. - /// - /// Supported placeholders inside the pattern string: - /// {time} — ISO-8601 UTC timestamp with milliseconds - /// {level} — level name (Trace, Debug, ...) - /// {thread} — producing thread id - /// {scopes} — "a.b.c " breadcrumb of the scope stack (empty if none) - /// {message} — the message text - /// {file} — source file basename - /// {line} — source line - /// {kind} — Message / ScopeEnter / ScopeExit - /// Everything else is copied verbatim. Unknown {names} stay literal. - /// - /// Default pattern: "{time} [{level}] {scopes}{message}" + // ── colour ──────────────────────────────────────────────────────────── + + enum class AnsiColor { + Default, + Black, + Red, + Green, + Yellow, + Blue, + Magenta, + Cyan, + White, + BrightBlack, + BrightRed, + BrightGreen, + BrightYellow, + BrightBlue, + BrightMagenta, + BrightCyan, + BrightWhite, + }; + + /// Parse a colour name ("red", "bright_black", "cyan", ...). Returns + /// AnsiColor::Default for unknown names. + [[nodiscard]] AnsiColor parse_color(std::string_view name) noexcept; + + /// SGR escape for a colour ("\x1b[31m"); empty for Default. + [[nodiscard]] std::string_view ansi_code(AnsiColor color) noexcept; + + inline constexpr std::string_view kAnsiReset = "\x1b[0m"; + + /// Colour configuration for a PatternFormatter. Disabled by default; + /// ConsoleLogger turns it on when the stream is a colour-capable TTY. + struct ColorPolicy { + bool enabled = false; + std::unordered_map level_colors; + std::unordered_map token_colors; + + /// Sensible per-level defaults (Trace dim → Fatal bright magenta). + [[nodiscard]] static ColorPolicy defaults(); + }; + + // ── PatternFormatter ────────────────────────────────────────────────── + // + // Placeholder pattern with per-token appearance and colour. + // + // {token} — substitute the token + // {token:spec} — spec = [align][width][,colour] + // align : '<' left (default), '>' right, '^' + // centre width : decimal field width (padded with + // spaces) colour: a name ("cyan") or "auto" (= + // level colour) + // + // Built-in tokens: time, level, thread, scopes, message, file, line, + // kind. An unknown token resolves against registered custom tokens + // (register_token), then against Entry::fields by key, and otherwise + // stays literal — so `{request_id:>8}` prints a structured field. + // + // Default pattern: "{time} [{level}] {scopes}{message}" class PatternFormatter final : public Formatter { public: @@ -48,31 +94,47 @@ namespace Void::Logging [[nodiscard]] std::string format(const Entry& entry) const override; + /// Add a custom token. `name` becomes usable as `{name}`. + /// Overrides a built-in of the same name. + void register_token(std::string name, + std::function + renderer); + + void set_color_policy(ColorPolicy policy) + { + m_colors = std::move(policy); + } + + [[nodiscard]] const ColorPolicy& color_policy() const noexcept + { + return m_colors; + } + private: - enum class Token { - Literal, - Time, - LevelName, - Thread, - Scopes, - Message, - File, - Line, - Kind - }; + enum class Align { Left, Right, Center }; + enum class ColorMode { None, Auto, Fixed }; struct Segment { - Token token; - std::string literal; // only for Token::Literal + bool literal{true}; + std::string text; // literal text, or the token name + Align align{Align::Left}; + std::size_t width{0}; + ColorMode color_mode{ColorMode::None}; + AnsiColor color{AnsiColor::Default}; }; + [[nodiscard]] std::string render_token(const Segment& seg, + const Entry& entry) const; + std::vector m_segments; + std::unordered_map> + m_custom; + ColorPolicy m_colors; }; - /// One compact JSON object per entry: - /// {"time":"...","level":"Info","thread":"...","scopes":[...], - /// "message":"...","file":"...","line":N} + /// One compact JSON object per entry (includes fields when present). class JsonLinesFormatter final : public Formatter { public: @@ -80,8 +142,7 @@ namespace Void::Logging [[nodiscard]] std::string format(const Entry& entry) const override; }; - /// logfmt: time=... level=... thread=... msg="..." (scopes/file/line - /// included when present). + /// logfmt: time=... level=... thread=... msg="..." plus scopes/fields. class LogfmtFormatter final : public Formatter { public: diff --git a/include/Void/Log/History.hpp b/include/Void/Log/History.hpp new file mode 100644 index 0000000..4b4e528 --- /dev/null +++ b/include/Void/Log/History.hpp @@ -0,0 +1,65 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +namespace Void::Logging +{ + struct HistoryOptions { + std::size_t max_bytes = 8 * 1024 * 1024; + std::size_t max_files = 10; + Mode mode = Mode::Async; + std::size_t capacity = 1024; + OverflowPolicy policy = OverflowPolicy::Block; + }; + + /// Always-on, never-level-filtered durable history log: an append-only + /// rolling file capturing every entry as a machine-readable audit + /// trail. Defaults to a JsonLines format. Distinct from level-split or + /// app logs — its contract is "keep everything, durably". + class HistoryLogger final : public Logger + { + public: + + using Options = HistoryOptions; + + explicit HistoryLogger(std::filesystem::path path, + Options options = {}); + + ~HistoryLogger() noexcept override; + + HistoryLogger(const HistoryLogger&) = delete; + HistoryLogger& operator=(const HistoryLogger&) = delete; + HistoryLogger(HistoryLogger&&) = delete; + HistoryLogger& operator=(HistoryLogger&&) = delete; + + [[nodiscard]] static Void::Result:: + Result, Void::Result::Error> + open(std::filesystem::path path, Options options = {}); + + /// Replace the default JsonLines rendering. + void set_formatter(std::shared_ptr formatter) + { + m_formatter = std::move(formatter); + } + + protected: + + void write(const Entry& entry) override; + void on_flush(std::span entries) override; + + private: + + Detail::RollingFile m_file; + std::shared_ptr m_formatter; + }; + +} // namespace Void::Logging diff --git a/include/Void/Log/RotatingFileLogger.hpp b/include/Void/Log/RotatingFileLogger.hpp index 7712033..01a7fed 100644 --- a/include/Void/Log/RotatingFileLogger.hpp +++ b/include/Void/Log/RotatingFileLogger.hpp @@ -2,12 +2,12 @@ #include #include +#include #include #include #include #include -#include #include #include @@ -70,12 +70,9 @@ namespace Void::Logging private: void append(const Entry& entry); - void rotate_if_needed(); std::filesystem::path m_path; - Options m_options; - std::ofstream m_file; - std::size_t m_current_bytes{0}; + Detail::RollingFile m_file; std::shared_ptr m_formatter; }; diff --git a/include/Void/Log/SplitFileLogger.hpp b/include/Void/Log/SplitFileLogger.hpp new file mode 100644 index 0000000..6d7e403 --- /dev/null +++ b/include/Void/Log/SplitFileLogger.hpp @@ -0,0 +1,84 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace Void::Logging +{ + /// Options for SplitFileLogger (namespace scope to avoid the GCC + /// nested-default-arg trap). + struct SplitFileOptions { + /// One combined file `/all.log` with every level, in addition + /// to the per-level files. + bool combined = true; + 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; + }; + + /// File sink that routes each entry to a per-level file + /// (`/.log`, e.g. `error.log`, lazily created) and, when + /// enabled, also to a single combined `/all.log`. Each file rolls + /// independently. Async by default. An installed Formatter replaces the + /// default "[level] message" rendering (no color in files). + class SplitFileLogger final : public Logger + { + public: + + using Options = SplitFileOptions; + + explicit SplitFileLogger(std::filesystem::path dir, + Options options = {}); + + ~SplitFileLogger() noexcept override; + + SplitFileLogger(const SplitFileLogger&) = delete; + SplitFileLogger& operator=(const SplitFileLogger&) = delete; + SplitFileLogger(SplitFileLogger&&) = delete; + SplitFileLogger& operator=(SplitFileLogger&&) = delete; + + /// Non-throwing factory (fails if the directory cannot be + /// created). + [[nodiscard]] static Void::Result:: + Result, Void::Result::Error> + open(std::filesystem::path dir, Options options = {}); + + void set_formatter(std::shared_ptr formatter) + { + m_formatter = std::move(formatter); + } + + [[nodiscard]] const std::filesystem::path& dir() const noexcept + { + return m_dir; + } + + protected: + + void write(const Entry& entry) override; + void on_flush(std::span entries) override; + + private: + + Detail::RollingFile& file_for(Level level); + void append(const Entry& entry); + + std::filesystem::path m_dir; + Options m_options; + std::map m_per_level; + std::unique_ptr m_combined; + std::shared_ptr m_formatter; + }; + +} // namespace Void::Logging diff --git a/src/Log/ConsoleLogger.cpp b/src/Log/ConsoleLogger.cpp index cd3f2df..af43bf4 100644 --- a/src/Log/ConsoleLogger.cpp +++ b/src/Log/ConsoleLogger.cpp @@ -1,86 +1,35 @@ -#include #include #ifdef VOID_HAS_STACKTRACE #include #endif -#include #include #include -#include -#include namespace Void::Logging { namespace { -#ifdef VOID_HAS_STACKTRACE - std::string_view color_for(Level level) + ColorPolicy console_default_policy() { - using namespace Void::Stacktrace::Color; -#ifdef VOID_HAS_ENUM_REFLECTION - static constexpr auto enumerators = - std::define_static_array(std::meta::enumerators_of(^^Level)); - template for (constexpr auto e : enumerators) { - if (level == [:e:]) { - if constexpr (std::meta::identifier_of(e) == "Trace") - return dim; - if constexpr (std::meta::identifier_of(e) == "Debug") - return cyan; - if constexpr (std::meta::identifier_of(e) == "Info") - return bold_cyan; - if constexpr (std::meta::identifier_of(e) == "Warning") - return bold_yellow; - if constexpr (std::meta::identifier_of(e) == "Error") - return bold_red; - if constexpr (std::meta::identifier_of(e) == "Fatal") - return bold_magenta; - return reset; - } - } - return reset; -#else - switch (level) { - case Level::Trace: - return dim; - case Level::Debug: - return cyan; - case Level::Info: - return bold_cyan; - case Level::Warning: - return bold_yellow; - case Level::Error: - return bold_red; - case Level::Fatal: - return bold_magenta; - default: - return reset; - } -#endif - } -#endif - - std::string format_entry(const Entry& entry) - { - auto level_str = std::string{to_string(entry.level)}; + ColorPolicy p = ColorPolicy::defaults(); #ifdef VOID_HAS_STACKTRACE - using namespace Void::Stacktrace::Color; - return std::format("[{}] {}\n", - apply(color_for(entry.level), level_str), - entry.message); + // Honor the global color toggle when Stacktrace is present. + p.enabled = Void::Stacktrace::Color::g_color_enabled; #else - return std::format("[{}] {}\n", level_str, entry.message); + p.enabled = false; #endif + return p; } } // namespace - ConsoleLogger::ConsoleLogger(std::ostream& out, - Mode mode, + ConsoleLogger::ConsoleLogger(std::ostream& out, Mode mode, std::size_t capacity) : Logger(mode, capacity), m_out(out) { + m_default.set_color_policy(console_default_policy()); } ConsoleLogger::ConsoleLogger() : ConsoleLogger(std::cerr) {} @@ -89,12 +38,8 @@ namespace Void::Logging void ConsoleLogger::write(const Entry& entry) { - if (m_formatter) { - m_out << m_formatter->format(entry) << '\n'; - } - else { - m_out << format_entry(entry); - } + const Formatter& fmt = m_formatter ? *m_formatter : m_default; + m_out << fmt.format(entry) << '\n'; m_out.flush(); } diff --git a/src/Log/Field.cpp b/src/Log/Field.cpp new file mode 100644 index 0000000..475259e --- /dev/null +++ b/src/Log/Field.cpp @@ -0,0 +1,50 @@ +#include + +#include + +namespace Void::Logging +{ + + namespace + { + thread_local std::vector> t_fields; + } // namespace + + FieldScope::FieldScope(std::string key, std::string value) + { + t_fields.emplace_back(std::move(key), std::move(value)); + m_count = 1; + } + + FieldScope::FieldScope( + std::initializer_list> fields) + { + for (const auto& [k, v] : fields) { + t_fields.emplace_back(k, v); + } + m_count = fields.size(); + } + + FieldScope::~FieldScope() noexcept + { + if (!m_active) { + return; + } + for (std::size_t i = 0; i < m_count && !t_fields.empty(); ++i) { + t_fields.pop_back(); + } + } + + FieldScope::FieldScope(FieldScope&& other) noexcept + : m_count(other.m_count), m_active(other.m_active) + { + other.m_active = false; + } + + std::span> + current_fields() noexcept + { + return t_fields; + } + +} // namespace Void::Logging diff --git a/src/Log/Formatter.cpp b/src/Log/Formatter.cpp index 60f012f..0b5790f 100644 --- a/src/Log/Formatter.cpp +++ b/src/Log/Formatter.cpp @@ -1,6 +1,8 @@ #include #include +#include +#include #include #include #include @@ -10,6 +12,104 @@ namespace Void::Logging { + // ── colour ──────────────────────────────────────────────────────────── + + AnsiColor parse_color(std::string_view name) noexcept + { + struct Pair { + std::string_view name; + AnsiColor color; + }; + static constexpr std::array table{{ + {"black", AnsiColor::Black}, + {"red", AnsiColor::Red}, + {"green", AnsiColor::Green}, + {"yellow", AnsiColor::Yellow}, + {"blue", AnsiColor::Blue}, + {"magenta", AnsiColor::Magenta}, + {"cyan", AnsiColor::Cyan}, + {"white", AnsiColor::White}, + {"bright_black", AnsiColor::BrightBlack}, + {"bright_red", AnsiColor::BrightRed}, + {"bright_green", AnsiColor::BrightGreen}, + {"bright_yellow", AnsiColor::BrightYellow}, + {"bright_blue", AnsiColor::BrightBlue}, + {"bright_magenta", AnsiColor::BrightMagenta}, + {"bright_cyan", AnsiColor::BrightCyan}, + {"bright_white", AnsiColor::BrightWhite}, + }}; + for (const auto& [n, c] : table) { + if (n == name) { + return c; + } + } + // "dim"/"gray" aliases + if (name == "dim" || name == "gray" || name == "grey") { + return AnsiColor::BrightBlack; + } + return AnsiColor::Default; + } + + 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"; + } + return ""; + } + + ColorPolicy ColorPolicy::defaults() + { + ColorPolicy p; + p.enabled = true; + p.level_colors = { + {Level::Trace, AnsiColor::BrightBlack}, + {Level::Debug, AnsiColor::Cyan}, + {Level::Info, AnsiColor::BrightCyan}, + {Level::Warning, AnsiColor::BrightYellow}, + {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 { @@ -61,24 +161,35 @@ namespace Void::Logging } return std::filesystem::path{file}.filename().string(); } + + const std::string* find_field(const Entry& entry, + std::string_view key) + { + const std::string* found = nullptr; + for (const auto& [k, v] : entry.fields) { + if (k == key) { + found = &v; // later duplicates win + } + } + return found; + } } // namespace } // namespace FormatDetail - // ============================================================================= - // PatternFormatter - // ============================================================================= + // ── PatternFormatter ────────────────────────────────────────────────── PatternFormatter::PatternFormatter(std::string pattern) { - using FormatDetail::scope_breadcrumb; - std::string literal; std::string_view rest{pattern}; auto flush_literal = [&] { if (!literal.empty()) { - m_segments.push_back({Token::Literal, std::move(literal)}); - literal = {}; + Segment seg; + seg.literal = true; + seg.text = std::move(literal); + m_segments.push_back(std::move(seg)); + literal.clear(); } }; @@ -95,85 +206,172 @@ namespace Void::Logging literal += rest; break; } - const auto name = rest.substr(1, close - 1); - Token token = Token::Literal; - if (name == "time") { - token = Token::Time; - } else if (name == "level") { - token = Token::LevelName; - } else if (name == "thread") { - token = Token::Thread; - } else if (name == "scopes") { - token = Token::Scopes; - } else if (name == "message") { - token = Token::Message; - } else if (name == "file") { - token = Token::File; - } else if (name == "line") { - token = Token::Line; - } else if (name == "kind") { - token = Token::Kind; + const auto body = rest.substr(1, close - 1); // inside braces + rest.remove_prefix(close + 1); + + // Split "token:spec". + std::string_view token = body; + std::string_view spec; + if (const auto colon = body.find(':'); + colon != std::string_view::npos) { + token = body.substr(0, colon); + spec = body.substr(colon + 1); } - if (token == Token::Literal) { - // Unknown placeholder — keep it verbatim. - literal += rest.substr(0, close + 1); - } else { - flush_literal(); - m_segments.push_back({token, {}}); + Segment seg; + 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) { + color_name = spec.substr(comma + 1); + spec = spec.substr(0, comma); } - rest.remove_prefix(close + 1); + if (!spec.empty() && (spec.front() == '<' || spec.front() == '>' || + spec.front() == '^')) { + seg.align = spec.front() == '>' ? Align::Right + : spec.front() == '^' ? Align::Center + : Align::Left; + spec.remove_prefix(1); + } + if (!spec.empty()) { + std::size_t w = 0; + std::from_chars(spec.data(), spec.data() + spec.size(), w); + seg.width = w; + } + if (!color_name.empty()) { + if (color_name == "auto") { + seg.color_mode = ColorMode::Auto; + } else { + seg.color_mode = ColorMode::Fixed; + seg.color = parse_color(color_name); + } + } + + flush_literal(); + m_segments.push_back(std::move(seg)); } flush_literal(); } + void PatternFormatter::register_token( + std::string name, std::function renderer) + { + m_custom.emplace(std::move(name), std::move(renderer)); + } + + std::string PatternFormatter::render_token(const Segment& seg, + const Entry& entry) const + { + using namespace FormatDetail; + const std::string& name = seg.text; + if (name == "time") { + return iso8601(entry.timestamp); + } + if (name == "level") { + return std::string{to_string(entry.level)}; + } + if (name == "thread") { + return thread_str(entry.thread_id); + } + if (name == "scopes") { + auto crumb = scope_breadcrumb(entry.scopes); + return crumb.empty() ? std::string{} : crumb + " "; + } + if (name == "message") { + return entry.message; + } + if (name == "file") { + return file_basename(entry); + } + if (name == "line") { + return std::to_string(entry.location.line()); + } + 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)) { + return *v; + } + // Unknown — keep literal so misspellings are visible. + return "{" + name + "}"; + } + std::string PatternFormatter::format(const Entry& entry) const { std::string out; for (const auto& seg : m_segments) { - switch (seg.token) { - case Token::Literal: - out += seg.literal; - break; - case Token::Time: - out += FormatDetail::iso8601(entry.timestamp); - break; - case Token::LevelName: - out += to_string(entry.level); - break; - case Token::Thread: - out += FormatDetail::thread_str(entry.thread_id); - break; - case Token::Scopes: - { - auto crumb = - FormatDetail::scope_breadcrumb(entry.scopes); - if (!crumb.empty()) { - out += crumb; - out += ' '; - } - break; - } - case Token::Message: - out += entry.message; - break; - case Token::File: - out += FormatDetail::file_basename(entry); - break; - case Token::Line: - out += std::to_string(entry.location.line()); - break; - case Token::Kind: - out += FormatDetail::kind_str(entry.kind); - break; + if (seg.literal) { + out += seg.text; + continue; } + + 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) { + case Align::Left: + text.append(pad, ' '); + break; + case Align::Right: + text.insert(text.begin(), + static_cast(pad), ' '); + break; + case Align::Center: + { + const std::size_t l = pad / 2; + text.insert(text.begin(), + static_cast(l), ' '); + text.append(pad - l, ' '); + break; + } + } + } + + // Colour. + if (m_colors.enabled && seg.color_mode != ColorMode::None) { + AnsiColor color = AnsiColor::Default; + if (seg.color_mode == ColorMode::Auto) { + if (const auto it = m_colors.level_colors.find(entry.level); + it != m_colors.level_colors.end()) { + color = it->second; + } + } else { + color = seg.color; + } + if (color != AnsiColor::Default) { + out += ansi_code(color); + out += text; + out += kAnsiReset; + 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() && + it->second != AnsiColor::Default) { + out += ansi_code(it->second); + out += text; + out += kAnsiReset; + continue; + } + } + out += text; } return out; } - // ============================================================================= - // JsonLinesFormatter - // ============================================================================= + // ── JsonLinesFormatter ──────────────────────────────────────────────── std::string JsonLinesFormatter::format(const Entry& entry) const { @@ -193,6 +391,13 @@ namespace Void::Logging } o.emplace_back("scopes", std::move(arr)); } + if (!entry.fields.empty()) { + auto fobj = Json::object(); + for (const auto& [k, v] : entry.fields) { + fobj.as_object().emplace_back(k, Json::Value{v}); + } + o.emplace_back("fields", std::move(fobj)); + } o.emplace_back("message", Json::Value{entry.message}); if (auto file = FormatDetail::file_basename(entry); !file.empty()) { o.emplace_back("file", Json::Value{file}); @@ -203,9 +408,7 @@ namespace Void::Logging return Json::serialize(obj); } - // ============================================================================= - // LogfmtFormatter - // ============================================================================= + // ── LogfmtFormatter ─────────────────────────────────────────────────── namespace { @@ -236,6 +439,12 @@ namespace Void::Logging out += " scopes="; out += crumb; } + for (const auto& [k, v] : entry.fields) { + out += ' '; + out += k; + out += '='; + append_quoted(out, v); + } if (auto file = FormatDetail::file_basename(entry); !file.empty()) { out += " file="; out += file; diff --git a/src/Log/FromConfig.cpp b/src/Log/FromConfig.cpp index d965b36..c773f80 100644 --- a/src/Log/FromConfig.cpp +++ b/src/Log/FromConfig.cpp @@ -2,9 +2,11 @@ #include #include #include +#include #include #include #include +#include #include #include @@ -104,9 +106,13 @@ namespace Void::Logging { const auto format = cfg.get_or("format", "default"); if (format == "pattern") { - return std::make_shared( + auto fmt = std::make_shared( std::string{cfg.get_or( "pattern", "{time} [{level}] {scopes}{message}")}); + if (cfg.get_or_as("color", false)) { + fmt->set_color_policy(ColorPolicy::defaults()); + } + return fmt; } if (format == "json") { return std::make_shared(); @@ -200,6 +206,54 @@ namespace Void::Logging (*sink)->set_formatter(formatter); } sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "split") { + const auto dir = sub.get_or("split.dir"); + if (dir.empty()) { + return Void::Result::fail( + "Logging::from_config: sink 'split' needs " + "split.dir"); + } + SplitFileLogger::Options opt; + opt.combined = + sub.get_or_as("split.combined", true); + opt.max_bytes = + sub.get_or_as("split.max_kb", 1024) * 1024; + opt.max_files = + sub.get_or_as("split.max_files", 5); + opt.mode = dispatch.mode; + opt.capacity = dispatch.capacity; + opt.policy = dispatch.policy; + auto sink = SplitFileLogger::open( + std::filesystem::path{dir}, opt); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + if (formatter) { + (*sink)->set_formatter(formatter); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); + } else if (name == "history") { + const auto path = sub.get_or("history.path"); + if (path.empty()) { + return Void::Result::fail( + "Logging::from_config: sink 'history' needs " + "history.path"); + } + HistoryLogger::Options opt; + opt.max_bytes = + sub.get_or_as("history.max_kb", 8192) * + 1024; + opt.max_files = + sub.get_or_as("history.max_files", 10); + opt.mode = dispatch.mode; + opt.capacity = dispatch.capacity; + opt.policy = dispatch.policy; + auto sink = HistoryLogger::open( + std::filesystem::path{path}, opt); + if (!sink.has_value()) { + return Void::Result::fail(std::move(sink).error()); + } + sinks.push_back(std::shared_ptr{std::move(*sink)}); } else if (name == "syslog") { #ifdef VOID_HAS_SYSLOG const auto identity = sub.get_or("syslog.identity"); diff --git a/src/Log/History.cpp b/src/Log/History.cpp new file mode 100644 index 0000000..e4181de --- /dev/null +++ b/src/Log/History.cpp @@ -0,0 +1,55 @@ +#include +#include + +#include +#include + +namespace Void::Logging +{ + + HistoryLogger::HistoryLogger(std::filesystem::path path, Options options) + : Logger(options.mode, options.capacity, options.policy), + m_file( + std::move(path), + Detail::RollingFileOptions{options.max_bytes, options.max_files}), + m_formatter(std::make_shared()) + { + if (!m_file.open()) { + throw std::runtime_error(std::format( + "HistoryLogger: cannot open '{}'", m_file.path().string())); + } + // History captures everything regardless of the global facade / + // per-module filters; its own minimum level stays Trace. + set_level(Level::Trace); + Void::Log::debug("Log.History", "history log at '{}'", + m_file.path().string()); + } + + Void::Result::Result, Void::Result::Error> + HistoryLogger::open(std::filesystem::path path, Options options) + { + try { + return Void::Result::ok( + std::make_unique(std::move(path), options)); + } catch (const std::exception& e) { + return Void::Result::fail(std::string{e.what()}); + } + } + + HistoryLogger::~HistoryLogger() noexcept { flush(); } + + void HistoryLogger::write(const Entry& entry) + { + m_file.write(m_formatter->format(entry)); + m_file.flush(); + } + + void HistoryLogger::on_flush(std::span entries) + { + for (const auto& e : entries) { + m_file.write(m_formatter->format(e)); + } + m_file.flush(); + } + +} // namespace Void::Logging diff --git a/src/Log/Logger.cpp b/src/Log/Logger.cpp index 4916edd..5097143 100644 --- a/src/Log/Logger.cpp +++ b/src/Log/Logger.cpp @@ -1,3 +1,4 @@ +#include #include #include // std::exchange @@ -209,6 +210,7 @@ namespace Void::Logging } } + const auto fields = current_fields(); Entry entry{ .kind = Kind::Message, .level = level, @@ -217,6 +219,7 @@ namespace Void::Logging .location = location, .thread_id = std::this_thread::get_id(), .scopes = s_scope_stack, // snapshot — s_scope_stack is thread-local + .fields = {fields.begin(), fields.end()}, }; submit(std::move(entry)); @@ -299,6 +302,7 @@ namespace Void::Logging } } + const auto fields = current_fields(); Entry entry{ .kind = kind, .level = level, @@ -307,6 +311,7 @@ namespace Void::Logging .location = loc, .thread_id = std::this_thread::get_id(), .scopes = s_scope_stack, // snapshot at boundary time + .fields = {fields.begin(), fields.end()}, }; submit(std::move(entry)); diff --git a/src/Log/RollingFile.cpp b/src/Log/RollingFile.cpp new file mode 100644 index 0000000..41bd4b1 --- /dev/null +++ b/src/Log/RollingFile.cpp @@ -0,0 +1,76 @@ +#include + +#include +#include +#include + +namespace Void::Logging::Detail +{ + + RollingFile::RollingFile(std::filesystem::path path, RollingFileOptions opt) + : m_path(std::move(path)), m_opt(opt) + { + } + + bool RollingFile::open() + { + std::error_code ec; + if (m_path.has_parent_path()) { + std::filesystem::create_directories(m_path.parent_path(), ec); + } + if (std::filesystem::exists(m_path, ec)) { + m_current_bytes = static_cast( + std::filesystem::file_size(m_path, ec)); + } + m_file.open(m_path, std::ios::app); + return m_file.is_open(); + } + + void RollingFile::write(std::string_view line) + { + if (!m_file.is_open()) { + return; + } + m_file.write(line.data(), static_cast(line.size())); + m_file.put('\n'); + m_current_bytes += line.size() + 1; + if (m_current_bytes >= m_opt.max_bytes) { + rotate(); + } + } + + void RollingFile::flush() + { + if (m_file.is_open()) { + m_file.flush(); + } + } + + void RollingFile::rotate() + { + m_file.close(); + std::error_code ec; + + const auto numbered = [&](std::size_t n) { + auto p = m_path; + p += std::format(".{}", n); + return p; + }; + std::filesystem::remove(numbered(m_opt.max_files), ec); + for (std::size_t n = m_opt.max_files; n > 1; --n) { + const auto from = numbered(n - 1); + if (std::filesystem::exists(from, ec)) { + std::filesystem::rename(from, numbered(n), ec); + } + } + if (m_opt.max_files > 0) { + std::filesystem::rename(m_path, numbered(1), ec); + } else { + std::filesystem::remove(m_path, ec); + } + + m_file.open(m_path, std::ios::trunc); + m_current_bytes = 0; + } + +} // namespace Void::Logging::Detail diff --git a/src/Log/RotatingFileLogger.cpp b/src/Log/RotatingFileLogger.cpp index 9d835cf..4c83657 100644 --- a/src/Log/RotatingFileLogger.cpp +++ b/src/Log/RotatingFileLogger.cpp @@ -3,7 +3,6 @@ #include #include -#include namespace Void::Logging { @@ -11,20 +10,14 @@ namespace Void::Logging RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path, Options options) : Logger(options.mode, options.capacity, options.policy), m_path(path), - m_options(options) + m_file(path, Detail::RollingFileOptions{options.max_bytes, + options.max_files}) { - std::error_code ec; - if (std::filesystem::exists(m_path, ec)) { - m_current_bytes = static_cast( - std::filesystem::file_size(m_path, ec)); - } - m_file.open(m_path, std::ios::app); - if (!m_file.is_open()) { + if (!m_file.open()) { throw std::runtime_error(std::format( "RotatingFileLogger: cannot open '{}'", m_path.string())); } - Void::Log::debug("Log.RotatingFile", "opened '{}' ({} bytes)", - m_path.string(), m_current_bytes); + Void::Log::debug("Log.RotatingFile", "opened '{}'", m_path.string()); } Void::Result::Result, @@ -46,7 +39,6 @@ namespace Void::Logging { append(entry); m_file.flush(); - rotate_if_needed(); } void RotatingFileLogger::on_flush(std::span entries) @@ -55,55 +47,16 @@ namespace Void::Logging append(entry); } m_file.flush(); - rotate_if_needed(); } void RotatingFileLogger::append(const Entry& entry) { - std::string line; if (m_formatter) { - line = m_formatter->format(entry); + m_file.write(m_formatter->format(entry)); } else { - line = - std::format("[{}] {}", to_string(entry.level), entry.message); + m_file.write( + std::format("[{}] {}", to_string(entry.level), entry.message)); } - line += '\n'; - m_file << line; - m_current_bytes += line.size(); - } - - void RotatingFileLogger::rotate_if_needed() - { - if (m_current_bytes < m_options.max_bytes) { - return; - } - - m_file.close(); - std::error_code ec; - - // Shift app.log.(N-1) -> app.log.N, ..., app.log -> app.log.1; - // the oldest file falls off the end. - const auto numbered = [&](std::size_t n) { - auto p = m_path; - p += std::format(".{}", n); - return p; - }; - std::filesystem::remove(numbered(m_options.max_files), ec); - for (std::size_t n = m_options.max_files; n > 1; --n) { - const auto from = numbered(n - 1); - if (std::filesystem::exists(from, ec)) { - std::filesystem::rename(from, numbered(n), ec); - } - } - if (m_options.max_files > 0) { - std::filesystem::rename(m_path, numbered(1), ec); - } else { - std::filesystem::remove(m_path, ec); - } - - m_file.open(m_path, std::ios::trunc); - m_current_bytes = 0; - Void::Log::debug("Log.RotatingFile", "rotated '{}'", m_path.string()); } } // namespace Void::Logging diff --git a/src/Log/SplitFileLogger.cpp b/src/Log/SplitFileLogger.cpp new file mode 100644 index 0000000..20f80be --- /dev/null +++ b/src/Log/SplitFileLogger.cpp @@ -0,0 +1,110 @@ +#include +#include + +#include +#include +#include +#include + +namespace Void::Logging +{ + + namespace + { + std::string level_filename(Level level) + { + std::string name{to_string(level)}; + for (auto& c : name) { + c = static_cast( + std::tolower(static_cast(c))); + } + return name + ".log"; + } + } // namespace + + SplitFileLogger::SplitFileLogger(std::filesystem::path dir, Options options) + : Logger(options.mode, options.capacity, options.policy), + m_dir(std::move(dir)), m_options(options) + { + std::error_code ec; + std::filesystem::create_directories(m_dir, ec); + if (ec) { + throw std::runtime_error(std::format( + "SplitFileLogger: cannot create '{}'", m_dir.string())); + } + if (m_options.combined) { + m_combined = std::make_unique( + m_dir / "all.log", + Detail::RollingFileOptions{m_options.max_bytes, + m_options.max_files}); + (void)m_combined->open(); + } + Void::Log::debug("Log.Split", "split logging into '{}'", + m_dir.string()); + } + + Void::Result::Result, Void::Result::Error> + SplitFileLogger::open(std::filesystem::path dir, Options options) + { + try { + return Void::Result::ok( + std::make_unique(std::move(dir), options)); + } catch (const std::exception& e) { + return Void::Result::fail(std::string{e.what()}); + } + } + + SplitFileLogger::~SplitFileLogger() noexcept { flush(); } + + Detail::RollingFile& SplitFileLogger::file_for(Level level) + { + auto it = m_per_level.find(level); + if (it == m_per_level.end()) { + Detail::RollingFile file{ + m_dir / level_filename(level), + Detail::RollingFileOptions{m_options.max_bytes, + m_options.max_files}}; + (void)file.open(); + it = m_per_level.emplace(level, std::move(file)).first; + } + return it->second; + } + + void SplitFileLogger::append(const Entry& entry) + { + std::string line; + if (m_formatter) { + line = m_formatter->format(entry); + } else { + line = + std::format("[{}] {}", to_string(entry.level), entry.message); + } + file_for(entry.level).write(line); + if (m_combined) { + m_combined->write(line); + } + } + + void SplitFileLogger::write(const Entry& entry) + { + append(entry); + file_for(entry.level).flush(); + if (m_combined) { + m_combined->flush(); + } + } + + void SplitFileLogger::on_flush(std::span entries) + { + for (const auto& e : entries) { + append(e); + } + for (auto& [level, file] : m_per_level) { + file.flush(); + } + if (m_combined) { + m_combined->flush(); + } + } + +} // namespace Void::Logging diff --git a/tests/standalone/Log/Fields.cpp b/tests/standalone/Log/Fields.cpp new file mode 100644 index 0000000..b12e043 --- /dev/null +++ b/tests/standalone/Log/Fields.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +#include +#include + +#include +#include + +using namespace Void::Logging; + +Void::Testing::Test field_scope_attaches_to_entries() +{ + std::vector captured; + CallbackLogger log{[&](const Entry& e) { captured.push_back(e); }, + Mode::Immediate}; + + { + FieldScope svc{"service", "billing"}; + log.info("inside scope"); + } + log.info("outside scope"); + + Void::Testing::expect_eq(captured.size(), std::size_t{2}); + Void::Testing::expect_eq(captured[0].fields.size(), std::size_t{1}); + Void::Testing::expect_eq(captured[0].fields[0].first, + std::string{"service"}); + Void::Testing::expect_eq(captured[0].fields[0].second, + std::string{"billing"}); + Void::Testing::expect(captured[1].fields.empty()); +} + +Void::Testing::Test field_scope_nests() +{ + std::vector captured; + CallbackLogger log{[&](const Entry& e) { captured.push_back(e); }, + Mode::Immediate}; + + FieldScope a{"a", "1"}; + { + FieldScope b{{{"b", "2"}, {"c", "3"}}}; + log.info("two scopes"); + } + log.info("one scope"); + + Void::Testing::expect_eq(captured[0].fields.size(), std::size_t{3}); + Void::Testing::expect_eq(captured[1].fields.size(), std::size_t{1}); +} + +Void::Testing::Test field_scope_feeds_pattern_token() +{ + std::string rendered; + PatternFormatter fmt{"[{request_id}] {message}"}; + CallbackLogger log{[&](const Entry& e) { rendered = fmt.format(e); }, + Mode::Immediate}; + + FieldScope req{"request_id", "r-42"}; + log.warning("processing"); + Void::Testing::expect_eq(rendered, std::string{"[r-42] processing"}); +} diff --git a/tests/standalone/Log/FileSinks.cpp b/tests/standalone/Log/FileSinks.cpp new file mode 100644 index 0000000..43f1fc7 --- /dev/null +++ b/tests/standalone/Log/FileSinks.cpp @@ -0,0 +1,142 @@ +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +using namespace Void::Logging; + +namespace +{ + std::string slurp(const std::filesystem::path& p) + { + std::ifstream f(p); + return {std::istreambuf_iterator(f), {}}; + } +} // namespace + +class SplitFileLoggerTests : public Void::Testing::Fixture +{ + public: + + std::filesystem::path dir; + + void setup() override + { + dir = std::filesystem::temp_directory_path() / "void_split_test"; + std::filesystem::remove_all(dir); + } + void teardown() override { std::filesystem::remove_all(dir); } + + Void::Testing::Test routes_by_level() + { + { + SplitFileLogger log{dir, + {.mode = Void::Logging::Mode::Immediate}}; + log.info("an info line"); + log.error("an error line"); + } + Void::Testing::expect( + slurp(dir / "info.log").find("an info line") != + std::string::npos); + Void::Testing::expect( + slurp(dir / "error.log").find("an error line") != + std::string::npos); + // error.log must NOT contain the info line. + Void::Testing::expect( + slurp(dir / "error.log").find("an info line") == + std::string::npos); + } + + Void::Testing::Test combined_has_all_levels() + { + { + SplitFileLogger log{dir, + {.mode = Void::Logging::Mode::Immediate}}; + log.info("info one"); + log.error("error one"); + } + const auto all = slurp(dir / "all.log"); + Void::Testing::expect(all.find("info one") != std::string::npos); + Void::Testing::expect(all.find("error one") != std::string::npos); + } + + Void::Testing::Test combined_can_be_disabled() + { + { + SplitFileLogger log{dir, + {.combined = false, + .mode = Void::Logging::Mode::Immediate}}; + log.info("solo"); + } + Void::Testing::expect(!std::filesystem::exists(dir / "all.log")); + Void::Testing::expect(std::filesystem::exists(dir / "info.log")); + } +}; + +class HistoryLoggerTests : public Void::Testing::Fixture +{ + public: + + std::filesystem::path dir; + std::filesystem::path path; + + void setup() override + { + dir = std::filesystem::temp_directory_path() / "void_hist_test"; + std::filesystem::remove_all(dir); + std::filesystem::create_directories(dir); + path = dir / "history.jsonl"; + } + void teardown() override { std::filesystem::remove_all(dir); } + + Void::Testing::Test writes_jsonlines() + { + { + HistoryLogger log{path, + {.mode = Void::Logging::Mode::Immediate}}; + log.info("audit me"); + } + std::ifstream f(path); + std::string line; + std::getline(f, line); + const auto parsed = Void::Json::parse(line); + Void::Testing::expect(parsed.has_value()); + Void::Testing::expect_eq((*parsed)["message"].as_string(), + std::string{"audit me"}); + } + + Void::Testing::Test captures_below_default_min_level() + { + { + HistoryLogger log{path, + {.mode = Void::Logging::Mode::Immediate}}; + log.trace("low level but kept"); + } + Void::Testing::expect(slurp(path).find("low level but kept") != + std::string::npos); + } + + Void::Testing::Test rotates_on_size() + { + { + HistoryLogger log{path, + {.max_bytes = 256, + .max_files = 3, + .mode = Void::Logging::Mode::Immediate}}; + for (int i = 0; i < 60; ++i) { + log.info("a fairly long history line number " + + std::to_string(i)); + } + } + auto rotated = path; + rotated += ".1"; + Void::Testing::expect(std::filesystem::exists(rotated)); + } +}; diff --git a/tests/standalone/Log/FromConfig.cpp b/tests/standalone/Log/FromConfig.cpp index 249e203..83db69e 100644 --- a/tests/standalone/Log/FromConfig.cpp +++ b/tests/standalone/Log/FromConfig.cpp @@ -46,6 +46,31 @@ Void::Testing::Test from_config_builds_multi_sink_tree() std::string::npos); } +Void::Testing::Test from_config_split_and_history_sinks() +{ + Void::FileSystem::TempDir tmp{"void_fromcfg"}; + Config cfg; + cfg.set("log.sinks", "split, history"); + cfg.set("log.split.dir", (tmp.path() / "split").string()); + cfg.set("log.history.path", (tmp.path() / "history.jsonl").string()); + cfg.set("log.async", "false"); + + const auto logger = Void::Logging::from_config(cfg); + Void::Testing::expect(logger.has_value()); + (*logger)->error("split me"); + (*logger)->flush(); + + std::ifstream err(tmp.path() / "split" / "error.log"); + std::string err_content((std::istreambuf_iterator(err)), {}); + Void::Testing::expect(err_content.find("split me") != + std::string::npos); + + std::ifstream hist(tmp.path() / "history.jsonl"); + std::string hist_content((std::istreambuf_iterator(hist)), {}); + Void::Testing::expect(hist_content.find("split me") != + std::string::npos); +} + Void::Testing::Test from_config_json_format_applies() { Void::FileSystem::TempDir tmp{"void_fromcfg"}; diff --git a/tests/standalone/Log/Pattern.cpp b/tests/standalone/Log/Pattern.cpp new file mode 100644 index 0000000..3e1a980 --- /dev/null +++ b/tests/standalone/Log/Pattern.cpp @@ -0,0 +1,137 @@ +#include +#include +#include +#include + +#include + +using Void::Logging::AnsiColor; +using Void::Logging::ColorPolicy; +using Void::Logging::Entry; +using Void::Logging::Level; +using Void::Logging::PatternFormatter; + +namespace +{ + Entry make_entry() + { + Entry e; + e.level = Level::Warning; + e.message = "disk full"; + e.fields = {{"service", "ingest"}, {"request_id", "abc123"}}; + return e; + } +} // namespace + +// ── width / alignment +// ───────────────────────────────────────────────────────── + +Void::Testing::Test pattern_left_pad_width() +{ + PatternFormatter fmt{"[{level:<10}]"}; + Void::Testing::expect_eq(fmt.format(make_entry()), + std::string{"[Warning ]"}); +} + +Void::Testing::Test pattern_right_pad_width() +{ + PatternFormatter fmt{"[{level:>10}]"}; + Void::Testing::expect_eq(fmt.format(make_entry()), + std::string{"[ Warning]"}); +} + +Void::Testing::Test pattern_center_pad_width() +{ + PatternFormatter fmt{"[{level:^9}]"}; + // "Warning" is 7 chars, width 9 → 1 left, 1 right + Void::Testing::expect_eq(fmt.format(make_entry()), + std::string{"[ Warning ]"}); +} + +Void::Testing::Test pattern_width_smaller_than_text_is_noop() +{ + PatternFormatter fmt{"{level:<3}"}; + Void::Testing::expect_eq(fmt.format(make_entry()), std::string{"Warning"}); +} + +// ── custom tokens & fields +// ──────────────────────────────────────────────────── + +Void::Testing::Test pattern_reads_structured_field() +{ + PatternFormatter fmt{"{service}/{request_id}: {message}"}; + Void::Testing::expect_eq(fmt.format(make_entry()), + std::string{"ingest/abc123: disk full"}); +} + +Void::Testing::Test pattern_unknown_token_stays_literal() +{ + PatternFormatter fmt{"{nope} {message}"}; + Void::Testing::expect_eq(fmt.format(make_entry()), + std::string{"{nope} disk full"}); +} + +Void::Testing::Test pattern_custom_token_registered() +{ + PatternFormatter fmt{"<{shout}> {message}"}; + fmt.register_token("shout", [](const Entry& e) { + std::string up = e.message; + for (auto& c : up) { + c = static_cast(std::toupper(static_cast(c))); + } + return up; + }); + Void::Testing::expect_eq(fmt.format(make_entry()), + std::string{" disk full"}); +} + +Void::Testing::Test pattern_field_with_alignment() +{ + PatternFormatter fmt{"{service:>8}"}; + Void::Testing::expect_eq(fmt.format(make_entry()), std::string{" ingest"}); +} + +// ── color +// ───────────────────────────────────────────────────────────────────── + +Void::Testing::Test pattern_no_color_by_default() +{ + PatternFormatter fmt{"{level:,auto} {message}"}; + // Policy disabled by default → no escape codes. + const auto out = fmt.format(make_entry()); + Void::Testing::expect(out.find('\x1b') == std::string::npos); + Void::Testing::expect_eq(out, std::string{"Warning disk full"}); +} + +Void::Testing::Test pattern_auto_color_uses_level_color() +{ + PatternFormatter fmt{"{level:,auto}"}; + fmt.set_color_policy(ColorPolicy::defaults()); + const auto out = fmt.format(make_entry()); + // Warning → bright yellow (93), wrapped + reset, text intact. + Void::Testing::expect(out.find("\x1b[93m") != std::string::npos); + Void::Testing::expect(out.find("Warning") != std::string::npos); + Void::Testing::expect(out.find("\x1b[0m") != std::string::npos); +} + +Void::Testing::Test pattern_fixed_color() +{ + PatternFormatter fmt{"{message:,cyan}"}; + ColorPolicy p; + p.enabled = true; + fmt.set_color_policy(p); + const auto out = fmt.format(make_entry()); + Void::Testing::expect(out.find("\x1b[36m") != std::string::npos); + Void::Testing::expect(out.find("disk full") != std::string::npos); +} + +Void::Testing::Test color_name_parsing() +{ + Void::Testing::expect(Void::Logging::parse_color("red") == AnsiColor::Red); + Void::Testing::expect(Void::Logging::parse_color("bright_magenta") == + AnsiColor::BrightMagenta); + Void::Testing::expect(Void::Logging::parse_color("dim") == + AnsiColor::BrightBlack); + Void::Testing::expect(Void::Logging::parse_color("notacolor") == + AnsiColor::Default); +}