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

401 lines
11 KiB
C++

#pragma once
#include <atomic>
#include <concepts>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <format>
#include <functional>
#include <memory>
#include <mutex>
#include <shared_mutex>
#include <source_location>
#include <string>
#include <string_view>
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
// ── Void::Log — the emission facade
// ─────────────────────────────────────────── Header-only apart from its
// state, which Void::LogState (a small library with no dependencies) holds
// once per process, so every module (including INTERFACE libraries) can log by
// linking only that. The full sink framework lives in Void::Logging
// (Logger.hpp); bridge with Void/Log/LoggingAdapter.hpp.
namespace Void::Log
{
enum class Level : unsigned char {
Trace = 0,
Debug,
Info,
Warning,
Error,
Fatal,
Disabled
};
/// Signature for any log consumer.
using Sink =
std::function<void(Level level, std::string_view module,
std::string_view message,
const std::source_location& location)>;
using RegistrationId = std::uint64_t;
enum class DrainResult : std::uint8_t {
drained = 0,
not_found,
would_deadlock
};
using EmergencyHandler = void (*)(std::string_view message) noexcept;
namespace Detail
{
template <typename... Args> struct FmtLoc {
std::format_string<Args...> fmt;
std::source_location location;
template <std::convertible_to<std::string_view> T>
consteval FmtLoc(T&& f,
std::source_location loc =
std::source_location::current())
: fmt(std::forward<T>(f)), location(loc)
{
}
};
struct SinkRegistration {
RegistrationId id{0};
Sink sink{};
std::shared_ptr<const void> owner{};
std::atomic<bool> detached{false};
std::atomic<std::size_t> active_calls{0};
std::mutex drain_mutex;
std::condition_variable drain_cv;
};
struct State {
// Fast-path gates (checked before any locking or formatting).
std::atomic<bool> has_sink{false};
std::atomic<Level> min_level{Level::Trace};
std::atomic<bool> has_module_levels{false};
std::atomic<std::uint64_t> reentrant_dropped{0};
std::atomic<EmergencyHandler> emergency_handler{nullptr};
// Slow path (registration is immutable after creation;
// invoked and destroyed strictly outside `mutex`).
std::shared_ptr<SinkRegistration> registration{};
RegistrationId next_id{0};
std::unordered_map<RegistrationId, std::weak_ptr<SinkRegistration>> known;
std::unordered_map<std::string, Level> module_levels;
std::shared_mutex mutex;
};
inline constexpr std::size_t kMaxNestedFacadeSinks = 8;
// Process-wide singleton accessors defined in Void::LogState.
State& state();
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept;
struct ActiveRegistrationGuard {
std::shared_ptr<SinkRegistration> reg;
std::vector<const SinkRegistration*>& stack;
ActiveRegistrationGuard(std::shared_ptr<SinkRegistration> r,
std::vector<const SinkRegistration*>& st)
: reg(std::move(r)), stack(st)
{
stack.push_back(reg.get());
}
~ActiveRegistrationGuard() noexcept
{
if (!stack.empty()) {
stack.pop_back();
}
if (reg->active_calls.fetch_sub(
1, std::memory_order_acq_rel) == 1) {
std::lock_guard lock{reg->drain_mutex};
reg->drain_cv.notify_all();
}
}
ActiveRegistrationGuard(const ActiveRegistrationGuard&) = delete;
ActiveRegistrationGuard&
operator=(const ActiveRegistrationGuard&) = delete;
};
} // namespace Detail
/// Install a sink alongside an optional lifetime-keepalive owner and return
/// its registration ID for explicit detach_and_drain().
inline RegistrationId
register_sink(Sink sink, std::shared_ptr<const void> owner = {})
{
auto& s = Detail::state();
std::shared_ptr<Detail::SinkRegistration> prev;
RegistrationId id = 0;
if (sink) {
auto next = std::make_shared<Detail::SinkRegistration>();
next->sink = std::move(sink);
next->owner = std::move(owner);
std::unique_lock lock{s.mutex};
id = ++s.next_id;
next->id = id;
s.known.emplace(id, next);
for (auto it = s.known.begin(); it != s.known.end();) {
if (it->second.expired()) {
it = s.known.erase(it);
} else {
++it;
}
}
prev = std::exchange(s.registration, std::move(next));
if (prev) {
prev->detached.store(true, std::memory_order_release);
}
s.has_sink.store(true, std::memory_order_release);
} else {
std::unique_lock lock{s.mutex};
prev = std::exchange(s.registration, nullptr);
if (prev) {
prev->detached.store(true, std::memory_order_release);
}
s.has_sink.store(false, std::memory_order_release);
}
// Destroy previous callback/owner outside s.mutex.
prev.reset();
return id;
}
/// Install the global sink. Any previously installed sink is replaced
/// outside the facade lock (does not block waiting for in-flight calls).
inline void set_sink(Sink sink)
{
(void)register_sink(std::move(sink), {});
}
/// Detach a registered sink (or active sink when id == 0) and wait until
/// all already-admitted invocations using that registration complete.
/// Returns would_deadlock if called synchronously from that registration's
/// own active callback.
[[nodiscard]] inline DrainResult detach_and_drain(RegistrationId id = 0)
{
auto& s = Detail::state();
std::shared_ptr<Detail::SinkRegistration> target;
{
std::unique_lock lock{s.mutex};
if (id == 0) {
target = s.registration;
} else if (s.registration && s.registration->id == id) {
target = s.registration;
} else if (const auto it = s.known.find(id); it != s.known.end()) {
target = it->second.lock();
}
if (!target) {
return DrainResult::not_found;
}
const auto& active = Detail::active_registrations_tls();
for (const auto* entry : active) {
if (entry == target.get()) {
return DrainResult::would_deadlock;
}
}
target->detached.store(true, std::memory_order_release);
if (target == s.registration) {
s.registration.reset();
s.has_sink.store(false, std::memory_order_release);
}
s.known.erase(target->id);
}
{
std::unique_lock drain_lock{target->drain_mutex};
target->drain_cv.wait(drain_lock, [&target] {
return target->active_calls.load(std::memory_order_acquire) == 0;
});
}
target.reset();
return DrainResult::drained;
}
[[nodiscard]] inline std::uint64_t reentrant_dropped() noexcept
{
return Detail::state().reentrant_dropped.load(std::memory_order_relaxed);
}
inline void set_emergency_handler(EmergencyHandler handler) noexcept
{
Detail::state().emergency_handler.store(
handler, std::memory_order_release);
}
inline void set_min_level(Level level) noexcept
{
Detail::state().min_level.store(level, std::memory_order_relaxed);
}
[[nodiscard]] inline Level min_level() noexcept
{
return Detail::state().min_level.load(std::memory_order_relaxed);
}
inline void set_module_level(std::string_view module, Level level)
{
auto& s = Detail::state();
std::unique_lock lock{s.mutex};
s.module_levels.insert_or_assign(std::string{module}, level);
s.has_module_levels.store(true, std::memory_order_release);
}
inline void clear_module_level(std::string_view module)
{
auto& s = Detail::state();
std::unique_lock lock{s.mutex};
s.module_levels.erase(std::string{module});
s.has_module_levels.store(!s.module_levels.empty(),
std::memory_order_release);
}
[[nodiscard]] inline bool enabled(Level level, std::string_view module)
{
auto& s = Detail::state();
if (!s.has_sink.load(std::memory_order_relaxed)) {
return false;
}
if (level == Level::Disabled) {
return false;
}
if (s.has_module_levels.load(std::memory_order_acquire)) {
std::shared_lock lock{s.mutex};
if (auto it = s.module_levels.find(std::string{module});
it != s.module_levels.end()) {
return level >= it->second;
}
}
return level >= s.min_level.load(std::memory_order_relaxed);
}
namespace Detail
{
inline void emit(Level level, std::string_view module,
std::string_view message,
const std::source_location& location)
{
auto& s = state();
if (!::Void::Log::enabled(level, module)) {
return;
}
std::shared_ptr<SinkRegistration> reg;
bool reentrant = false;
{
std::shared_lock lock{s.mutex};
reg = s.registration;
if (!reg || reg->detached.load(std::memory_order_acquire) ||
!reg->sink) {
return;
}
const auto& active = active_registrations_tls();
if (active.size() >= kMaxNestedFacadeSinks) {
reentrant = true;
} else {
for (const auto* entry : active) {
if (entry == reg.get()) {
reentrant = true;
break;
}
}
}
if (!reentrant) {
reg->active_calls.fetch_add(1, std::memory_order_acq_rel);
}
}
if (reentrant) {
s.reentrant_dropped.fetch_add(1, std::memory_order_relaxed);
if (const auto eh =
s.emergency_handler.load(std::memory_order_acquire);
eh != nullptr) {
eh(message);
}
return;
}
ActiveRegistrationGuard guard{
std::move(reg), active_registrations_tls()};
guard.reg->sink(level, module, message, location);
}
} // namespace Detail
inline void log(Level level, std::string_view module,
std::string_view message,
const std::source_location& location =
std::source_location::current())
{
Detail::emit(level, module, message, location);
}
template <typename... Args>
void log(Level level, std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
if (!enabled(level, module)) {
return;
}
Detail::emit(level, module,
std::format(fmt.fmt, std::forward<Args>(args)...),
fmt.location);
}
template <typename... Args>
void trace(std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
log(Level::Trace, module, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void debug(std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
log(Level::Debug, module, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void info(std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
log(Level::Info, module, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void warn(std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
log(Level::Warning, module, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void error(std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
log(Level::Error, module, fmt, std::forward<Args>(args)...);
}
template <typename... Args>
void fatal(std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
{
log(Level::Fatal, module, fmt, std::forward<Args>(args)...);
}
} // namespace Void::Log