Logging: colors, configurable/custom pattern tokens, split + history sinks

Pattern formatting (PatternFormatter):
- Token spec grammar {token:[align][width][,color]} — align <,>,^,
  std::format-style width, color a name or "auto" (= the level's color).
- Custom tokens via register_token(name, fn); unknown {name} resolves
  against registered renderers, then Entry::fields by key, else stays
  literal — so structured fields print as {request_id:>8}.
- Color model: AnsiColor + ColorPolicy{enabled, level_colors,
  token_colors} (ColorPolicy::defaults()); only PatternFormatter
  colorizes (never file/JSON/logfmt). ConsoleLogger now renders its
  default line through a colored PatternFormatter and exposes
  set_color_policy (honors Stacktrace::Color::g_color_enabled).

Structured fields:
- Entry gains a fields vector; Logging::FieldScope (RAII, thread-local)
  attaches key/values to every entry on the thread, snapshotted like
  scopes. JsonLines/logfmt include them.

New file sinks (async by default):
- Detail::RollingFile factors size+max-files rotation; RotatingFileLogger
  now delegates to it.
- SplitFileLogger: per-level files (<dir>/<level>.log) plus an optional
  combined <dir>/all.log.
- HistoryLogger: always-on, never-level-filtered durable JSON-lines
  audit trail over a rolling file.
- from_config gains split/history sinks and a log.color toggle.

22 new tests (pattern width/align/custom-token/field, color on/off + name
parsing, FieldScope nesting, split routing + combined, history JSON +
rotation, from_config split/history). 987 green; module build clean
under -Werror.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Fable 5 committed 2026-06-14 00:24:31 +03:00
1 parent ff6960a2af
commit 6b5f61f00a
22 files changed
+1384 -233

No files matched your search

+13 -1
View File
@@ -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<const Formatter> 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<const Formatter> 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
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <string_view>
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
+8
View File
@@ -6,6 +6,7 @@
#include <source_location>
#include <string>
#include <thread>
#include <utility>
#include <vector>
namespace Void::Logging
@@ -48,6 +49,13 @@ namespace Void::Logging
/// the last element; for ScopeExit it reflects the stack *before*
/// the pop.
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.
std::vector<std::pair<std::string, std::string>> fields{};
};
} // namespace Void::Logging
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include <initializer_list>
#include <span>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
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=<id>
class FieldScope
{
public:
FieldScope(std::string key, std::string value);
explicit FieldScope(
std::initializer_list<std::pair<std::string, std::string>>
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<const std::pair<std::string, std::string>>
current_fields() noexcept;
} // namespace Void::Logging
+94 -33
View File
@@ -3,9 +3,10 @@
#include <Void/Log/Entry.hpp>
#include <Void/Log/Level.hpp>
#include <memory>
#include <functional>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
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, 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:
@@ -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<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 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<Segment> m_segments;
std::unordered_map<std::string,
std::function<std::string(const Entry&)>>
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:
+65
View File
@@ -0,0 +1,65 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Detail/RollingFile.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Logger.hpp>
#include <cstddef>
#include <filesystem>
#include <memory>
#include <span>
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<std::unique_ptr<HistoryLogger>, Void::Result::Error>
open(std::filesystem::path path, Options options = {});
/// Replace the default JsonLines rendering.
void set_formatter(std::shared_ptr<const Formatter> formatter)
{
m_formatter = std::move(formatter);
}
protected:
void write(const Entry& entry) override;
void on_flush(std::span<const Entry> entries) override;
private:
Detail::RollingFile m_file;
std::shared_ptr<const Formatter> m_formatter;
};
} // namespace Void::Logging
+2 -5
View File
@@ -2,12 +2,12 @@
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Detail/RollingFile.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Logger.hpp>
#include <cstddef>
#include <filesystem>
#include <fstream>
#include <memory>
#include <span>
@@ -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<const Formatter> m_formatter;
};
+84
View File
@@ -0,0 +1,84 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Detail/RollingFile.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Logger.hpp>
#include <cstddef>
#include <filesystem>
#include <map>
#include <memory>
#include <span>
namespace Void::Logging
{
/// Options for SplitFileLogger (namespace scope to avoid the GCC
/// nested-default-arg trap).
struct SplitFileOptions {
/// One combined file `<dir>/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
/// (`<dir>/<level>.log`, e.g. `error.log`, lazily created) and, when
/// enabled, also to a single combined `<dir>/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<std::unique_ptr<SplitFileLogger>, Void::Result::Error>
open(std::filesystem::path dir, Options options = {});
void set_formatter(std::shared_ptr<const Formatter> 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<const Entry> entries) override;
private:
Detail::RollingFile& file_for(Level level);
void append(const Entry& entry);
std::filesystem::path m_dir;
Options m_options;
std::map<Level, Detail::RollingFile> m_per_level;
std::unique_ptr<Detail::RollingFile> m_combined;
std::shared_ptr<const Formatter> m_formatter;
};
} // namespace Void::Logging