Overhaul Logging and Configuration; integrate the log facade library-wide
Void::Log facade (header-only, macro-free):
- Leveled function templates trace/debug/info/warn/error/fatal(module,
fmt, args...) with lazy formatting - a disabled call is one relaxed
atomic load, no allocation, no formatting.
- Global min level + per-module overrides (can raise or lower); empty
sink/Disabled level = logging fully off; set_sink remains the splice
point for external logging libraries.
Void::Logging::Logger - async by default, one class for both modes:
- Mode::Async (default): lock-free MPSC queue + logger-owned worker
delivering batches via on_flush outside any lock; Immediate/Buffered
give synchronous behavior via constructor arg or set_mode at runtime.
- Bounded queue with OverflowPolicy{Block, DropNewest, DropOldest};
flush() (now virtual) blocks until everything submitted is delivered;
base destructor only stops/joins the worker, never touches virtuals.
- Fixed a wakeup race: stale park token + fresh release overflowed the
binary semaphore; wakeup is a counting semaphore (spurious wakes are
absorbed by the worker loop).
New sinks and formatters:
- RotatingFileLogger (size-based rotation, max-files cap), NullLogger,
CallbackLogger, MultiLogger (tee via new Logger::relay), SyslogLogger.
- Formatter interface: PatternFormatter ({time}/{level}/{scopes}/...),
JsonLinesFormatter, LogfmtFormatter; installable on Console/File/
Rotating sinks. Console/File sinks now default to Async.
- Logging::from_config builds the whole sink tree from Config keys;
apply_facade_config drives facade levels.
Configuration:
- Typed get_as<T>/get_or_as<T> (numbers, bool spellings, enums by name,
chrono durations), dotted keys, subtree(), sorted keys().
- New sources: from_env_prefix (APP_LOG__LEVEL -> log.level), from_ini
(sections as prefixes), from_json (objects/arrays flattened),
from_args (--key=value / --key value / --flag).
- Bind.hpp: reflection bind<T>(cfg, prefix) fills aggregates; defaults
in the struct are the schema; nested aggregates, optional, vector.
- Watch.hpp: ConfigWatch reloads on change with per-key diff; parse
failures keep the previous config.
System: new FileSystem::FileWatcher - debounced polling watcher (stable
mtime+size across N polls), callbacks off-thread, deletion events;
shared groundwork for plugin hot-reload.
Sweep: all internal Void::Log::log call sites migrated to the leveled
API ("Umbrella.Feature" labels); Plugin loader now logs load/reload.
918 tests green (28 new), stable across 30 consecutive runs, ASan+UBSan
clean.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8a6065539a
commit
c74a02a5a5
43 files changed
+3889
-236
No files matched your search
@@ -89,7 +89,12 @@ namespace Void::Logging
|
||||
|
||||
void ConsoleLogger::write(const Entry& entry)
|
||||
{
|
||||
m_out << format_entry(entry);
|
||||
if (m_formatter) {
|
||||
m_out << m_formatter->format(entry) << '\n';
|
||||
}
|
||||
else {
|
||||
m_out << format_entry(entry);
|
||||
}
|
||||
m_out.flush();
|
||||
}
|
||||
|
||||
|
||||
+17
-11
@@ -13,14 +13,11 @@ namespace Void::Logging
|
||||
: Logger(mode, capacity), m_path(path), m_file(path, std::ios::app)
|
||||
{
|
||||
if (!m_file.is_open()) {
|
||||
Void::Log::log(
|
||||
Void::Log::Level::Warning, "Logging",
|
||||
std::format("FileLogger: cannot open '{}'", path.string()));
|
||||
Void::Log::warn("Logging", "FileLogger: cannot open '{}'", path.string());
|
||||
throw std::runtime_error(
|
||||
std::format("FileLogger: cannot open '{}'", path.string()));
|
||||
}
|
||||
Void::Log::log(Void::Log::Level::Debug, "Logging",
|
||||
std::format("FileLogger: opened '{}'", path.string()));
|
||||
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
|
||||
}
|
||||
|
||||
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
|
||||
@@ -39,24 +36,33 @@ namespace Void::Logging
|
||||
FileLogger::~FileLogger() noexcept
|
||||
{
|
||||
flush();
|
||||
Void::Log::log(Void::Log::Level::Debug, "Logging",
|
||||
std::format("FileLogger: closed '{}'",
|
||||
m_path.string()));
|
||||
Void::Log::debug("Logging", "FileLogger: closed '{}'",
|
||||
m_path.string());
|
||||
}
|
||||
|
||||
void FileLogger::write(const Entry& entry)
|
||||
{
|
||||
m_file << std::format(
|
||||
"[{}] {}\n", to_string(entry.level), entry.message);
|
||||
append(entry);
|
||||
m_file.flush();
|
||||
}
|
||||
|
||||
void FileLogger::on_flush(std::span<const Entry> entries)
|
||||
{
|
||||
for (const auto& e : entries) {
|
||||
m_file << std::format("[{}] {}\n", to_string(e.level), e.message);
|
||||
append(e);
|
||||
}
|
||||
m_file.flush();
|
||||
}
|
||||
|
||||
void FileLogger::append(const Entry& entry)
|
||||
{
|
||||
if (m_formatter) {
|
||||
m_file << m_formatter->format(entry) << '\n';
|
||||
}
|
||||
else {
|
||||
m_file << std::format(
|
||||
"[{}] {}\n", to_string(entry.level), entry.message);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,250 @@
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Data/Json.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <format>
|
||||
#include <sstream>
|
||||
#include <string_view>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace FormatDetail
|
||||
{
|
||||
|
||||
std::string iso8601(std::chrono::system_clock::time_point tp)
|
||||
{
|
||||
const auto ms = std::chrono::floor<std::chrono::milliseconds>(tp);
|
||||
return std::format("{:%FT%H:%M:%S}Z", ms);
|
||||
}
|
||||
|
||||
std::string scope_breadcrumb(const std::vector<std::string>& scopes)
|
||||
{
|
||||
std::string out;
|
||||
for (const auto& s : scopes) {
|
||||
if (!out.empty()) {
|
||||
out += '.';
|
||||
}
|
||||
out += s;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
namespace
|
||||
{
|
||||
std::string thread_str(std::thread::id id)
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << id;
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
std::string_view kind_str(Kind kind)
|
||||
{
|
||||
switch (kind) {
|
||||
case Kind::Message:
|
||||
return "Message";
|
||||
case Kind::ScopeEnter:
|
||||
return "ScopeEnter";
|
||||
case Kind::ScopeExit:
|
||||
return "ScopeExit";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
std::string file_basename(const Entry& entry)
|
||||
{
|
||||
const char* file = entry.location.file_name();
|
||||
if (file == nullptr || *file == '\0') {
|
||||
return {};
|
||||
}
|
||||
return std::filesystem::path{file}.filename().string();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
} // namespace FormatDetail
|
||||
|
||||
// =============================================================================
|
||||
// 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 = {};
|
||||
}
|
||||
};
|
||||
|
||||
while (!rest.empty()) {
|
||||
const auto open = rest.find('{');
|
||||
if (open == std::string_view::npos) {
|
||||
literal += rest;
|
||||
break;
|
||||
}
|
||||
literal += rest.substr(0, open);
|
||||
rest.remove_prefix(open);
|
||||
const auto close = rest.find('}');
|
||||
if (close == std::string_view::npos) {
|
||||
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;
|
||||
}
|
||||
|
||||
if (token == Token::Literal) {
|
||||
// Unknown placeholder — keep it verbatim.
|
||||
literal += rest.substr(0, close + 1);
|
||||
} else {
|
||||
flush_literal();
|
||||
m_segments.push_back({token, {}});
|
||||
}
|
||||
rest.remove_prefix(close + 1);
|
||||
}
|
||||
flush_literal();
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// JsonLinesFormatter
|
||||
// =============================================================================
|
||||
|
||||
std::string JsonLinesFormatter::format(const Entry& entry) const
|
||||
{
|
||||
auto obj = Json::object();
|
||||
auto& o = obj.as_object();
|
||||
o.emplace_back("time",
|
||||
Json::Value{FormatDetail::iso8601(entry.timestamp)});
|
||||
o.emplace_back("level", Json::Value{to_string(entry.level)});
|
||||
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.scopes.empty()) {
|
||||
auto arr = Json::array();
|
||||
arr.as_array().reserve(entry.scopes.size());
|
||||
for (const auto& s : entry.scopes) {
|
||||
arr.as_array().emplace_back(s);
|
||||
}
|
||||
o.emplace_back("scopes", std::move(arr));
|
||||
}
|
||||
o.emplace_back("message", Json::Value{entry.message});
|
||||
if (auto file = FormatDetail::file_basename(entry); !file.empty()) {
|
||||
o.emplace_back("file", Json::Value{file});
|
||||
o.emplace_back(
|
||||
"line",
|
||||
Json::Value{static_cast<double>(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 += '\\';
|
||||
}
|
||||
out += c;
|
||||
}
|
||||
out += '"';
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::string LogfmtFormatter::format(const Entry& entry) const
|
||||
{
|
||||
std::string out;
|
||||
out += "time=";
|
||||
out += FormatDetail::iso8601(entry.timestamp);
|
||||
out += " level=";
|
||||
out += to_string(entry.level);
|
||||
out += " thread=";
|
||||
out += FormatDetail::thread_str(entry.thread_id);
|
||||
if (auto crumb = FormatDetail::scope_breadcrumb(entry.scopes);
|
||||
!crumb.empty()) {
|
||||
out += " scopes=";
|
||||
out += crumb;
|
||||
}
|
||||
if (auto file = FormatDetail::file_basename(entry); !file.empty()) {
|
||||
out += " file=";
|
||||
out += file;
|
||||
out += ':';
|
||||
out += std::to_string(entry.location.line());
|
||||
}
|
||||
out += " msg=";
|
||||
append_quoted(out, entry.message);
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,259 @@
|
||||
#include <Void/Log/FromConfig.hpp>
|
||||
#include <Void/Log/ConsoleLogger.hpp>
|
||||
#include <Void/Log/FileLogger.hpp>
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.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;
|
||||
}
|
||||
|
||||
std::shared_ptr<const Formatter>
|
||||
make_formatter(const Configuration::Config& cfg)
|
||||
{
|
||||
const auto format = cfg.get_or("format", "default");
|
||||
if (format == "pattern") {
|
||||
return std::make_shared<PatternFormatter>(
|
||||
std::string{cfg.get_or(
|
||||
"pattern", "{time} [{level}] {scopes}{message}")});
|
||||
}
|
||||
if (format == "json") {
|
||||
return std::make_shared<JsonLinesFormatter>();
|
||||
}
|
||||
if (format == "logfmt") {
|
||||
return std::make_shared<LogfmtFormatter>();
|
||||
}
|
||||
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 == "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
|
||||
+200
-46
@@ -65,62 +65,85 @@ namespace Void::Logging
|
||||
// Logger — lifetime
|
||||
// =============================================================================
|
||||
|
||||
Logger::Logger(Mode mode, std::size_t capacity) noexcept
|
||||
: m_mode(mode), m_buffer_capacity(capacity)
|
||||
Logger::Logger(Mode mode, std::size_t capacity,
|
||||
OverflowPolicy policy) noexcept
|
||||
: m_mode(mode),
|
||||
m_async_capacity(capacity > 0 ? capacity : 1),
|
||||
m_policy(policy),
|
||||
m_buffer_capacity(capacity > 0 ? capacity : 1),
|
||||
m_space(static_cast<std::ptrdiff_t>(capacity > 0 ? capacity : 1))
|
||||
{
|
||||
if (m_mode == Mode::Buffered) {
|
||||
if (mode == Mode::Buffered) {
|
||||
m_buffer.reserve(m_buffer_capacity);
|
||||
}
|
||||
}
|
||||
|
||||
Logger::~Logger() noexcept
|
||||
{
|
||||
// Only stop and join the worker. Virtual extension points must not
|
||||
// be touched here — the derived class is already destroyed. Pending
|
||||
// entries are freed (silently dropped) by the queue's destructor.
|
||||
m_stop.store(true, std::memory_order_release);
|
||||
wake_worker();
|
||||
if (m_worker.joinable()) {
|
||||
m_worker.join();
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Configuration
|
||||
// =============================================================================
|
||||
|
||||
void Logger::set_level(Level level) noexcept
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
m_level = level;
|
||||
m_level.store(level, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
Level Logger::level() const noexcept
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
return m_level;
|
||||
return m_level.load(std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
void Logger::set_mode(Mode mode) noexcept
|
||||
{
|
||||
std::vector<Entry> to_flush;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
if (m_mode == mode) {
|
||||
return;
|
||||
}
|
||||
// Flush any buffered entries before switching modes.
|
||||
to_flush = std::move(m_buffer);
|
||||
m_buffer = {};
|
||||
m_mode = mode;
|
||||
const Mode old = m_mode.load(std::memory_order_acquire);
|
||||
if (old == mode) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_mode == Mode::Buffered) {
|
||||
m_buffer.reserve(m_buffer_capacity);
|
||||
// Deliver everything pending under the old strategy first so no
|
||||
// entry is stranded in a queue/buffer nobody drains anymore.
|
||||
if (old == Mode::Async) {
|
||||
drain_async();
|
||||
}
|
||||
else if (old == Mode::Buffered) {
|
||||
std::vector<Entry> to_flush;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
to_flush = std::move(m_buffer);
|
||||
m_buffer = {};
|
||||
}
|
||||
if (!to_flush.empty()) {
|
||||
on_flush(to_flush);
|
||||
}
|
||||
}
|
||||
if (!to_flush.empty()) {
|
||||
on_flush(to_flush); // called outside the lock
|
||||
|
||||
if (mode == Mode::Buffered) {
|
||||
std::lock_guard lock(m_mutex);
|
||||
m_buffer.reserve(m_buffer_capacity);
|
||||
}
|
||||
m_mode.store(mode, std::memory_order_release);
|
||||
}
|
||||
|
||||
Mode Logger::mode() const noexcept
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
return m_mode;
|
||||
return m_mode.load(std::memory_order_acquire);
|
||||
}
|
||||
|
||||
void Logger::set_buffer_capacity(std::size_t n) noexcept
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
m_buffer_capacity = n;
|
||||
m_buffer_capacity = n > 0 ? n : 1;
|
||||
}
|
||||
|
||||
std::size_t Logger::buffer_capacity() const noexcept
|
||||
@@ -129,6 +152,11 @@ namespace Void::Logging
|
||||
return m_buffer_capacity;
|
||||
}
|
||||
|
||||
OverflowPolicy Logger::overflow_policy() const noexcept
|
||||
{
|
||||
return m_policy;
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Scoped context
|
||||
// =============================================================================
|
||||
@@ -194,6 +222,11 @@ namespace Void::Logging
|
||||
submit(std::move(entry));
|
||||
}
|
||||
|
||||
void Logger::relay(Entry entry)
|
||||
{
|
||||
submit(std::move(entry));
|
||||
}
|
||||
|
||||
void Logger::trace(std::string_view msg, std::source_location loc)
|
||||
{
|
||||
log(Level::Trace, msg, loc);
|
||||
@@ -225,6 +258,10 @@ namespace Void::Logging
|
||||
|
||||
void Logger::flush()
|
||||
{
|
||||
if (m_mode.load(std::memory_order_acquire) == Mode::Async) {
|
||||
drain_async();
|
||||
return;
|
||||
}
|
||||
std::vector<Entry> to_flush;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
@@ -281,36 +318,153 @@ namespace Void::Logging
|
||||
|
||||
void Logger::submit(Entry entry)
|
||||
{
|
||||
bool write_now = false;
|
||||
if (entry.level < m_level.load(std::memory_order_relaxed)) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (m_mode.load(std::memory_order_acquire)) {
|
||||
case Mode::Async:
|
||||
async_submit(std::move(entry));
|
||||
return;
|
||||
|
||||
case Mode::Immediate:
|
||||
// Virtual call outside any lock (see class documentation).
|
||||
write(entry);
|
||||
return;
|
||||
|
||||
case Mode::Buffered: {
|
||||
std::vector<Entry> batch;
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
m_buffer.push_back(std::move(entry));
|
||||
if (m_buffer.size() >= m_buffer_capacity) {
|
||||
batch = std::move(m_buffer);
|
||||
m_buffer = {};
|
||||
m_buffer.reserve(m_buffer_capacity);
|
||||
}
|
||||
}
|
||||
if (!batch.empty()) {
|
||||
on_flush(batch);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// Private — async machinery
|
||||
// =============================================================================
|
||||
|
||||
void Logger::async_submit(Entry entry)
|
||||
{
|
||||
start_worker();
|
||||
|
||||
switch (m_policy) {
|
||||
case OverflowPolicy::Block:
|
||||
// Wait for queue space; the worker releases one slot per
|
||||
// popped entry. Nothing is ever dropped.
|
||||
m_space.acquire();
|
||||
break;
|
||||
|
||||
case OverflowPolicy::DropNewest:
|
||||
if (!m_space.try_acquire()) {
|
||||
return; // full — discard the incoming entry
|
||||
}
|
||||
break;
|
||||
|
||||
case OverflowPolicy::DropOldest:
|
||||
// Unbounded enqueue; the worker trims the oldest entries
|
||||
// down to capacity when it falls behind.
|
||||
break;
|
||||
}
|
||||
|
||||
m_submitted.fetch_add(1, std::memory_order_release);
|
||||
m_queue.push(std::move(entry));
|
||||
wake_worker();
|
||||
}
|
||||
|
||||
void Logger::start_worker()
|
||||
{
|
||||
if (m_worker_started.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
std::call_once(m_worker_once, [this] {
|
||||
m_worker = std::thread([this] { worker_loop(); });
|
||||
m_worker_started.store(true, std::memory_order_release);
|
||||
});
|
||||
}
|
||||
|
||||
void Logger::wake_worker() noexcept
|
||||
{
|
||||
if (m_sleeping.exchange(false, std::memory_order_acq_rel)) {
|
||||
m_wakeup.release();
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::worker_loop()
|
||||
{
|
||||
std::vector<Entry> batch;
|
||||
const bool counts_space = m_policy != OverflowPolicy::DropOldest;
|
||||
|
||||
{
|
||||
std::lock_guard lock(m_mutex);
|
||||
for (;;) {
|
||||
// Drain everything currently queued.
|
||||
while (auto e = m_queue.try_pop()) {
|
||||
batch.push_back(std::move(*e));
|
||||
if (counts_space) {
|
||||
m_space.release();
|
||||
}
|
||||
}
|
||||
|
||||
// Re-check level under the lock; set_level() may have raced.
|
||||
if (entry.level < m_level) {
|
||||
if (!batch.empty()) {
|
||||
const bool stopping = m_stop.load(std::memory_order_acquire);
|
||||
|
||||
std::size_t dropped = 0;
|
||||
if (m_policy == OverflowPolicy::DropOldest &&
|
||||
batch.size() > m_async_capacity) {
|
||||
dropped = batch.size() - m_async_capacity;
|
||||
batch.erase(batch.begin(),
|
||||
batch.begin() +
|
||||
static_cast<std::ptrdiff_t>(dropped));
|
||||
}
|
||||
|
||||
// After stop the derived class may already be destroyed —
|
||||
// never touch the virtuals; just account and discard.
|
||||
if (!stopping) {
|
||||
on_flush(batch);
|
||||
}
|
||||
m_completed.fetch_add(batch.size() + dropped,
|
||||
std::memory_order_release);
|
||||
m_completed.notify_all();
|
||||
batch.clear();
|
||||
continue; // re-poll before considering a park
|
||||
}
|
||||
|
||||
if (m_stop.load(std::memory_order_acquire)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (m_mode == Mode::Immediate) {
|
||||
write_now = true;
|
||||
// entry intentionally NOT moved — used below outside the lock.
|
||||
} else {
|
||||
m_buffer.push_back(std::move(entry));
|
||||
|
||||
if (m_buffer.size() >= m_buffer_capacity) {
|
||||
batch = std::move(m_buffer);
|
||||
m_buffer = {};
|
||||
m_buffer.reserve(m_buffer_capacity);
|
||||
}
|
||||
// Park. Producers re-check m_sleeping after pushing, so a wake
|
||||
// between the store and acquire below cannot be missed.
|
||||
m_sleeping.store(true, std::memory_order_release);
|
||||
if (!m_queue.empty() || m_stop.load(std::memory_order_acquire)) {
|
||||
m_sleeping.store(false, std::memory_order_release);
|
||||
continue;
|
||||
}
|
||||
} // ← mutex released here
|
||||
m_wakeup.acquire();
|
||||
m_sleeping.store(false, std::memory_order_release);
|
||||
}
|
||||
}
|
||||
|
||||
// Virtual calls happen outside the lock (see class documentation).
|
||||
if (write_now) {
|
||||
write(entry); // entry was not moved in this branch
|
||||
} else if (!batch.empty()) {
|
||||
on_flush(batch);
|
||||
void Logger::drain_async()
|
||||
{
|
||||
const auto target = m_submitted.load(std::memory_order_acquire);
|
||||
for (;;) {
|
||||
const auto done = m_completed.load(std::memory_order_acquire);
|
||||
if (done >= target) {
|
||||
return;
|
||||
}
|
||||
wake_worker();
|
||||
m_completed.wait(done, std::memory_order_acquire);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
|
||||
#include <format>
|
||||
#include <stdexcept>
|
||||
#include <system_error>
|
||||
|
||||
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)
|
||||
{
|
||||
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()) {
|
||||
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::Result::Result<std::unique_ptr<RotatingFileLogger>,
|
||||
Void::Result::Error>
|
||||
RotatingFileLogger::open(const std::filesystem::path& path,
|
||||
Options options)
|
||||
{
|
||||
try {
|
||||
return Void::Result::ok(
|
||||
std::make_unique<RotatingFileLogger>(path, options));
|
||||
} catch (const std::exception& e) {
|
||||
return Void::Result::fail(std::string{e.what()});
|
||||
}
|
||||
}
|
||||
|
||||
RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); }
|
||||
|
||||
void RotatingFileLogger::write(const Entry& entry)
|
||||
{
|
||||
append(entry);
|
||||
m_file.flush();
|
||||
rotate_if_needed();
|
||||
}
|
||||
|
||||
void RotatingFileLogger::on_flush(std::span<const Entry> entries)
|
||||
{
|
||||
for (const auto& entry : entries) {
|
||||
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);
|
||||
} else {
|
||||
line =
|
||||
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
|
||||
@@ -0,0 +1,55 @@
|
||||
#include <Void/Log/SyslogLogger.hpp>
|
||||
|
||||
#ifdef VOID_HAS_SYSLOG
|
||||
|
||||
#include <syslog.h>
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
|
||||
namespace
|
||||
{
|
||||
int priority_for(Level level) noexcept
|
||||
{
|
||||
switch (level) {
|
||||
case Level::Trace:
|
||||
case Level::Debug:
|
||||
return LOG_DEBUG;
|
||||
case Level::Info:
|
||||
return LOG_INFO;
|
||||
case Level::Warning:
|
||||
return LOG_WARNING;
|
||||
case Level::Error:
|
||||
return LOG_ERR;
|
||||
case Level::Fatal:
|
||||
return LOG_CRIT;
|
||||
case Level::Disabled:
|
||||
break;
|
||||
}
|
||||
return LOG_INFO;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
SyslogLogger::SyslogLogger(std::string identity, Mode mode,
|
||||
std::size_t capacity)
|
||||
: Logger(mode, capacity), m_identity(std::move(identity))
|
||||
{
|
||||
::openlog(m_identity.c_str(), LOG_PID, LOG_USER);
|
||||
}
|
||||
|
||||
SyslogLogger::~SyslogLogger() noexcept
|
||||
{
|
||||
flush();
|
||||
::closelog();
|
||||
}
|
||||
|
||||
void SyslogLogger::write(const Entry& entry)
|
||||
{
|
||||
::syslog(priority_for(entry.level), "%s", entry.message.c_str());
|
||||
}
|
||||
|
||||
} // namespace Void::Logging
|
||||
|
||||
#endif // VOID_HAS_SYSLOG
|
||||
@@ -1,4 +1,4 @@
|
||||
void_add_module(Log
|
||||
INTERNAL_DEPS Functional
|
||||
INTERNAL_DEPS Functional Configuration
|
||||
OPTIONAL_DEPS Stacktrace
|
||||
)
|
||||
Reference in new issue
Block a user