Files
Library/tests/standalone/Logging/FileLogger.cpp
T
faumarayandClaude Sonnet 4.6 4fc129fb7e 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>
2026-04-25 21:28:29 +03:00

428 lines
17 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <Void/Logging/Logger.hpp>
#include <chrono>
#include <filesystem>
#include <format>
#include <fstream>
#include <span>
#include <stdexcept>
#include <string>
#include <string_view>
namespace Example
{
class FileLogger final : public Void::Logging::Logger
{
public:
// -------------------------------------------------------------------------
// Construction / destruction
// -------------------------------------------------------------------------
/// @param path Path to the log file (created or appended to).
/// @param capacity Number of entries to buffer before
/// auto-flushing.
/// Defaults to 64 — tune to your I/O budget.
explicit FileLogger(const std::filesystem::path& path,
std::size_t capacity = 64)
: Logger(Void::Logging::Mode::Buffered, capacity),
m_file(path,
std::ios::app) // append so restarts don't truncate
{
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"FileLogger: cannot open '{}'", path.string()));
}
// Write a session separator so restarts are visible in the
// file.
m_file << "\n──────────────────────────────────────────────────"
"──────\n"
<< " Session started\n"
<< "────────────────────────────────────────────────────"
"────\n\n";
m_file.flush();
}
/// Flush remaining buffered entries before the file handle is
/// closed. IMPORTANT: always call flush() in the derived destructor
/// — the base destructor cannot call pure-virtual write() safely.
~FileLogger() noexcept override
{
flush(); // drains Logger's internal buffer → calls our
// on_flush()
// Write a closing marker so the file makes sense when tailed
// live.
if (m_file.is_open()) {
m_file << "\n──────────────────────────────────────────────"
"──────────\n"
<< " Session ended\n"
<< "────────────────────────────────────────────────"
"────────\n";
m_file.flush();
}
}
// Not copyable or movable (file handle + non-movable base).
FileLogger(const FileLogger&) = delete;
FileLogger& operator=(const FileLogger&) = delete;
FileLogger(FileLogger&&) = delete;
FileLogger& operator=(FileLogger&&) = delete;
protected:
// -------------------------------------------------------------------------
// on_flush — batch write (preferred path)
//
// Called by Logger when the buffer reaches capacity or flush() is
// called. All entries are formatted into a single std::string
// before writing so we minimise the number of write() syscalls.
// -------------------------------------------------------------------------
void
on_flush(std::span<const Void::Logging::Entry> entries) override
{
std::string batch;
batch.reserve(entries.size() * 120); // rough estimate per entry
for (const auto& entry : entries) {
format_entry(batch, entry);
}
m_file.write(batch.data(),
static_cast<std::streamsize>(batch.size()));
m_file.flush(); // ensure OS buffers are flushed to disk
}
// -------------------------------------------------------------------------
// write — single-entry path (Immediate mode, or base-class default
// on_flush falls back here — we override on_flush so this is only
// reached if someone calls set_mode(Immediate) at runtime).
// -------------------------------------------------------------------------
void write(const Void::Logging::Entry& entry) override
{
std::string line;
line.reserve(120);
format_entry(line, entry);
m_file.write(line.data(),
static_cast<std::streamsize>(line.size()));
m_file.flush();
}
private:
// -------------------------------------------------------------------------
// Formatting helpers
// -------------------------------------------------------------------------
/// Append one formatted entry to `out`.
static void format_entry(std::string& out,
const Void::Logging::Entry& e)
{
using Void::Logging::Kind;
switch (e.kind) {
case Kind::ScopeEnter:
format_scope_enter(out, e);
break;
case Kind::ScopeExit:
format_scope_exit(out, e);
break;
default:
format_message(out, e);
break;
}
}
/// "2025-06-01 14:32:00.123"
static std::string
format_timestamp(std::chrono::system_clock::time_point tp)
{
// Floor to milliseconds for readability.
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
tp.time_since_epoch()) %
1000;
auto tt = std::chrono::system_clock::to_time_t(tp);
std::tm tm{};
#if defined(_WIN32)
::localtime_s(&tm, &tt);
#else
::localtime_r(&tt, &tm);
#endif
return std::format("{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
tm.tm_hour, tm.tm_min, tm.tm_sec,
ms.count());
}
/// Build the indented scope prefix from entry.scopes.
/// Each nesting level adds two spaces.
static std::string scope_indent(const Void::Logging::Entry& e)
{
return std::string(e.scopes.size() * 2, ' ');
}
/// Regular message:
/// 2025-06-01 14:32:00.123 [INFO ] [network > tls] handshake
/// complete
static void format_message(std::string& out,
const Void::Logging::Entry& e)
{
// Scope breadcrumb, e.g. "[network > tls]"
std::string breadcrumb;
if (!e.scopes.empty()) {
breadcrumb = " [";
for (std::size_t i = 0; i < e.scopes.size(); ++i) {
if (i > 0) {
breadcrumb += " > ";
}
breadcrumb += e.scopes[i];
}
breadcrumb += ']';
}
std::format_to(std::back_inserter(out),
"{} [{:<7}]{}{} {}\n",
format_timestamp(e.timestamp),
Void::Logging::to_string(e.level),
breadcrumb,
scope_indent(e),
e.message);
}
/// Scope enter:
/// 2025-06-01 14:32:00.123 [TRACE ] ┌─ network
static void format_scope_enter(std::string& out,
const Void::Logging::Entry& e)
{
// The entering scope is already the last element of e.scopes.
// Parent indent = (depth - 1) levels.
std::size_t parent_depth =
e.scopes.size() > 0 ? e.scopes.size() - 1 : 0;
std::string indent(parent_depth * 2, ' ');
std::format_to(std::back_inserter(out),
"{} [{:<7}] {}┌─ {}\n",
format_timestamp(e.timestamp),
Void::Logging::to_string(e.level),
indent,
e.message);
}
/// Scope exit:
/// 2025-06-01 14:32:00.123 [TRACE ] └─ network
static void format_scope_exit(std::string& out,
const Void::Logging::Entry& e)
{
std::size_t parent_depth =
e.scopes.size() > 0 ? e.scopes.size() - 1 : 0;
std::string indent(parent_depth * 2, ' ');
std::format_to(std::back_inserter(out),
"{} [{:<7}] {}└─ {}\n",
format_timestamp(e.timestamp),
Void::Logging::to_string(e.level),
indent,
e.message);
}
// -------------------------------------------------------------------------
// Data
// -------------------------------------------------------------------------
std::ofstream m_file;
};
} // namespace Example
// =============================================================================
// main.cpp — FileLogger usage example
//
// Demonstrates:
// 1. Basic buffered file logging
// 2. push_scope() — RAII scope that annotates child entries AND emits
// ScopeEnter / ScopeExit boundary entries
// 3. scope() — lightweight marker pair (no stack mutation)
// 4. Nested scopes — entries carry the full breadcrumb automatically
// 5. Presets — bake in a level (and optional prefix), call with msg
// 6. Formatted log calls with std::format-style args
// 7. Level filtering — show how Debug entries are suppressed in production
// 8. Manual flush — force a write mid-session without waiting for the
// buffer to fill
//
// Expected output (app.log):
// ──────────────────────────────────────────────────────
// Session started
// ──────────────────────────────────────────────────────
//
// 2025-06-01 14:32:00.001 [INFO ] Application starting up (v2.3.1)
// 2025-06-01 14:32:00.002 [TRACE ] ┌─ network
// 2025-06-01 14:32:00.003 [INFO ] [network] Resolving host: api.example.com
// 2025-06-01 14:32:00.004 [DEBUG ] [network] Raw IP: 93.184.216.34
// 2025-06-01 14:32:00.005 [TRACE ] ┌─ tls
// 2025-06-01 14:32:00.006 [DEBUG ] [network > tls] Cipher:
// TLS_AES_256_GCM_SHA384 2025-06-01 14:32:00.007 [INFO ] [network > tls]
// Handshake complete 2025-06-01 14:32:00.008 [TRACE ] └─ tls 2025-06-01
// 14:32:00.009 [INFO ] [network] Connected — 42 ms 2025-06-01 14:32:00.010
// [TRACE ] └─ network 2025-06-01 14:32:00.011 [TRACE ] ┌─ render 2025-06-01
// 14:32:00.012 [TRACE ] └─ render 2025-06-01 14:32:00.013 [INFO ] All
// systems nominal 2025-06-01 14:32:00.014 [ERROR ] [db] Query failed: timeout
// after 5000 ms 2025-06-01 14:32:00.015 [WARN ] [db] Retrying (attempt 2 of
// 3) 2025-06-01 14:32:00.016 [FATAL ] [db] Unrecoverable: connection pool
// exhausted
//
// ──────────────────────────────────────────────────────
// Session ended
// ──────────────────────────────────────────────────────
// =============================================================================
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <string>
#include <thread>
// ---------------------------------------------------------------------------
// Simulated subsystem functions — each receives the logger by reference.
// Real code would inject it via a constructor or service locator.
// ---------------------------------------------------------------------------
/// Simulates a TLS handshake — demonstrates a nested scope.
void do_tls_handshake(Void::Logging::Logger& log)
{
// push_scope: "tls" is pushed onto the thread-local stack.
// All entries logged inside this block carry scopes = {"network", "tls"}.
// A ScopeEnter entry is emitted here; ScopeExit fires on scope destruction.
auto tls_scope = log.push_scope("tls", Void::Logging::Level::Trace);
log.debug("Cipher: TLS_AES_256_GCM_SHA384");
log.info("Handshake complete");
// ← ScopeExit "tls" emitted here automatically
}
/// Simulates a network connection — demonstrates scope with a nested call.
void connect(Void::Logging::Logger& log, std::string_view host)
{
// Outer RAII scope — annotates every entry logged inside this function
// and inside any function called from here (e.g. do_tls_handshake).
auto net_scope = log.push_scope("network", Void::Logging::Level::Trace);
log.info("Resolving host: {}", host);
log.debug("Raw IP: 93.184.216.34");
do_tls_handshake(log);
// Pretend the connection took 42 ms.
log.info("Connected — 42 ms");
// ← ScopeExit "network" emitted here automatically
}
/// Simulates a render pass — demonstrates the lightweight scope() call.
/// scope() emits ScopeEnter+ScopeExit immediately but does NOT push onto the
/// scope stack, so entries inside the block are NOT annotated with a
/// breadcrumb. Use this when you only want visual delimiters in the log, not
/// full annotation.
void render_frame(Void::Logging::Logger& log)
{
// Emits "┌─ render" then "└─ render" immediately — no stack change.
log.scope("render", Void::Logging::Level::Trace);
// This entry has no scope breadcrumb because the stack was not modified.
// (Uncomment to observe the difference vs push_scope.)
// log.debug("Drawing {} triangles", 14'200);
}
/// Simulates a database subsystem — demonstrates Preset usage.
void database_operations(Void::Logging::Logger& log)
{
// Presets bake in the level (and an optional prefix string).
// Useful when a subsystem always logs at the same level, or when you want
// a consistent tag without scoping the stack.
auto db_err = log.make_preset(Void::Logging::Level::Error, "[db] ");
auto db_warn = log.make_preset(Void::Logging::Level::Warning, "[db] ");
auto db_fatal = log.make_preset(Void::Logging::Level::Fatal, "[db] ");
// Call exactly like a function — source location captured transparently.
db_err("Query failed: timeout after {} ms", 5000);
db_warn("Retrying (attempt {} of {})", 2, 3);
db_fatal("Unrecoverable: connection pool exhausted");
}
// ---------------------------------------------------------------------------
// main
// ---------------------------------------------------------------------------
int main()
{
// -----------------------------------------------------------------------
// 1. Construct the logger
// Mode::Buffered with capacity=8 means entries are held until 8 have
// accumulated, then the whole batch is written to disk at once.
// A capacity of 8 is tiny — chosen here so the auto-flush triggers
// visibly during the example. Real code would use 64–512.
// -----------------------------------------------------------------------
Example::FileLogger log("app.log", /*capacity=*/8);
// -----------------------------------------------------------------------
// 2. Set the minimum level.
// Level::Debug — Debug + Info + Warning + Error + Fatal are written.
// Level::Trace entries (scope boundaries) are written too because the
// default is Trace; if you raise this to Info, scope markers disappear.
// -----------------------------------------------------------------------
log.set_level(Void::Logging::Level::Trace);
// -----------------------------------------------------------------------
// 3. Plain log calls — no scope, no format args
// -----------------------------------------------------------------------
log.info("Application starting up (v2.3.1)");
// -----------------------------------------------------------------------
// 4. RAII scopes with nested child scope
// connect() pushes "network"; inside it do_tls_handshake() pushes
// "tls". Every entry logged inside those functions carries the
// breadcrumb automatically — no extra work at the call site.
// -----------------------------------------------------------------------
connect(log, "api.example.com");
// -----------------------------------------------------------------------
// 5. Lightweight scope marker (no stack mutation)
// render_frame() calls log.scope("render") which emits Enter+Exit
// immediately. Entries inside the function body are NOT annotated.
// -----------------------------------------------------------------------
render_frame(log);
// -----------------------------------------------------------------------
// 6. Manual flush — useful after a critical startup phase to ensure the
// log is on disk before entering the main loop.
// -----------------------------------------------------------------------
log.flush();
// -----------------------------------------------------------------------
// 7. Info after the flush — will go into a fresh buffer.
// -----------------------------------------------------------------------
log.info("All systems nominal");
// -----------------------------------------------------------------------
// 8. Presets — fixed level + prefix, variable message
// -----------------------------------------------------------------------
database_operations(log);
// -----------------------------------------------------------------------
// 9. Level filtering demo (commented out by default)
//
// Raise the level to Info — subsequent Debug/Trace calls are dropped
// before they even enter the buffer.
// -----------------------------------------------------------------------
// log.set_level(Void::Logging::Level::Info);
// log.debug("This will be silently dropped");
// log.info("But this will appear");
// -----------------------------------------------------------------------
// 10. FileLogger destructor calls flush() — remaining buffered entries
// are written to disk here before the file handle closes.
// -----------------------------------------------------------------------
std::cout << "Done. Check app.log.\n";
return EXIT_SUCCESS;
}