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

+10 -65
View File
@@ -1,86 +1,35 @@
#include <Void/Detail/Enum.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#ifdef VOID_HAS_STACKTRACE
#include <Void/Stacktrace/Color.hpp>
#endif
#include <format>
#include <iostream>
#include <ostream>
#include <string>
#include <string_view>
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();
}
+50
View File
@@ -0,0 +1,50 @@
#include <Void/Log/Field.hpp>
#include <utility>
namespace Void::Logging
{
namespace
{
thread_local std::vector<std::pair<std::string, std::string>> 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<std::pair<std::string, std::string>> 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<const std::pair<std::string, std::string>>
current_fields() noexcept
{
return t_fields;
}
} // namespace Void::Logging
+282 -73
View File
@@ -1,6 +1,8 @@
#include <Void/Log/Formatter.hpp>
#include <Void/Data/Json.hpp>
#include <array>
#include <charconv>
#include <chrono>
#include <filesystem>
#include <format>
@@ -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<Pair, 16> 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<std::string(const Entry&)> 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<std::ptrdiff_t>(pad), ' ');
break;
case Align::Center:
{
const std::size_t l = pad / 2;
text.insert(text.begin(),
static_cast<std::ptrdiff_t>(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;
+55 -1
View File
@@ -2,9 +2,11 @@
#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>
@@ -104,9 +106,13 @@ namespace Void::Logging
{
const auto format = cfg.get_or("format", "default");
if (format == "pattern") {
return std::make_shared<PatternFormatter>(
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") {
return std::make_shared<JsonLinesFormatter>();
@@ -200,6 +206,54 @@ namespace Void::Logging
(*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");
+55
View File
@@ -0,0 +1,55 @@
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <format>
#include <stdexcept>
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<JsonLinesFormatter>())
{
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<std::unique_ptr<HistoryLogger>, Void::Result::Error>
HistoryLogger::open(std::filesystem::path path, Options options)
{
try {
return Void::Result::ok(
std::make_unique<HistoryLogger>(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<const Entry> entries)
{
for (const auto& e : entries) {
m_file.write(m_formatter->format(e));
}
m_file.flush();
}
} // namespace Void::Logging
+5
View File
@@ -1,3 +1,4 @@
#include <Void/Log/Field.hpp>
#include <Void/Log/Logger.hpp>
#include <utility> // 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));
+76
View File
@@ -0,0 +1,76 @@
#include <Void/Log/Detail/RollingFile.hpp>
#include <format>
#include <system_error>
#include <utility>
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::size_t>(
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<std::streamsize>(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
+7 -54
View File
@@ -3,7 +3,6 @@
#include <format>
#include <stdexcept>
#include <system_error>
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::size_t>(
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<std::unique_ptr<RotatingFileLogger>,
@@ -46,7 +39,6 @@ namespace Void::Logging
{
append(entry);
m_file.flush();
rotate_if_needed();
}
void RotatingFileLogger::on_flush(std::span<const Entry> 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
+110
View File
@@ -0,0 +1,110 @@
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/Log.hpp>
#include <cctype>
#include <format>
#include <stdexcept>
#include <system_error>
namespace Void::Logging
{
namespace
{
std::string level_filename(Level level)
{
std::string name{to_string(level)};
for (auto& c : name) {
c = static_cast<char>(
std::tolower(static_cast<unsigned char>(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<Detail::RollingFile>(
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<std::unique_ptr<SplitFileLogger>, Void::Result::Error>
SplitFileLogger::open(std::filesystem::path dir, Options options)
{
try {
return Void::Result::ok(
std::make_unique<SplitFileLogger>(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<const Entry> 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