feat(Log): harden LogState facade, bounded Logger delivery/tickets/quarantine, file sync/reopen, redaction, and separate LogConfig (M-LOG-01..05)

This commit is contained in:
faumaray committed 2026-11-24 10:16:35 +03:00
1 parent 18a623aa62
commit a74a402938
23 files changed
+2656 -1197

No files matched your search

+119 -8
View File
@@ -1,7 +1,15 @@
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Log.hpp>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <format>
#include <mutex>
#include <stdexcept>
namespace Void::Logging
@@ -20,6 +28,18 @@ namespace Void::Logging
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
}
FileLogger::FileLogger(const std::filesystem::path& path,
LoggerOptions options)
: Logger(std::move(options)), m_path(path), m_file(path, std::ios::app)
{
if (!m_file.is_open()) {
Void::Log::warn("Logging", "FileLogger: cannot open '{}'", path.string());
throw std::runtime_error(
std::format("FileLogger: cannot open '{}'", path.string()));
}
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
}
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
FileLogger::open(const std::filesystem::path& path,
Mode mode,
@@ -29,7 +49,21 @@ namespace Void::Logging
return Void::Result::ok(
std::make_unique<FileLogger>(path, mode, capacity));
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
FileLogger::open(const std::filesystem::path& path,
LoggerOptions options)
{
try {
return Void::Result::ok(
std::make_unique<FileLogger>(path, std::move(options)));
} catch (const std::exception& e) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
@@ -37,13 +71,70 @@ namespace Void::Logging
{
flush();
Void::Log::debug("Logging", "FileLogger: closed '{}'",
m_path.string());
m_path.string());
}
Void::Result::Result<void> FileLogger::reopen()
{
flush();
m_file.close();
m_file.clear();
m_file.open(m_path, std::ios::app);
if (!m_file.is_open()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::reopen failed for '{}'",
m_path.string())));
}
return {};
}
Void::Result::Result<void> FileLogger::sync_files()
{
flush();
if (is_quarantined()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, last_error_summary()));
}
m_file.flush();
if (!m_file.good()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files flush failure for '{}'",
m_path.string())));
}
#ifndef _WIN32
const int fd = ::open(m_path.c_str(), O_RDONLY);
if (fd < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files open('{}') failed: {}",
m_path.string(), std::strerror(errno))));
}
int rc = 0;
do {
rc = ::fsync(fd);
} while (rc < 0 && errno == EINTR);
const int saved_err = errno;
::close(fd);
if (rc < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files fsync('{}') failed: {}",
m_path.string(), std::strerror(saved_err))));
}
#endif
return {};
}
void FileLogger::write(const Entry& entry)
{
append(entry);
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: flush failure on '{}'", m_path.string()));
}
}
void FileLogger::on_flush(std::span<const Entry> entries)
@@ -52,17 +143,37 @@ namespace Void::Logging
append(e);
}
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: batch flush failure on '{}'", m_path.string()));
}
}
void FileLogger::append(const Entry& entry)
{
if (m_formatter) {
m_file << m_formatter->format(entry) << '\n';
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"FileLogger: file not open for '{}'", m_path.string()));
}
else {
m_file << std::format(
"[{}] {}\n", to_string(entry.level), entry.message);
std::string line;
if (m_formatter) {
auto bounded = format_bounded(
*m_formatter,
entry,
delivery_limits().max_format_scratch_bytes,
delivery_limits().truncate_oversize);
if (!bounded) {
throw std::runtime_error(bounded.error().message());
}
line = std::move(*bounded);
} else {
line = std::format("[{}] {}", to_string(entry.level), entry.message);
}
m_file << line << '\n';
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: write failure on '{}'", m_path.string()));
}
}
} // namespace Void::Logging
} // namespace Void::Logging
+114 -73
View File
@@ -1,9 +1,11 @@
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Logger.hpp>
#include <Void/Data/Json.hpp>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <format>
#include <sstream>
@@ -12,8 +14,6 @@
namespace Void::Logging
{
// ── colour ────────────────────────────────────────────────────────────
AnsiColor parse_color(std::string_view name) noexcept
{
struct Pair {
@@ -43,7 +43,6 @@ namespace Void::Logging
return c;
}
}
// "dim"/"gray" aliases
if (name == "dim" || name == "gray" || name == "grey") {
return AnsiColor::BrightBlack;
}
@@ -53,40 +52,23 @@ namespace Void::Logging
std::string_view ansi_code(AnsiColor color) noexcept
{
switch (color) {
case AnsiColor::Default:
return "";
case AnsiColor::Black:
return "\x1b[30m";
case AnsiColor::Red:
return "\x1b[31m";
case AnsiColor::Green:
return "\x1b[32m";
case AnsiColor::Yellow:
return "\x1b[33m";
case AnsiColor::Blue:
return "\x1b[34m";
case AnsiColor::Magenta:
return "\x1b[35m";
case AnsiColor::Cyan:
return "\x1b[36m";
case AnsiColor::White:
return "\x1b[37m";
case AnsiColor::BrightBlack:
return "\x1b[90m";
case AnsiColor::BrightRed:
return "\x1b[91m";
case AnsiColor::BrightGreen:
return "\x1b[92m";
case AnsiColor::BrightYellow:
return "\x1b[93m";
case AnsiColor::BrightBlue:
return "\x1b[94m";
case AnsiColor::BrightMagenta:
return "\x1b[95m";
case AnsiColor::BrightCyan:
return "\x1b[96m";
case AnsiColor::BrightWhite:
return "\x1b[97m";
case AnsiColor::Default: return "";
case AnsiColor::Black: return "\x1b[30m";
case AnsiColor::Red: return "\x1b[31m";
case AnsiColor::Green: return "\x1b[32m";
case AnsiColor::Yellow: return "\x1b[33m";
case AnsiColor::Blue: return "\x1b[34m";
case AnsiColor::Magenta: return "\x1b[35m";
case AnsiColor::Cyan: return "\x1b[36m";
case AnsiColor::White: return "\x1b[37m";
case AnsiColor::BrightBlack: return "\x1b[90m";
case AnsiColor::BrightRed: return "\x1b[91m";
case AnsiColor::BrightGreen: return "\x1b[92m";
case AnsiColor::BrightYellow: return "\x1b[93m";
case AnsiColor::BrightBlue: return "\x1b[94m";
case AnsiColor::BrightMagenta: return "\x1b[95m";
case AnsiColor::BrightCyan: return "\x1b[96m";
case AnsiColor::BrightWhite: return "\x1b[97m";
}
return "";
}
@@ -103,13 +85,10 @@ namespace Void::Logging
{Level::Error, AnsiColor::BrightRed},
{Level::Fatal, AnsiColor::BrightMagenta},
};
// The level token defaults to the level's own colour.
p.token_colors = {};
return p;
}
// ── FormatDetail ──────────────────────────────────────────────────────
namespace FormatDetail
{
@@ -143,12 +122,9 @@ namespace Void::Logging
std::string_view kind_str(Kind kind)
{
switch (kind) {
case Kind::Message:
return "Message";
case Kind::ScopeEnter:
return "ScopeEnter";
case Kind::ScopeExit:
return "ScopeExit";
case Kind::Message: return "Message";
case Kind::ScopeEnter: return "ScopeEnter";
case Kind::ScopeExit: return "ScopeExit";
}
return "?";
}
@@ -168,7 +144,7 @@ namespace Void::Logging
const std::string* found = nullptr;
for (const auto& [k, v] : entry.fields) {
if (k == key) {
found = &v; // later duplicates win
found = &v;
}
}
return found;
@@ -177,8 +153,6 @@ namespace Void::Logging
} // namespace FormatDetail
// ── PatternFormatter ──────────────────────────────────────────────────
PatternFormatter::PatternFormatter(std::string pattern)
{
std::string literal;
@@ -206,10 +180,9 @@ namespace Void::Logging
literal += rest;
break;
}
const auto body = rest.substr(1, close - 1); // inside braces
const auto body = rest.substr(1, close - 1);
rest.remove_prefix(close + 1);
// Split "token:spec".
std::string_view token = body;
std::string_view spec;
if (const auto colon = body.find(':');
@@ -222,7 +195,6 @@ namespace Void::Logging
seg.literal = false;
seg.text = std::string{token};
// spec = [align][width][,colour]
std::string_view color_name;
if (const auto comma = spec.find(',');
comma != std::string_view::npos) {
@@ -292,15 +264,18 @@ namespace Void::Logging
if (name == "kind") {
return std::string{kind_str(entry.kind)};
}
// Custom token?
if (const auto it = m_custom.find(name); it != m_custom.end()) {
return it->second(entry);
}
// Structured field?
if (const auto* v = find_field(entry, name)) {
if (!m_fields.allows(name)) {
return {};
}
if (m_fields.is_redacted(name)) {
return m_fields.redaction_mask;
}
return *v;
}
// Unknown — keep literal so misspellings are visible.
return "{" + name + "}";
}
@@ -315,7 +290,6 @@ namespace Void::Logging
std::string text = render_token(seg, entry);
// Width / alignment.
if (seg.width > text.size()) {
const std::size_t pad = seg.width - text.size();
switch (seg.align) {
@@ -337,7 +311,6 @@ namespace Void::Logging
}
}
// Colour.
if (m_colors.enabled && seg.color_mode != ColorMode::None) {
AnsiColor color = AnsiColor::Default;
if (seg.color_mode == ColorMode::Auto) {
@@ -355,7 +328,6 @@ namespace Void::Logging
continue;
}
}
// Per-token colour from the policy (no inline ,colour spec).
if (m_colors.enabled && seg.color_mode == ColorMode::None) {
if (const auto it = m_colors.token_colors.find(seg.text);
it != m_colors.token_colors.end() &&
@@ -371,8 +343,6 @@ namespace Void::Logging
return out;
}
// ── JsonLinesFormatter ────────────────────────────────────────────────
std::string JsonLinesFormatter::format(const Entry& entry) const
{
auto obj = Json::object();
@@ -383,6 +353,9 @@ namespace Void::Logging
o.emplace_back("kind", Json::Value{FormatDetail::kind_str(entry.kind)});
o.emplace_back("thread",
Json::Value{FormatDetail::thread_str(entry.thread_id)});
if (entry.truncated) {
o.emplace_back("truncated", Json::Value{true});
}
if (!entry.scopes.empty()) {
auto arr = Json::array();
arr.as_array().reserve(entry.scopes.size());
@@ -397,7 +370,11 @@ namespace Void::Logging
if (!m_fields.allows(k)) {
continue;
}
fobj.as_object().emplace_back(k, Json::Value{v});
fobj.as_object().emplace_back(
k,
Json::Value{m_fields.is_redacted(k)
? m_fields.redaction_mask
: v});
}
if (!fobj.as_object().empty()) {
o.emplace_back("fields", std::move(fobj));
@@ -408,26 +385,56 @@ namespace Void::Logging
o.emplace_back("file", Json::Value{file});
o.emplace_back(
"line",
Json::Value{static_cast<double>(entry.location.line())});
Json::Value{static_cast<std::int64_t>(entry.location.line())});
}
return Json::serialize(obj);
}
// ── LogfmtFormatter ───────────────────────────────────────────────────
namespace
{
void append_quoted(std::string& out, std::string_view value)
{
out += '"';
for (const char c : value) {
if (c == '"' || c == '\\') {
out += '\\';
for (const unsigned char uc : value) {
switch (uc) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (uc < 0x20 || uc == 0x7F) {
out += std::format("\\u{:04x}", uc);
} else {
out += static_cast<char>(uc);
}
break;
}
out += c;
}
out += '"';
}
[[nodiscard]] bool is_safe_bare_token(std::string_view sv) noexcept
{
if (sv.empty()) {
return false;
}
for (const unsigned char uc : sv) {
if (uc <= 0x20 || uc == 0x7F || uc == '=' || uc == '"') {
return false;
}
}
return true;
}
void append_key_or_token(std::string& out, std::string_view token)
{
if (is_safe_bare_token(token)) {
out += token;
} else {
append_quoted(out, token);
}
}
} // namespace
std::string LogfmtFormatter::format(const Entry& entry) const
@@ -439,23 +446,27 @@ namespace Void::Logging
out += to_string(entry.level);
out += " thread=";
out += FormatDetail::thread_str(entry.thread_id);
if (entry.truncated) {
out += " truncated=true";
}
if (auto crumb = FormatDetail::scope_breadcrumb(entry.scopes);
!crumb.empty()) {
out += " scopes=";
out += crumb;
append_key_or_token(out, crumb);
}
for (const auto& [k, v] : entry.fields) {
if (!m_fields.allows(k)) {
continue;
}
out += ' ';
out += k;
append_key_or_token(out, k);
out += '=';
append_quoted(out, v);
append_quoted(
out, m_fields.is_redacted(k) ? m_fields.redaction_mask : v);
}
if (auto file = FormatDetail::file_basename(entry); !file.empty()) {
out += " file=";
out += file;
append_key_or_token(out, file);
out += ':';
out += std::to_string(entry.location.line());
}
@@ -464,4 +475,34 @@ namespace Void::Logging
return out;
}
} // namespace Void::Logging
Void::Result::Result<std::string>
format_bounded(const Formatter& formatter,
const Entry& entry,
std::size_t max_bytes,
bool truncate)
{
if (max_bytes == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"format_bounded requires max_bytes > 0"));
}
std::string rendered = formatter.format(entry);
if (rendered.size() <= max_bytes) {
return rendered;
}
if (!truncate) {
return Void::Result::fail(make_log_error(
LogErrorCode::entry_too_large,
"Formatted log entry exceeds max_format_scratch_bytes"));
}
constexpr std::string_view kMarker = "...[truncated]";
if (max_bytes <= kMarker.size()) {
rendered.resize(max_bytes);
return rendered;
}
rendered.resize(max_bytes - kMarker.size());
rendered += kMarker;
return rendered;
}
} // namespace Void::Logging
-325
View File
@@ -1,325 +0,0 @@
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/SyslogLogger.hpp>
#include <format>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace Void::Logging
{
namespace
{
std::vector<std::string> split_list(std::string_view csv)
{
std::vector<std::string> out;
std::size_t start = 0;
while (start <= csv.size()) {
auto comma = csv.find(',', start);
if (comma == std::string_view::npos) {
comma = csv.size();
}
auto item = csv.substr(start, comma - start);
while (!item.empty() && item.front() == ' ') {
item.remove_prefix(1);
}
while (!item.empty() && item.back() == ' ') {
item.remove_suffix(1);
}
if (!item.empty()) {
out.emplace_back(item);
}
start = comma + 1;
}
return out;
}
std::optional<Level> parse_level(std::string_view name)
{
std::string lower;
for (const char c : name) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "trace") {
return Level::Trace;
}
if (lower == "debug") {
return Level::Debug;
}
if (lower == "info") {
return Level::Info;
}
if (lower == "warning" || lower == "warn") {
return Level::Warning;
}
if (lower == "error") {
return Level::Error;
}
if (lower == "fatal") {
return Level::Fatal;
}
if (lower == "disabled" || lower == "off") {
return Level::Disabled;
}
return std::nullopt;
}
std::optional<Void::Log::Level>
parse_facade_level(std::string_view name)
{
const auto l = parse_level(name);
if (!l.has_value()) {
return std::nullopt;
}
switch (*l) {
case Level::Trace:
return Void::Log::Level::Trace;
case Level::Debug:
return Void::Log::Level::Debug;
case Level::Info:
return Void::Log::Level::Info;
case Level::Warning:
return Void::Log::Level::Warning;
case Level::Error:
return Void::Log::Level::Error;
case Level::Fatal:
return Void::Log::Level::Fatal;
case Level::Disabled:
return Void::Log::Level::Disabled;
}
return std::nullopt;
}
// Field allow/deny lists for the structured (json/logfmt) sinks, from
// the per-sink keys `fields.include` / `fields.exclude` (comma lists).
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
return f;
}
std::shared_ptr<const Formatter>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "pattern") {
auto fmt =
std::make_shared<PatternFormatter>(std::string{cfg.get_or(
"pattern", "{time} [{level}] {scopes}{message}")});
if (cfg.get_or_as<bool>("color", false)) {
fmt->set_color_policy(ColorPolicy::defaults());
}
return fmt;
}
if (format == "json") {
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
if (format == "logfmt") {
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
return nullptr; // "default": per-sink built-in rendering
}
struct Dispatch {
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::Block;
};
Dispatch make_dispatch(const Configuration::Config& cfg)
{
Dispatch d;
if (!cfg.get_or_as<bool>("async", true)) {
d.mode = Mode::Immediate;
}
d.capacity = cfg.get_or_as<std::size_t>("capacity", 512);
const auto overflow = cfg.get_or("overflow", "block");
if (overflow == "drop_newest") {
d.policy = OverflowPolicy::DropNewest;
} else if (overflow == "drop_oldest") {
d.policy = OverflowPolicy::DropOldest;
}
return d;
}
} // namespace
Void::Result::Result<std::shared_ptr<Logger>, Void::Result::Error>
from_config(const Configuration::Config& cfg, std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
const auto dispatch = make_dispatch(sub);
const auto formatter = make_formatter(sub);
std::vector<std::shared_ptr<Logger>> sinks;
for (const auto& name : split_list(sub.get_or("sinks", "console"))) {
if (name == "console") {
const bool to_stdout =
sub.get_or("console.stream", "stderr") == "stdout";
auto sink = std::make_shared<ConsoleLogger>(
to_stdout ? std::cout : std::cerr, dispatch.mode,
dispatch.capacity);
if (formatter) {
sink->set_formatter(formatter);
}
sinks.push_back(std::move(sink));
} else if (name == "file") {
const auto path = sub.get_or("file.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'file' needs "
"file.path");
}
auto sink = FileLogger::open(std::filesystem::path{path},
dispatch.mode,
dispatch.capacity);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "rotating") {
const auto path = sub.get_or("rotating.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'rotating' needs "
"rotating.path");
}
RotatingFileLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("rotating.max_kb", 1024) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("rotating.max_files", 5);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
RotatingFileLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "split") {
const auto dir = sub.get_or("split.dir");
if (dir.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'split' needs "
"split.dir");
}
SplitFileLogger::Options opt;
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes =
sub.get_or_as<std::size_t>("split.max_kb", 1024) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("split.max_files", 5);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "history") {
const auto path = sub.get_or("history.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'history' needs "
"history.path");
}
HistoryLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("history.max_kb", 8192) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("history.max_files", 10);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "syslog") {
#ifdef VOID_HAS_SYSLOG
const auto identity = sub.get_or("syslog.identity");
if (identity.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'syslog' needs "
"syslog.identity");
}
sinks.push_back(std::make_shared<SyslogLogger>(
std::string{identity}, dispatch.mode, dispatch.capacity));
#else
return Void::Result::fail(
"Logging::from_config: syslog is not available on "
"this platform");
#endif
} else {
return Void::Result::fail(std::format(
"Logging::from_config: unknown sink '{}'", name));
}
}
std::shared_ptr<Logger> root;
if (sinks.empty()) {
root = std::make_shared<NullLogger>();
} else if (sinks.size() == 1) {
root = std::move(sinks.front());
} else {
root = std::make_shared<MultiLogger>(std::move(sinks));
}
if (const auto level = parse_level(sub.get_or("level", "trace"));
level.has_value()) {
root->set_level(*level);
}
Void::Log::debug("Logging", "from_config: built logger tree");
return Void::Result::ok(std::move(root));
}
void apply_facade_config(const Configuration::Config& cfg,
std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
if (const auto level = parse_facade_level(sub.get_or("level", ""));
level.has_value()) {
Void::Log::set_min_level(*level);
}
for (const auto& key : sub.subtree("module_levels").keys()) {
const auto value = sub.get_or(std::string{"module_levels."} + key);
if (const auto level = parse_facade_level(value);
level.has_value()) {
Void::Log::set_module_level(key, *level);
}
}
}
} // namespace Void::Logging
+712 -241
View File
File diff suppressed because it is too large. Load diff
+86 -10
View File
@@ -1,9 +1,18 @@
#include <Void/Log/Detail/RollingFile.hpp>
#include <Void/Log/Logger.hpp>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <chrono>
#include <ctime>
#include <format>
#include <stdexcept>
#include <system_error>
#include <utility>
#include <vector>
@@ -46,25 +55,46 @@ namespace Void::Logging::Detail
bool RollingFile::open()
{
std::error_code ec;
if (m_path.has_parent_path()) {
if (m_opt.create_directories && m_path.has_parent_path()) {
std::filesystem::create_directories(m_path.parent_path(), ec);
if (ec) {
return false;
}
}
if (std::filesystem::exists(m_path, ec)) {
m_current_bytes = static_cast<std::size_t>(
std::filesystem::file_size(m_path, ec));
} else {
m_current_bytes = 0;
}
m_file.clear();
m_file.open(m_path, std::ios::app);
m_creationTime = std::chrono::system_clock::now();
return m_file.is_open();
}
bool RollingFile::reopen()
{
if (m_file.is_open()) {
m_file.flush();
m_file.close();
}
m_file.clear();
return open();
}
void RollingFile::write(std::string_view line)
{
if (!m_file.is_open()) {
return;
throw std::runtime_error(std::format(
"RollingFile: stream closed for '{}'", m_path.string()));
}
m_file.write(line.data(), static_cast<std::streamsize>(line.size()));
m_file.put('\n');
if (!m_file.good()) {
throw std::runtime_error(std::format(
"RollingFile: write failure on '{}'", m_path.string()));
}
m_current_bytes += line.size() + 1;
if (m_self_rotate && m_current_bytes >= m_opt.max_bytes) {
rotate();
@@ -73,9 +103,46 @@ namespace Void::Logging::Detail
void RollingFile::flush()
{
if (m_file.is_open()) {
m_file.flush();
if (!m_file.is_open()) {
return;
}
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"RollingFile: flush failure on '{}'", m_path.string()));
}
}
Void::Result::Result<void> RollingFile::sync()
{
try {
flush();
} catch (const std::exception& e) {
return Void::Result::fail(
make_log_error(LogErrorCode::io_error, e.what()));
}
#ifndef _WIN32
const int fd = ::open(m_path.c_str(), O_RDONLY);
if (fd < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RollingFile::sync open('{}') failed: {}",
m_path.string(), std::strerror(errno))));
}
int rc = 0;
do {
rc = ::fsync(fd);
} while (rc < 0 && errno == EINTR);
const int saved_err = errno;
::close(fd);
if (rc < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RollingFile::sync fsync('{}') failed: {}",
m_path.string(), std::strerror(saved_err))));
}
#endif
return {};
}
void RollingFile::rotate()
@@ -85,12 +152,15 @@ namespace Void::Logging::Detail
std::error_code ec;
if (m_opt.max_files > 0) {
// Create the history/ subdirectory next to the original file
auto parent = m_path.parent_path();
auto history_dir = parent / "history";
std::filesystem::create_directories(history_dir, ec);
if (ec) {
throw std::runtime_error(std::format(
"RollingFile: cannot create history dir '{}'",
history_dir.string()));
}
// Build new name: <stem>-<timestamp>.<ext>
auto stem = m_path.stem();
auto ext = m_path.extension();
auto new_filename = stem.string() + "-" +
@@ -98,19 +168,24 @@ namespace Void::Logging::Detail
auto archived = history_dir / new_filename;
std::filesystem::rename(m_path, archived, ec);
prune_archives(); // now looks inside history/
prune_archives();
} else {
std::filesystem::remove(m_path, ec);
}
m_file.clear();
m_file.open(m_path, std::ios::trunc);
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"RollingFile: reopen after rotate failed on '{}'",
m_path.string()));
}
m_current_bytes = 0;
m_creationTime = m_rotationTime;
}
void RollingFile::prune_archives()
{
// Prune only from the history/ subdirectory
auto parent = m_path.parent_path();
auto history_dir = parent / "history";
if (!std::filesystem::exists(history_dir)) {
@@ -132,7 +207,7 @@ namespace Void::Logging::Detail
}
}
} catch (const std::filesystem::filesystem_error&) {
return; // best-effort pruning only
return;
}
std::sort(archives.begin(), archives.end());
@@ -150,9 +225,10 @@ namespace Void::Logging::Detail
std::filesystem::create_directories(dir, ec);
std::filesystem::rename(m_path, dir / m_path.filename(), ec);
m_file.clear();
m_file.open(m_path, std::ios::trunc);
m_current_bytes = 0;
m_creationTime = m_rotationTime;
}
} // namespace Void::Logging::Detail
} // namespace Void::Logging::Detail
+51 -6
View File
@@ -9,9 +9,23 @@ namespace Void::Logging
RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path,
Options options)
: Logger(options.mode, options.capacity, options.policy), m_path(path),
m_file(path, Detail::RollingFileOptions{options.max_bytes,
options.max_files})
: Logger(LoggerOptions{
.mode = options.mode,
.policy = options.policy,
.limits = DeliveryLimits{
.entries = options.capacity > 0 ? options.capacity : 1,
.owned_bytes = std::max<std::size_t>(
8ULL * 1024ULL * 1024ULL,
(options.capacity > 0 ? options.capacity : 1) * 1024ULL),
.max_fields = 64,
.max_scopes = 64},
.failure_policy = FailurePolicy::Quarantine,
.suppress_reentrancy = false}),
m_path(path),
m_file(path,
Detail::RollingFileOptions{options.max_bytes,
options.max_files,
options.create_directories})
{
if (!m_file.open()) {
throw std::runtime_error(std::format(
@@ -29,12 +43,35 @@ namespace Void::Logging
return Void::Result::ok(
std::make_unique<RotatingFileLogger>(path, options));
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); }
Void::Result::Result<void> RotatingFileLogger::reopen()
{
flush();
if (!m_file.reopen()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RotatingFileLogger::reopen failed for '{}'",
m_path.string())));
}
return {};
}
Void::Result::Result<void> RotatingFileLogger::sync_files()
{
flush();
if (is_quarantined()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, last_error_summary()));
}
return m_file.sync();
}
void RotatingFileLogger::write(const Entry& entry)
{
append(entry);
@@ -52,11 +89,19 @@ namespace Void::Logging
void RotatingFileLogger::append(const Entry& entry)
{
if (m_formatter) {
m_file.write(m_formatter->format(entry));
auto bounded = format_bounded(
*m_formatter,
entry,
delivery_limits().max_format_scratch_bytes,
delivery_limits().truncate_oversize);
if (!bounded) {
throw std::runtime_error(bounded.error().message());
}
m_file.write(*bounded);
} else {
m_file.write(
std::format("[{}] {}", to_string(entry.level), entry.message));
}
}
} // namespace Void::Logging
} // namespace Void::Logging
+2 -2
View File
@@ -1,5 +1,5 @@
void_add_module(Log
INTERNAL_DEPS Async Core Data Functional Configuration LogState
INTERNAL_DEPS Async Core Data Functional Memory Time LogState
OPTIONAL_DEPS Stacktrace
EXCLUDE_HEADERS Void/Log/Log.hpp
EXCLUDE_HEADERS Void/Log/Log.hpp Void/Log/FromConfig.hpp
)
+449
View File
@@ -0,0 +1,449 @@
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/SyslogLogger.hpp>
#include <cctype>
#include <format>
#include <iostream>
#include <string>
#include <vector>
namespace Void::Logging
{
namespace
{
std::vector<std::string> split_list(std::string_view csv)
{
std::vector<std::string> out;
std::size_t start = 0;
while (start <= csv.size()) {
auto comma = csv.find(',', start);
if (comma == std::string_view::npos) {
comma = csv.size();
}
auto item = csv.substr(start, comma - start);
while (!item.empty() && item.front() == ' ') {
item.remove_prefix(1);
}
while (!item.empty() && item.back() == ' ') {
item.remove_suffix(1);
}
if (!item.empty()) {
out.emplace_back(item);
}
start = comma + 1;
}
return out;
}
std::optional<Level> parse_level(std::string_view name)
{
std::string lower;
for (const char c : name) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "trace") {
return Level::Trace;
}
if (lower == "debug") {
return Level::Debug;
}
if (lower == "info") {
return Level::Info;
}
if (lower == "warning" || lower == "warn") {
return Level::Warning;
}
if (lower == "error") {
return Level::Error;
}
if (lower == "fatal") {
return Level::Fatal;
}
if (lower == "disabled" || lower == "off") {
return Level::Disabled;
}
return std::nullopt;
}
std::optional<Void::Log::Level>
parse_facade_level(std::string_view name)
{
const auto l = parse_level(name);
if (!l.has_value()) {
return std::nullopt;
}
switch (*l) {
case Level::Trace: return Void::Log::Level::Trace;
case Level::Debug: return Void::Log::Level::Debug;
case Level::Info: return Void::Log::Level::Info;
case Level::Warning: return Void::Log::Level::Warning;
case Level::Error: return Void::Log::Level::Error;
case Level::Fatal: return Void::Log::Level::Fatal;
case Level::Disabled: return Void::Log::Level::Disabled;
}
return std::nullopt;
}
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
f.redact = split_list(cfg.get_or("fields.redact", ""));
return f;
}
Void::Result::Result<std::shared_ptr<const Formatter>,
Void::Result::Error>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "default") {
return Void::Result::ok<std::shared_ptr<const Formatter>>(nullptr);
}
if (format == "pattern") {
auto fmt = std::make_shared<PatternFormatter>(std::string{
cfg.get_or("pattern",
"{time} [{level}] {scopes}{message}")});
if (const auto col = cfg.get_as<std::string>("color");
col.has_value()) {
const auto parsed = cfg.get_as<bool>("color");
if (!parsed.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: invalid bool "
"'{}' for color",
*col)));
}
if (*parsed) {
fmt->set_color_policy(ColorPolicy::defaults());
}
}
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
if (format == "json") {
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
if (format == "logfmt") {
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown format '{}'",
format)));
}
struct Dispatch {
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::DropNewest;
};
Void::Result::Result<Dispatch, Void::Result::Error>
make_dispatch(const Configuration::Config& cfg)
{
Dispatch d;
if (cfg.get_as<std::string>("async").has_value()) {
const auto async_val = cfg.get_as<bool>("async");
if (!async_val.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: invalid async bool"));
}
d.mode = *async_val ? Mode::Async : Mode::Immediate;
}
if (cfg.get_as<std::string>("capacity").has_value()) {
const auto cap_val = cfg.get_as<std::size_t>("capacity");
if (!cap_val.has_value() || *cap_val == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: capacity must be positive"));
}
d.capacity = *cap_val;
}
if (const auto overflow = cfg.get_as<std::string>("overflow");
overflow.has_value()) {
if (*overflow == "block") {
d.policy = OverflowPolicy::Block;
} else if (*overflow == "drop_newest") {
d.policy = OverflowPolicy::DropNewest;
} else if (*overflow == "drop_oldest") {
d.policy = OverflowPolicy::DropOldest;
} else {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown overflow "
"policy '{}'",
*overflow)));
}
}
return d;
}
Void::Result::Result<std::size_t, Void::Result::Error>
positive_size_or(const Configuration::Config& cfg,
std::string_view key,
std::size_t fallback)
{
if (!cfg.get_as<std::string>(key).has_value()) {
return fallback;
}
const auto parsed = cfg.get_as<std::size_t>(key);
if (!parsed.has_value() || *parsed == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: '{}' must be > 0",
key)));
}
return *parsed;
}
} // namespace
Void::Result::Result<std::shared_ptr<Logger>, Void::Result::Error>
from_config(const Configuration::Config& cfg, std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
Level parsed_level = Level::Trace;
if (const auto raw_lvl = sub.get_as<std::string>("level");
raw_lvl.has_value()) {
const auto lvl = parse_level(*raw_lvl);
if (!lvl.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown level '{}'",
*raw_lvl)));
}
parsed_level = *lvl;
}
auto dispatch_res = make_dispatch(sub);
if (!dispatch_res.has_value()) {
return Void::Result::fail(std::move(dispatch_res).error());
}
const auto dispatch = *dispatch_res;
auto formatter_res = make_formatter(sub);
if (!formatter_res.has_value()) {
return Void::Result::fail(std::move(formatter_res).error());
}
const auto formatter = std::move(*formatter_res);
const LoggerOptions base_opts{
.mode = dispatch.mode,
.policy = dispatch.policy,
.limits = DeliveryLimits{
.entries = dispatch.capacity,
.owned_bytes = std::max<std::size_t>(
8ULL * 1024ULL * 1024ULL, dispatch.capacity * 1024ULL),
.max_fields = 64,
.max_scopes = 64},
.failure_policy = FailurePolicy::Quarantine,
.suppress_reentrancy = true};
std::vector<std::shared_ptr<Logger>> sinks;
for (const auto& name : split_list(sub.get_or("sinks", "console"))) {
if (name == "console") {
const auto stream = sub.get_or("console.stream", "stderr");
if (stream != "stderr" && stream != "stdout") {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown "
"console.stream '{}'",
stream)));
}
auto sink = std::make_shared<ConsoleLogger>(
stream == "stdout" ? std::cout : std::cerr, dispatch.mode,
dispatch.capacity);
if (formatter) {
sink->set_formatter(formatter);
}
sinks.push_back(std::move(sink));
} else if (name == "file") {
const auto path = sub.get_or("file.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'file' needs file.path"));
}
auto sink =
FileLogger::open(std::filesystem::path{path}, base_opts);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "rotating") {
const auto path = sub.get_or("rotating.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'rotating' needs "
"rotating.path"));
}
auto max_kb = positive_size_or(sub, "rotating.max_kb", 1024);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files =
positive_size_or(sub, "rotating.max_files", 5);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
RotatingFileLogger::Options opt;
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
RotatingFileLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "split") {
const auto dir = sub.get_or("split.dir");
if (dir.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'split' needs split.dir"));
}
auto max_kb = positive_size_or(sub, "split.max_kb", 1024);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files = positive_size_or(sub, "split.max_files", 5);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
SplitFileLogger::Options opt;
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "history") {
const auto path = sub.get_or("history.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'history' needs "
"history.path"));
}
auto max_kb = positive_size_or(sub, "history.max_kb", 8192);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files =
positive_size_or(sub, "history.max_files", 10);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
HistoryLogger::Options opt;
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "syslog") {
#ifdef VOID_HAS_SYSLOG
const auto identity = sub.get_or("syslog.identity");
if (identity.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'syslog' needs "
"syslog.identity"));
}
sinks.push_back(std::make_shared<SyslogLogger>(
std::string{identity}, dispatch.mode, dispatch.capacity));
#else
return Void::Result::fail(make_log_error(
LogErrorCode::unsupported_capability,
"Logging::from_config: syslog is not available on "
"this platform"));
#endif
} else {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown sink '{}'",
name)));
}
}
std::shared_ptr<Logger> root;
if (sinks.empty()) {
root = std::make_shared<NullLogger>(base_opts);
} else if (sinks.size() == 1) {
root = std::move(sinks.front());
} else {
if (sinks.size() > kDefaultMaxFanoutChildren) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: too many sinks"));
}
root = std::make_shared<MultiLogger>(std::move(sinks));
}
root->set_level(parsed_level);
Void::Log::debug("Logging", "from_config: built logger tree");
return Void::Result::ok(std::move(root));
}
void apply_facade_config(const Configuration::Config& cfg,
std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
if (const auto level = parse_facade_level(sub.get_or("level", ""));
level.has_value()) {
Void::Log::set_min_level(*level);
}
for (const auto& key : sub.subtree("module_levels").keys()) {
const auto value = sub.get_or(std::string{"module_levels."} + key);
if (const auto level = parse_facade_level(value);
level.has_value()) {
Void::Log::set_module_level(key, *level);
}
}
}
} // namespace Void::Logging
+4
View File
@@ -0,0 +1,4 @@
void_add_module(LogConfig
INTERNAL_DEPS Log Configuration Functional
EXTRA_HEADERS Void/Log/FromConfig.hpp
)
+7 -1
View File
@@ -12,4 +12,10 @@ namespace Void::Log::Detail
static State s;
return s;
}
} // namespace Void::Log::Detail
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept
{
static thread_local std::vector<const SinkRegistration*> stack;
return stack;
}
} // namespace Void::Log::Detail