Files
Library/include/Void/Log/Logger.hpp
T

559 lines
15 KiB
C++

#pragma once
#include "Void/Log/Field.hpp"
#include <Void/Async/Detail/Types.hpp>
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Log/Entry.hpp>
#include <Void/Log/Level.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <deque>
#include <format>
#include <functional>
#include <mutex>
#include <optional>
#include <set>
#include <source_location>
#include <span>
#include <string>
#include <string_view>
#include <thread>
#include <type_traits>
#include <vector>
namespace Void::Logging
{
enum class Mode { Async, Immediate, Buffered };
enum class OverflowPolicy { Block, DropNewest, DropOldest };
enum class LogErrorCode : std::int32_t {
invalid_argument = 1,
queue_full = 2,
entry_too_large = 3,
closed = 4,
cancelled = 5,
timeout = 6,
would_deadlock = 7,
quarantined = 8,
unsupported_capability = 9,
io_error = 10,
cycle_detected = 11
};
[[nodiscard]] inline Void::Result::Error
make_log_error(LogErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case LogErrorCode::invalid_argument:
case LogErrorCode::entry_too_large:
kind = ErrorKind::invalid_argument;
break;
case LogErrorCode::queue_full:
kind = ErrorKind::overloaded;
break;
case LogErrorCode::closed:
case LogErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case LogErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case LogErrorCode::would_deadlock:
case LogErrorCode::cycle_detected:
kind = ErrorKind::conflict;
break;
case LogErrorCode::quarantined:
kind = ErrorKind::internal;
break;
case LogErrorCode::unsupported_capability:
kind = ErrorKind::unsupported;
break;
case LogErrorCode::io_error:
kind = ErrorKind::io;
break;
}
return Error{kind,
std::move(message),
ErrorCode{Void::Result::kLogErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct DeliveryLimits {
std::size_t entries = 4096;
std::size_t owned_bytes = 8ULL * 1024ULL * 1024ULL;
std::size_t max_entry_bytes = 64ULL * 1024ULL;
std::size_t batch_entries = 128;
std::size_t batch_bytes = 256ULL * 1024ULL;
std::size_t max_fields = 32;
std::size_t max_scopes = 16;
std::size_t max_field_key_bytes = 256;
std::size_t max_field_value_bytes = 2048;
std::size_t max_format_scratch_bytes = 1024ULL * 1024ULL;
bool truncate_oversize = false;
[[nodiscard]] Void::Result::Result<void> validate() const;
};
enum class FailurePolicy : std::uint8_t {
Quarantine = 0,
Continue
};
struct LoggerOptions {
Mode mode = Mode::Async;
OverflowPolicy policy = OverflowPolicy::DropNewest;
DeliveryLimits limits{};
FailurePolicy failure_policy = FailurePolicy::Quarantine;
bool suppress_reentrancy = true;
const Void::Time::MonotonicClock* clock =
&Void::Time::SystemMonotonicClock::instance();
};
enum class SubmitState : std::uint8_t {
Accepted = 0,
Filtered,
Dropped,
Closed
};
using Ticket = std::uint64_t;
struct SubmitReceipt {
SubmitState state{SubmitState::Dropped};
std::optional<Ticket> ticket{};
bool truncated{false};
};
enum class FlushDurability : std::uint8_t {
BufferFlush = 0,
SyncFiles
};
struct FlushOptions {
FlushDurability durability = FlushDurability::BufferFlush;
Void::Async::OperationOptions async{};
};
struct CloseOptions {
bool drop_pending = false;
Void::Async::OperationOptions async{};
};
struct FlushReport {
std::uint64_t delivered{0};
std::uint64_t dropped{0};
std::uint64_t failed{0};
Ticket watermark{0};
bool timed_out{false};
bool cancelled{false};
};
struct LoggerStats {
std::size_t queued_entries{0};
std::size_t queued_bytes{0};
std::size_t in_flight_entries{0};
std::size_t in_flight_bytes{0};
std::uint64_t admitted{0};
std::uint64_t delivered{0};
std::uint64_t dropped{0};
std::uint64_t failed{0};
std::uint64_t reentrant_dropped{0};
Ticket completed_watermark{0};
bool quarantined{false};
bool closed{false};
};
/// Abstract base class for all Void loggers with bounded entry/byte
/// admission, ticket completion watermarks, failure quarantine, and flush
/// durability controls.
class Logger
{
public:
class ScopedContext
{
public:
explicit ScopedContext(Logger& owner,
std::string name,
Level level,
std::source_location loc) noexcept;
~ScopedContext() noexcept;
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};
};
class Preset
{
public:
Preset(Logger& owner, Level level,
std::string prefix = {}) noexcept
: m_owner(&owner), m_level(level),
m_prefix(std::move(prefix))
{
}
Preset(const Preset&) = default;
Preset& operator=(const Preset&) = default;
Preset(Preset&&) = default;
Preset& operator=(Preset&&) = default;
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);
}
}
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)
{
}
};
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);
}
[[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::Async,
std::size_t capacity = 512,
OverflowPolicy policy = OverflowPolicy::Block) noexcept;
explicit Logger(LoggerOptions options);
virtual ~Logger() noexcept;
Logger(const Logger&) = delete;
Logger& operator=(const Logger&) = delete;
Logger(Logger&&) = delete;
Logger& operator=(Logger&&) = delete;
// =========================================================================
// Configuration
// =========================================================================
void set_level(Level level) noexcept;
[[nodiscard]] Level level() const noexcept;
void set_mode(Mode mode) noexcept;
[[nodiscard]] Mode mode() const noexcept;
void set_buffer_capacity(std::size_t n) noexcept;
[[nodiscard]] std::size_t buffer_capacity() const noexcept;
[[nodiscard]] OverflowPolicy overflow_policy() const noexcept;
[[nodiscard]] const DeliveryLimits& delivery_limits() const noexcept
{
return m_options.limits;
}
// =========================================================================
// P2 Checked Submission, Flush, Close, and Quarantine Controls
// =========================================================================
[[nodiscard]] Void::Result::Result<SubmitReceipt>
try_submit(Entry entry,
Void::Async::OperationOptions options = {});
[[nodiscard]] Void::Result::Result<FlushReport>
flush_through(Ticket target = 0, FlushOptions options = {});
[[nodiscard]] Void::Result::Result<FlushReport>
close(CloseOptions options = {});
void request_close() noexcept;
virtual void flush();
[[nodiscard]] LoggerStats stats() const;
[[nodiscard]] bool is_quarantined() const noexcept;
[[nodiscard]] std::string last_error_summary() const;
void reset_quarantine() noexcept;
// =========================================================================
// Scoped context & Presets
// =========================================================================
[[nodiscard]] ScopedContext
push_scope(std::string name,
Level level = Level::Trace,
std::source_location loc =
std::source_location::current()) noexcept;
void scope(
std::string_view name,
Level level = Level::Trace,
std::source_location loc = std::source_location::current());
[[nodiscard]] static std::span<const std::string>
current_scopes() noexcept;
[[nodiscard]] Preset make_preset(Level level,
std::string prefix = {}) noexcept;
// =========================================================================
// Core & Formatted Logging (legacy compatibility adapters)
// =========================================================================
inline void log(
Level level, std::string_view message,
std::source_location location = std::source_location::current())
{
if (level < m_level.load(std::memory_order_relaxed)) {
return;
}
const auto fields = current_fields();
Entry entry{
.kind = Kind::Message,
.level = level,
.message = std::string(message),
.timestamp = std::chrono::system_clock::now(),
.location = location,
.thread_id = std::this_thread::get_id(),
.scopes = [] {
const auto scopes = Logger::current_scopes();
return std::vector<std::string>(
scopes.begin(), scopes.end());
}(),
.fields = {fields.begin(), fields.end()},
};
(void)try_submit(std::move(entry));
}
void relay(Entry entry);
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());
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)...);
}
[[nodiscard]] virtual Void::Result::Result<void> sync_files();
protected:
virtual void write(const Entry& entry) = 0;
virtual void on_flush(std::span<const Entry> entries);
private:
enum class TerminalOutcome : std::uint8_t {
Delivered = 0,
Dropped,
Failed
};
struct QueuedItem {
Ticket ticket{0};
std::size_t bytes{0};
Entry entry;
};
[[nodiscard]] static std::size_t
estimate_entry_bytes(const Entry& entry) noexcept;
[[nodiscard]] Void::Result::Result<void>
prepare_entry(Entry& entry) const;
void start_worker();
void worker_loop();
void mark_terminal_locked(Ticket t, TerminalOutcome outcome);
void advance_watermark_locked();
void deliver_batch_unlocked(
std::vector<QueuedItem>& items,
bool stopping,
std::size_t total_bytes);
void emit_scope_boundary(Kind kind,
std::string_view name,
Level level,
std::source_location loc);
[[nodiscard]] bool is_active_logger_on_thread() const noexcept;
std::atomic<Level> m_level{Level::Trace};
std::atomic<Mode> m_mode;
LoggerOptions m_options;
std::size_t m_buffer_capacity;
mutable std::mutex m_mutex;
std::condition_variable m_work_cv;
std::condition_variable m_space_cv;
std::condition_variable m_done_cv;
std::deque<QueuedItem> m_queue;
std::size_t m_queued_entries{0};
std::size_t m_queued_bytes{0};
std::size_t m_in_flight_entries{0};
std::size_t m_in_flight_bytes{0};
Ticket m_next_ticket{0};
Ticket m_completed_watermark{0};
std::set<std::pair<Ticket, TerminalOutcome>> m_pending_terminals;
std::uint64_t m_admitted_count{0};
std::uint64_t m_delivered_count{0};
std::uint64_t m_dropped_count{0};
std::uint64_t m_failed_count{0};
std::uint64_t m_wm_delivered{0};
std::uint64_t m_wm_dropped{0};
std::uint64_t m_wm_failed{0};
std::atomic<std::uint64_t> m_reentrant_dropped{0};
bool m_mode_changing{false};
bool m_stop_admission{false};
bool m_closed{false};
std::atomic<bool> m_stop_worker{false};
std::atomic<bool> m_quarantined{false};
std::string m_last_error;
std::atomic<bool> m_worker_started{false};
std::once_flag m_worker_once;
std::thread m_worker;
std::atomic<std::thread::id> m_worker_id{};
static thread_local std::vector<std::string> s_scope_stack;
};
} // namespace Void::Logging