Initial commit: VoidLibrary C++23 modular library
Adds Logging module with thread-safe Logger base class, ScopedContext RAII guards, Preset helpers, and a FileLogger standalone test/example. Includes CMake module system for auto-discovery and CTest integration. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
commit
4fc129fb7e
17 files changed
+1910
No files matched your search
@@ -0,0 +1,53 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Logging/Level.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <source_location>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
/// Distinguishes regular messages from scope boundary markers.
|
||||
///
|
||||
/// Sinks may use Kind to render scope entries differently —
|
||||
/// e.g. with indentation, brackets, or a dedicated colour.
|
||||
///
|
||||
/// Message — a regular log record
|
||||
/// ScopeEnter — emitted when a named scope opens (scope() call)
|
||||
/// ScopeExit — emitted when a named scope closes (RAII destructor)
|
||||
enum class Kind { Message, ScopeEnter, ScopeExit };
|
||||
|
||||
/// A single, immutable log record produced by Logger and handed to
|
||||
/// write() / on_flush(). All fields are populated by Logger before
|
||||
/// dispatch; derived sinks treat Entry as read-only.
|
||||
struct Entry {
|
||||
Kind kind{Kind::Message};
|
||||
Level level{Level::Debug};
|
||||
|
||||
/// Human-readable text. For ScopeEnter/ScopeExit entries this
|
||||
/// is the scope name.
|
||||
std::string message{};
|
||||
|
||||
/// Wall-clock time at the moment log() / scope() was called.
|
||||
std::chrono::system_clock::time_point timestamp{
|
||||
std::chrono::system_clock::now()};
|
||||
|
||||
/// Caller site captured automatically via
|
||||
/// std::source_location::current().
|
||||
std::source_location location{};
|
||||
|
||||
/// OS thread that produced this entry.
|
||||
std::thread::id thread_id{std::this_thread::get_id()};
|
||||
|
||||
/// Frozen snapshot of the thread-local ScopedContext stack at log
|
||||
/// time. Ordered outermost → innermost (index 0 is the root
|
||||
/// scope). For ScopeEnter this already includes the new scope as
|
||||
/// the last element; for ScopeExit it reflects the stack *before*
|
||||
/// the pop.
|
||||
std::vector<std::string> scopes{};
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include <format>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
enum class Level { Disabled, Trace, Debug, Info, Warning, Error, Fatal };
|
||||
|
||||
[[nodiscard]] constexpr bool operator<(Level a, Level b) noexcept
|
||||
{
|
||||
return std::to_underlying(a) < std::to_underlying(b);
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator<=(Level a, Level b) noexcept
|
||||
{
|
||||
return std::to_underlying(a) <= std::to_underlying(b);
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator>(Level a, Level b) noexcept
|
||||
{
|
||||
return std::to_underlying(a) > std::to_underlying(b);
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool operator>=(Level a, Level b) noexcept
|
||||
{
|
||||
return std::to_underlying(a) >= std::to_underlying(b);
|
||||
}
|
||||
|
||||
/// Convert a Level to its canonical string representation.
|
||||
/// Defined inline so it is usable in constexpr contexts and
|
||||
/// visible to every translation unit without ODR violations.
|
||||
[[nodiscard]] constexpr std::string_view to_string(Level level) noexcept
|
||||
{
|
||||
switch (level) {
|
||||
case Level::Disabled:
|
||||
return "DISABLED";
|
||||
case Level::Trace:
|
||||
return "TRACE";
|
||||
case Level::Debug:
|
||||
return "DEBUG";
|
||||
case Level::Info:
|
||||
return "INFO";
|
||||
case Level::Warning:
|
||||
return "WARN";
|
||||
case Level::Error:
|
||||
return "ERROR";
|
||||
case Level::Fatal:
|
||||
return "FATAL";
|
||||
default:
|
||||
return "UNK";
|
||||
}
|
||||
}
|
||||
} // namespace Void::Logging
|
||||
|
||||
// ADL-visible free overload so std::format("{}", level) works.
|
||||
template <>
|
||||
struct std::formatter<Void::Logging::Level> : std::formatter<std::string_view> {
|
||||
template <class FormatContext>
|
||||
auto format(Void::Logging::Level level, FormatContext& ctx) const
|
||||
{
|
||||
return std::formatter<std::string_view>::format(
|
||||
Void::Logging::to_string(level), ctx);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,467 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Logging/Entry.hpp>
|
||||
#include <Void/Logging/Level.hpp>
|
||||
|
||||
#include <concepts>
|
||||
#include <cstddef>
|
||||
#include <format>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <source_location>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Logging
|
||||
{
|
||||
enum class Mode { Immediate, Buffered };
|
||||
|
||||
/// Abstract base class for all Void loggers.
|
||||
///
|
||||
/// ## Responsibilities
|
||||
/// - Level filtering (thread-safe)
|
||||
/// - Entry construction: timestamp, thread_id, scope snapshot
|
||||
/// - Immediate vs. Buffered dispatch (auto-flushes when buffer is full)
|
||||
/// - Thread-safe submission — the internal mutex protects only the
|
||||
/// buffer; virtual extension points are called *outside* the lock so
|
||||
/// derived classes may perform blocking I/O or acquire their own
|
||||
/// resources freely.
|
||||
/// - Scoped context via per-thread RAII guards (Logger::ScopedContext)
|
||||
/// - Named scope logging: scope() emits ScopeEnter/ScopeExit entries
|
||||
/// - Logger presets via make_preset() — bake in a level (and optional
|
||||
/// message prefix) and later call with only the message/format args.
|
||||
///
|
||||
/// ## What this class deliberately does NOT do
|
||||
/// - Spawn or manage threads / coroutines → use Void::Concurrency
|
||||
/// - Open, close, or rotate files → use Void::Filesystem
|
||||
///
|
||||
/// ## Deriving a logger
|
||||
/// 1. Override `write(const Entry&)` — called once per entry in
|
||||
/// Immediate mode and by the default `on_flush` implementation.
|
||||
/// 2. Optionally override `on_flush(std::span<const Entry>)` — useful
|
||||
/// for sinks that benefit from batch writes (e.g. file loggers).
|
||||
/// 3. **Call `flush()` in your own destructor** before the base
|
||||
/// destructor runs. Calling a pure virtual from `~Logger` is
|
||||
/// undefined behaviour, so the base destructor does *not* flush;
|
||||
/// any unflushed entries that remain after your destructor will be
|
||||
/// silently discarded.
|
||||
///
|
||||
/// ## Example — minimal derived logger
|
||||
/// @code
|
||||
/// class StdoutLogger final : public Void::Logging::Logger
|
||||
/// {
|
||||
/// public:
|
||||
/// ~StdoutLogger() noexcept override { flush(); }
|
||||
/// protected:
|
||||
/// void write(const Void::Logging::Entry& e) override
|
||||
/// {
|
||||
/// std::println("[{}] {}", e.level, e.message);
|
||||
/// }
|
||||
/// };
|
||||
/// @endcode
|
||||
class Logger
|
||||
{
|
||||
public:
|
||||
|
||||
// =========================================================================
|
||||
// ScopedContext — RAII, per-thread, named scope push/pop
|
||||
//
|
||||
// Pushing a scope has two effects:
|
||||
// 1. The scope name is appended to this thread's scope stack so
|
||||
// all subsequent entries carry it in Entry::scopes.
|
||||
// 2. A ScopeEnter entry is emitted at the level supplied to
|
||||
// push_scope() (or Trace by default).
|
||||
// 3. On destruction a ScopeExit entry is emitted at the same
|
||||
// level.
|
||||
//
|
||||
// Usage:
|
||||
// {
|
||||
// auto s = logger.push_scope("network"); // →
|
||||
// ScopeEnter logger.info("connecting …"); //
|
||||
// scopes={"network"}
|
||||
// {
|
||||
// auto t = logger.push_scope("tls"); // →
|
||||
// ScopeEnter logger.debug("handshake"); //
|
||||
// scopes={"network","tls"}
|
||||
// } // → ScopeExit
|
||||
// "tls"
|
||||
// } // → ScopeExit
|
||||
// "network"
|
||||
// =========================================================================
|
||||
class ScopedContext
|
||||
{
|
||||
public:
|
||||
|
||||
explicit ScopedContext(Logger& owner,
|
||||
std::string name,
|
||||
Level level,
|
||||
std::source_location loc) noexcept;
|
||||
~ScopedContext() noexcept;
|
||||
|
||||
// Non-copyable; move transfers ownership so the moved-from
|
||||
// guard does not emit a spurious ScopeExit on destruction.
|
||||
ScopedContext(const ScopedContext&) = delete;
|
||||
ScopedContext& operator=(const ScopedContext&) = delete;
|
||||
ScopedContext(ScopedContext&&) noexcept;
|
||||
ScopedContext& operator=(ScopedContext&&) = delete;
|
||||
|
||||
private:
|
||||
|
||||
Logger* m_owner{nullptr};
|
||||
std::string m_name;
|
||||
Level m_level{Level::Trace};
|
||||
bool m_active{true};
|
||||
};
|
||||
|
||||
// =========================================================================
|
||||
// Preset — a partially-applied logger
|
||||
//
|
||||
// A Preset captures a reference to the owning Logger together with
|
||||
// a fixed Level (and optional message prefix). Call it with just
|
||||
// the message / format args; the level is already baked in.
|
||||
//
|
||||
// Lifetime: a Preset must not outlive the Logger it was made from.
|
||||
//
|
||||
// Usage:
|
||||
// auto net_err = logger.make_preset(Level::Error, "[network] ");
|
||||
// net_err("connection refused"); // same as:
|
||||
// // logger.error("[network] connection refused");
|
||||
//
|
||||
// auto dbg = logger.make_preset(Level::Debug);
|
||||
// dbg("value = {}", 42);
|
||||
// =========================================================================
|
||||
class Preset
|
||||
{
|
||||
public:
|
||||
|
||||
Preset(Logger& owner, Level level,
|
||||
std::string prefix = {}) noexcept
|
||||
: m_owner(&owner), m_level(level),
|
||||
m_prefix(std::move(prefix))
|
||||
{
|
||||
}
|
||||
|
||||
// Non-owning; copyable so presets can be stored / passed
|
||||
// around.
|
||||
Preset(const Preset&) = default;
|
||||
Preset& operator=(const Preset&) = default;
|
||||
Preset(Preset&&) = default;
|
||||
Preset& operator=(Preset&&) = default;
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Plain string overload
|
||||
// -----------------------------------------------------------------
|
||||
void operator()(std::string_view message,
|
||||
std::source_location loc =
|
||||
std::source_location::current()) const
|
||||
{
|
||||
if (m_prefix.empty()) {
|
||||
m_owner->log(m_level, message, loc);
|
||||
} else {
|
||||
m_owner->log(m_level,
|
||||
std::format("{}{}", m_prefix, message),
|
||||
loc);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================================================================
|
||||
// FormatWithLocation helper
|
||||
//
|
||||
// std::source_location cannot share a parameter list with
|
||||
// a variadic pack, so this wrapper type captures both the
|
||||
// format string and the caller's source location in its
|
||||
// constructor.
|
||||
//
|
||||
// std::type_identity_t<Args>... prevents Args from being
|
||||
// deduced from the wrapper; they are deduced solely from
|
||||
// the trailing pack.
|
||||
//
|
||||
// Usage — source location is captured transparently:
|
||||
// logger.info("player {} scored {} points", name,
|
||||
// score);
|
||||
// =========================================================================
|
||||
template <typename... Args> struct FormatWithLocation {
|
||||
std::format_string<Args...> fmt;
|
||||
std::source_location location;
|
||||
|
||||
template <std::convertible_to<std::string_view> T>
|
||||
consteval FormatWithLocation(
|
||||
T&& f,
|
||||
std::source_location loc =
|
||||
std::source_location::current())
|
||||
: fmt(std::forward<T>(f)), location(loc)
|
||||
{
|
||||
}
|
||||
};
|
||||
|
||||
// -----------------------------------------------------------------
|
||||
// Formatted overload
|
||||
// Uses the same FormatWithLocation trick as Logger itself
|
||||
// so the call-site source location is captured
|
||||
// transparently.
|
||||
// -----------------------------------------------------------------
|
||||
template <typename... Args>
|
||||
void operator()(
|
||||
FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args) const
|
||||
{
|
||||
auto msg =
|
||||
m_prefix.empty()
|
||||
? std::format(fwl.fmt,
|
||||
std::forward<Args>(args)...)
|
||||
: std::format(
|
||||
"{}{}", m_prefix,
|
||||
std::format(fwl.fmt,
|
||||
std::forward<Args>(args)...));
|
||||
m_owner->log(m_level, msg, fwl.location);
|
||||
}
|
||||
|
||||
// Accessors
|
||||
[[nodiscard]] Level level() const noexcept
|
||||
{
|
||||
return m_level;
|
||||
}
|
||||
[[nodiscard]] const std::string& prefix() const noexcept
|
||||
{
|
||||
return m_prefix;
|
||||
}
|
||||
[[nodiscard]] Logger& logger() const noexcept
|
||||
{
|
||||
return *m_owner;
|
||||
}
|
||||
|
||||
private:
|
||||
|
||||
Logger* m_owner{nullptr};
|
||||
Level m_level{Level::Trace};
|
||||
std::string m_prefix;
|
||||
};
|
||||
|
||||
// =========================================================================
|
||||
// Lifetime
|
||||
// =========================================================================
|
||||
explicit Logger(Mode mode = Mode::Immediate,
|
||||
std::size_t capacity = 512) noexcept;
|
||||
|
||||
/// Does NOT flush remaining buffered entries — see class-level
|
||||
/// note.
|
||||
virtual ~Logger() noexcept = default;
|
||||
|
||||
Logger(const Logger&) = delete;
|
||||
Logger& operator=(const Logger&) = delete;
|
||||
Logger(Logger&&) = delete;
|
||||
Logger& operator=(Logger&&) = delete;
|
||||
|
||||
// =========================================================================
|
||||
// Configuration (all setters are thread-safe)
|
||||
// =========================================================================
|
||||
|
||||
/// Set the minimum level. Entries below this level are dropped.
|
||||
/// Level::Disabled suppresses all output.
|
||||
void set_level(Level level) noexcept;
|
||||
[[nodiscard]] Level level() const noexcept;
|
||||
|
||||
/// Switch between Immediate and Buffered mode.
|
||||
/// If the buffer is non-empty when switching, it is flushed first.
|
||||
void set_mode(Mode mode) noexcept;
|
||||
[[nodiscard]] Mode mode() const noexcept;
|
||||
|
||||
/// Maximum number of entries held before an automatic flush
|
||||
/// (Buffered mode only).
|
||||
void set_buffer_capacity(std::size_t n) noexcept;
|
||||
[[nodiscard]] std::size_t buffer_capacity() const noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Flush
|
||||
// =========================================================================
|
||||
|
||||
/// Drain the buffer and deliver all pending entries via on_flush().
|
||||
/// No-op in Immediate mode. Thread-safe.
|
||||
void flush();
|
||||
|
||||
// =========================================================================
|
||||
// Scoped context
|
||||
// =========================================================================
|
||||
|
||||
/// Push a named scope onto this thread's scope stack AND emit a
|
||||
/// ScopeEnter entry at the given level. The returned ScopedContext
|
||||
/// emits a ScopeExit entry and pops the stack when it goes out of
|
||||
/// scope.
|
||||
///
|
||||
/// @param name Human-readable scope label.
|
||||
/// @param level Level used for the ScopeEnter/ScopeExit entries.
|
||||
/// Defaults to Trace so scope boundaries are usually
|
||||
/// invisible in production builds.
|
||||
/// @return A [[nodiscard]] RAII guard — assign it to a named
|
||||
/// local; do NOT discard (it would immediately exit).
|
||||
[[nodiscard]] ScopedContext
|
||||
push_scope(std::string name,
|
||||
Level level = Level::Trace,
|
||||
std::source_location loc =
|
||||
std::source_location::current()) noexcept;
|
||||
|
||||
/// Emit a named scope open/close pair as explicit log entries
|
||||
/// WITHOUT modifying the thread-local scope stack. Useful when you
|
||||
/// want scope boundaries in the log but don't want child entries
|
||||
/// annotated.
|
||||
///
|
||||
/// Both ScopeEnter and ScopeExit are emitted immediately (Immediate
|
||||
/// mode) or buffered together (Buffered mode).
|
||||
void scope(
|
||||
std::string_view name,
|
||||
Level level = Level::Trace,
|
||||
std::source_location loc = std::source_location::current());
|
||||
|
||||
/// Read-only view of the current thread's scope stack.
|
||||
/// Ordered outermost → innermost.
|
||||
[[nodiscard]] static std::span<const std::string>
|
||||
current_scopes() noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Preset factory
|
||||
// =========================================================================
|
||||
|
||||
/// Create a Preset that fixes the level and an optional message
|
||||
/// prefix. The Preset holds a non-owning reference to *this — do
|
||||
/// not outlive the logger.
|
||||
[[nodiscard]] Preset make_preset(Level level,
|
||||
std::string prefix = {}) noexcept;
|
||||
|
||||
// =========================================================================
|
||||
// Core (non-template) logging — canonical entry points
|
||||
// =========================================================================
|
||||
|
||||
void log(Level level,
|
||||
std::string_view message,
|
||||
std::source_location location =
|
||||
std::source_location::current());
|
||||
|
||||
void trace(
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
void debug(
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
void info(
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
void warning(
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
void error(
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
void fatal(
|
||||
std::string_view msg,
|
||||
std::source_location loc = std::source_location::current());
|
||||
|
||||
// =========================================================================
|
||||
// Formatted logging
|
||||
// =========================================================================
|
||||
|
||||
template <typename... Args>
|
||||
void log(Level level,
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...>
|
||||
fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(level,
|
||||
std::format(fwl.fmt, std::forward<Args>(args)...),
|
||||
fwl.location);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void trace(
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Trace, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void debug(
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Debug, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void info(
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Info, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void warning(
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Warning, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void error(
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Error, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename... Args>
|
||||
void fatal(
|
||||
Preset::FormatWithLocation<std::type_identity_t<Args>...> fwl,
|
||||
Args&&... args)
|
||||
{
|
||||
log(Level::Fatal, fwl, std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
protected:
|
||||
|
||||
// =========================================================================
|
||||
// Extension points
|
||||
//
|
||||
// Both methods are called OUTSIDE the internal mutex. Derived
|
||||
// classes may block, acquire their own locks, or call other Logger
|
||||
// methods without risk of deadlock.
|
||||
// =========================================================================
|
||||
|
||||
/// Deliver one entry to the sink.
|
||||
/// Called once per entry in Immediate mode, and by the default
|
||||
/// on_flush() for each entry in the batch.
|
||||
virtual void write(const Entry& entry) = 0;
|
||||
|
||||
/// Deliver a batch of buffered entries to the sink.
|
||||
/// The default implementation calls write() for each entry in
|
||||
/// order. Override to enable batched / vectored I/O.
|
||||
virtual void on_flush(std::span<const Entry> entries);
|
||||
|
||||
private:
|
||||
|
||||
/// Build an Entry and route it to write() or the buffer.
|
||||
void submit(Entry entry);
|
||||
|
||||
/// Emit a raw scope boundary entry; shared by push_scope and
|
||||
/// scope().
|
||||
void emit_scope_boundary(Kind kind,
|
||||
std::string_view name,
|
||||
Level level,
|
||||
std::source_location loc);
|
||||
|
||||
Level m_level{Level::Trace};
|
||||
Mode m_mode;
|
||||
std::size_t m_buffer_capacity;
|
||||
|
||||
mutable std::mutex m_mutex;
|
||||
std::vector<Entry> m_buffer;
|
||||
|
||||
/// Per-thread scope stack. ScopedContext pushes/pops into this.
|
||||
static thread_local std::vector<std::string> s_scope_stack;
|
||||
};
|
||||
|
||||
} // namespace Void::Logging
|
||||
@@ -0,0 +1 @@
|
||||
#pragma once
|
||||
Reference in new issue
Block a user