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:
faumarayandClaude Sonnet 4.6 committed 2026-04-25 21:28:29 +03:00
commit 4fc129fb7e
17 files changed
+1910

No files matched your search

+272
View File
@@ -0,0 +1,272 @@
---
BasedOnStyle: LLVM
AccessModifierOffset: 0
AlignAfterOpenBracket: Align
AlignArrayOfStructures: None
AlignConsecutiveAssignments:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: true
AlignConsecutiveBitFields:
Enabled: true
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveDeclarations:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveMacros:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveShortCaseStatements:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCaseArrows: false
AlignCaseColons: false
AlignConsecutiveTableGenBreakingDAGArgColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenCondOperatorColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignConsecutiveTableGenDefinitionColons:
Enabled: false
AcrossEmptyLines: false
AcrossComments: false
AlignCompound: false
AlignFunctionPointers: false
PadOperators: false
AlignEscapedNewlines: Right
AlignOperands: Align
AlignTrailingComments:
Kind: Always
OverEmptyLines: 0
AllowAllArgumentsOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowBreakBeforeNoexceptSpecifier: Never
AllowShortBlocksOnASingleLine: Never
AllowShortCaseExpressionOnASingleLine: true
AllowShortCaseLabelsOnASingleLine: false
AllowShortCompoundRequirementOnASingleLine: true
AllowShortEnumsOnASingleLine: true
AllowShortFunctionsOnASingleLine: All
AllowShortIfStatementsOnASingleLine: Never
AllowShortLambdasOnASingleLine: All
AllowShortLoopsOnASingleLine: false
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AttributeMacros:
- __capability
BinPackArguments: true
BinPackParameters: true
BitFieldColonSpacing: Both
BraceWrapping:
AfterCaseLabel: true
AfterClass: true
AfterControlStatement: Never
AfterEnum: false
AfterFunction: true
AfterNamespace: true
AfterObjCDeclaration: false
AfterStruct: true
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: true
BeforeLambdaBody: true
BeforeWhile: true
IndentBraces: true
SplitEmptyFunction: true
SplitEmptyRecord: true
SplitEmptyNamespace: true
BreakAdjacentStringLiterals: true
BreakAfterAttributes: Leave
BreakAfterJavaFieldAnnotations: false
BreakAfterReturnType: None
BreakArrays: true
BreakBeforeBinaryOperators: None
BreakBeforeBraces: Linux
BreakBeforeConceptDeclarations: Always
BreakBeforeInlineASMColon: OnlyMultiline
BreakBeforeTernaryOperators: true
BreakConstructorInitializers: BeforeColon
BreakFunctionDefinitionParameters: false
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
BreakTemplateDeclarations: MultiLine
ColumnLimit: 80
CommentPragmas: ""
CompactNamespaces: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: true
DerivePointerAlignment: true
DisableFormat: false
EmptyLineAfterAccessModifier: Always
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: true
FixNamespaceComments: true
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Preserve
IncludeCategories:
- Regex: ^"(llvm|llvm-c|clang|clang-c)/
Priority: 2
SortPriority: 0
CaseSensitive: true
- Regex: ^(<|"(gtest|gmock|isl|json)/)
Priority: 3
SortPriority: 0
CaseSensitive: true
- Regex: .*
Priority: 1
SortPriority: 0
CaseSensitive: true
IncludeIsMainRegex: (Test)?$
IncludeIsMainSourceRegex: ""
IndentAccessModifiers: true
IndentCaseBlocks: true
IndentCaseLabels: true
IndentExternBlock: AfterExternBlock
IndentGotoLabels: true
IndentPPDirectives: None
IndentRequiresClause: true
IndentWidth: 4
IndentWrappedFunctionNames: true
InsertBraces: true
InsertNewlineAtEOF: true
InsertTrailingCommas: None
IntegerLiteralSeparator:
Binary: 0
BinaryMinDigits: 0
Decimal: 0
DecimalMinDigits: 0
Hex: 0
HexMinDigits: 0
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLines:
AtEndOfFile: false
AtStartOfBlock: true
AtStartOfFile: true
LambdaBodyIndentation: Signature
LineEnding: DeriveLF
MacroBlockBegin: ""
MacroBlockEnd: ""
MainIncludeChar: AngleBracket
MaxEmptyLinesToKeep: 1
NamespaceIndentation: All
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 2
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PPIndentWidth: -1
PackConstructorInitializers: BinPack
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakOpenParenthesis: 0
PenaltyBreakScopeResolution: 500
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyIndentedWhitespace: 0
PenaltyReturnTypeOnItsOwnLine: 60
PointerAlignment: Right
QualifierAlignment: Leave
ReferenceAlignment: Pointer
ReflowComments: true
RemoveBracesLLVM: false
RemoveParentheses: Leave
RemoveSemicolon: false
RequiresClausePosition: OwnLine
RequiresExpressionIndentation: OuterScope
SeparateDefinitionBlocks: Leave
ShortNamespaceLines: 1
SkipMacroDefinitionBody: false
SortIncludes: CaseSensitive
SortJavaStaticImport: Before
SortUsingDeclarations: LexicographicNumeric
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: true
SpaceAroundPointerQualifiers: Default
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: false
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeJsonColon: false
SpaceBeforeParens: ControlStatements
SpaceBeforeParensOptions:
AfterControlStatements: true
AfterForeachMacros: true
AfterFunctionDeclarationName: false
AfterFunctionDefinitionName: false
AfterIfMacros: true
AfterOverloadedOperator: false
AfterPlacementOperator: true
AfterRequiresInClause: false
AfterRequiresInExpression: false
BeforeNonEmptyParentheses: false
SpaceBeforeRangeBasedForLoopColon: true
SpaceBeforeSquareBrackets: false
SpaceInEmptyBlock: false
SpacesBeforeTrailingComments: 1
SpacesInAngles: Never
SpacesInContainerLiterals: true
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParens: Never
SpacesInParensOptions:
ExceptDoubleParentheses: false
InConditionalStatements: false
InCStyleCasts: false
InEmptyParentheses: false
Other: false
SpacesInSquareBrackets: false
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 4
TableGenBreakInsideDAGArg: DontBreak
UseTab: Always
VerilogBreakBetweenInstancePorts: true
WhitespaceSensitiveMacros:
- BOOST_PP_STRINGIZE
- CF_SWIFT_NAME
- NS_SWIFT_NAME
- PP_STRINGIZE
- STRINGIZE
+1
View File
@@ -0,0 +1 @@
build
+71
View File
@@ -0,0 +1,71 @@
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Build
```bash
# Configure (clang++, Ninja, Debug)
cmake -B build -S . -G Ninja -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_BUILD_TYPE=Debug
# Build
cmake --build build
# Run all tests
ctest --test-dir build
# Run a single standalone test binary directly
./build/tests/test_standalone_Logging_FileLogger
```
Format code with:
```bash
clang-format -i <file>
```
## Architecture
VoidLibrary is a C++23 modular shared library. Each module is an independently installable CMake target under the `Void::` namespace.
### Module system
`cmake/Module.cmake` defines `void_add_module(NAME ...)`. The root `CMakeLists.txt` auto-discovers every subdirectory under `src/` and calls it. A module with only headers becomes an `INTERFACE` library; one with `.cpp` sources becomes a `SHARED` library.
Module layout:
- Headers: `include/Void/<ModuleName>/*.hpp`
- Sources: `src/<ModuleName>/*.cpp`
- CMake target: `Void_<ModuleName>` with alias `Void::<ModuleName>`
- Namespace: `Void::<ModuleName>`
To add a new module, create `src/<ModuleName>/` and populate it — the build system picks it up automatically. If a module needs special dependency wiring, drop a `module.cmake` file inside the source directory (see `cmake/module.cmake.template` for the pattern).
External dependencies are fetched via `cmake/Dependencies.cmake` using `FetchContent`; add new ones there and reference them via `EXTERNAL_DEPS` in `void_add_module`.
### Tests
`tests/CMakeLists.txt` defines two test categories:
| Category | Location | Binary | Links |
|---|---|---|---|
| Internal (kitchen-sink) | `tests/internal/*.cpp` | `VoidInternalTests` | all modules + `Void::Testing` |
| Standalone (isolated) | `tests/standalone/<ModuleName>/<name>.cpp` | `test_standalone_<ModuleName>_<name>` | its module only |
Standalone tests are preferred for testing a single module in isolation.
### Logging module
`Void::Logging::Logger` is an abstract base class. Derive from it to create a sink:
1. **Override `write(const Entry&)`** — called per-entry in Immediate mode and by the default `on_flush` fallback.
2. **Optionally override `on_flush(std::span<const Entry>)`** — for batch/vectored I/O (e.g. file sinks).
3. **Call `flush()` in your derived destructor** — the base destructor does not flush because calling a pure virtual from `~Logger` is UB. Any unflushed entries remaining after your destructor are silently dropped.
Key design points:
- Virtual extension points (`write`, `on_flush`) are called **outside** the internal mutex, so derived classes can do blocking I/O or acquire their own locks freely.
- `Level::Disabled` suppresses all output. Levels are ordered: `Trace < Debug < Info < Warning < Error < Fatal`.
- `push_scope(name)` returns a `[[nodiscard]]` RAII `ScopedContext` that emits `ScopeEnter`/`ScopeExit` entries and annotates all entries logged in that thread with a breadcrumb. `scope(name)` emits the boundary pair immediately without touching the scope stack.
- `make_preset(level, prefix)` returns a `Preset` — a non-owning callable that bakes in a level and optional prefix. Presets must not outlive their logger.
## Code style
Enforced by `.clang-format` (LLVM-based): 4-space indent (tabs), 80-column limit, Linux brace wrapping style, pointer alignment right.
+56
View File
@@ -0,0 +1,56 @@
cmake_minimum_required(VERSION 4.0.0)
project(Void VERSION 1.0.0 LANGUAGES CXX)
option(VOID_ENABLE_TESTING "Build the test suite" ON)
set(CMAKE_CXX_STANDARD 23)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include(GNUInstallDirs)
include(CMakePackageConfigHelpers)
set(EXPORT_SET_NAME ${PROJECT_NAME}Targets)
include(cmake/Module.cmake)
file(GLOB children RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}/src ${CMAKE_CURRENT_SOURCE_DIR}/src/*)
foreach(module_path ${children})
if(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src/${module_path})
if(EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/src/${module_path}/module.cmake)
include(src/${module_path}/module.cmake)
else()
void_add_module(${module_path})
endif()
endif()
endforeach()
add_subdirectory(tests)
get_property(ALL_DISCOVERED_MODULES GLOBAL PROPERTY VOID_MODULES)
get_property(ALL_EXTERNAL_DEPS GLOBAL PROPERTY VOID_EXT_DEPS)
if(ALL_EXTERNAL_DEPS)
list(REMOVE_DUPLICATES ALL_EXTERNAL_DEPS)
endif()
set(VOID_EXTERNAL_DEPS_LIST "${ALL_EXTERNAL_DEPS}")
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
VERSION ${PROJECT_VERSION}
COMPATIBILITY SameMajorVersion
)
configure_package_config_file(
"${CMAKE_CURRENT_SOURCE_DIR}/cmake/VoidConfig.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
INSTALL_DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
)
install(EXPORT ${EXPORT_SET_NAME}
NAMESPACE ${PROJECT_NAME}::
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
)
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}Config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${PROJECT_NAME}ConfigVersion.cmake"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME}"
)
+25
View File
@@ -0,0 +1,25 @@
include(FetchContent)
function(void_fetch_dependency DEP_NAME)
# FIXME: Add if needed external
# if(DEP_NAME STREQUAL "glaze")
# if(NOT glaze_POPULATED)
# message(STATUS "[MyLib] Fetching Glaze on-demand...")
# FetchContent_Declare(glaze
# GIT_REPOSITORY https://github.com/stephenberry/glaze.git
# GIT_TAG v2.8.5
# )
# FetchContent_MakeAvailable(glaze)
# endif()
#
# elseif(DEP_NAME STREQUAL "fmt")
# if(NOT fmt_POPULATED)
# message(STATUS "[MyLib] Fetching fmt on-demand...")
# FetchContent_Declare(fmt
# GIT_REPOSITORY https://github.com/fmtlib/fmt.git
# GIT_TAG 10.2.1
# )
# FetchContent_MakeAvailable(fmt)
# endif()
# endif()
endfunction()
+72
View File
@@ -0,0 +1,72 @@
set_property(GLOBAL PROPERTY VOID_MODULES "")
set_property(GLOBAL PROPERTY VOID_EXT_DEPS "")
function(void_add_module MODULE_NAME)
cmake_parse_arguments(ARG "" "" "INTERNAL_DEPS;EXTERNAL_DEPS;OPTIONAL_DEPS" ${ARGN})
set(TGT ${PROJECT_NAME}_${MODULE_NAME})
set(ALIAS ${PROJECT_NAME}::${MODULE_NAME})
file(GLOB_RECURSE SRC CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/src/${MODULE_NAME}/*.cpp")
file(GLOB_RECURSE HDR CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/include/Void/${MODULE_NAME}/*.hpp")
if(NOT SRC AND NOT HDR)
return()
endif()
if(NOT SRC)
set(LIB_TYPE "INTERFACE")
set(SCOPE "INTERFACE")
add_library(${TGT} INTERFACE)
target_compile_features(${TGT} INTERFACE cxx_std_23)
else()
set(LIB_TYPE "SHARED")
set(SCOPE "PUBLIC")
add_library(${TGT} SHARED)
target_sources(${TGT} PRIVATE ${SRC})
target_compile_features(${TGT} PRIVATE cxx_std_23)
endif()
add_library(${ALIAS} ALIAS ${TGT})
set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME})
foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS)
string(REGEX REPLACE "::.*" "" BASE_DEP ${ext_dep})
set_property(GLOBAL APPEND PROPERTY VOID_EXT_DEPS ${BASE_DEP})
include(cmake/Dependencies.cmake)
void_fetch_dependency(${BASE_DEP})
endforeach()
foreach(int_dep IN LISTS ARG_INTERNAL_DEPS)
target_link_libraries(${TGT} ${SCOPE} ${PROJECT_NAME}::${int_dep})
endforeach()
get_property(CURRENT_MODULES GLOBAL PROPERTY VOID_MODULES)
foreach(opt_dep IN LISTS ARG_OPTIONAL_DEPS)
if(${opt_dep} IN_LIST CURRENT_MODULES)
target_link_libraries(${TGT} ${SCOPE} ${PROJECT_NAME}::${opt_dep})
string(TOUPPER ${opt_dep} UPPER_DEP)
target_compile_definitions(${TGT} ${SCOPE} VOID_HAS_${UPPER_DEP})
endif()
endforeach()
if(ARG_EXTERNAL_DEPS)
target_link_libraries(${TGT} ${SCOPE} ${ARG_EXTERNAL_DEPS})
endif()
set_target_properties(${TGT} PROPERTIES
CXX_STANDARD 23
CXX_STANDARD_REQUIRED ON
CXX_EXTENSIONS OFF
)
target_sources(${TGT} ${SCOPE} FILE_SET HEADERS BASE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}/include" FILES ${HDR})
target_include_directories(${TGT} ${SCOPE}
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>
)
install(TARGETS ${TGT} EXPORT ${EXPORT_SET_NAME}
FILE_SET HEADERS DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}"
RUNTIME DESTINATION "${CMAKE_INSTALL_BINDIR}"
LIBRARY DESTINATION "${CMAKE_INSTALL_LIBDIR}"
ARCHIVE DESTINATION "${CMAKE_INSTALL_LIBDIR}"
)
endfunction()
+14
View File
@@ -0,0 +1,14 @@
@PACKAGE_INIT@
include(CMakeFindDependencyMacro)
set(_void_external_deps "@VOID_EXTERNAL_DEPS_LIST@")
foreach(dep IN LISTS _void_external_deps)
if(NOT TARGET ${dep})
find_dependency(${dep})
endif()
endforeach()
include("${CMAKE_CURRENT_LIST_DIR}/@EXPORT_SET_NAME@.cmake")
check_required_components("@PROJECT_NAME@")
+5
View File
@@ -0,0 +1,5 @@
#example how add module
void_add_module(Logging
INTERNAL_DEPS Core
EXTERNAL_DEPS glaze::glaze
)
+53
View File
@@ -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
+66
View File
@@ -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);
}
};
+467
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
#pragma once
View File
Whitespace-only changes.
+10
View File
@@ -0,0 +1,10 @@
#include <Void/Logging/Level.hpp>
#include <string_view>
namespace Void::Logging
{
} // namespace Void::Logging
constexpr std::string_view to_string(Void::Logging::Level level)
{
return Void::Logging::to_string(level);
};
+317
View File
@@ -0,0 +1,317 @@
#include <Void/Logging/Logger.hpp>
#include <utility> // std::exchange
namespace Void::Logging
{
// =============================================================================
// Thread-local definition
// =============================================================================
thread_local std::vector<std::string> Logger::s_scope_stack;
// =============================================================================
// ScopedContext
// =============================================================================
Logger::ScopedContext::ScopedContext(Logger& owner,
std::string name,
Level level,
std::source_location loc) noexcept
: m_owner(&owner), m_name(std::move(name)), m_level(level)
{
// push_back can technically throw; if it does we mark inactive so
// the destructor does not attempt a mismatched pop or spurious exit
// entry.
try {
s_scope_stack.push_back(m_name);
} catch (...) {
m_active = false;
return;
}
// Emit the ScopeEnter entry after the push so Entry::scopes already
// contains the new scope (innermost = last).
owner.emit_scope_boundary(Kind::ScopeEnter, m_name, m_level, loc);
}
Logger::ScopedContext::~ScopedContext() noexcept
{
if (!m_active || m_owner == nullptr) {
return;
}
// Emit the exit entry while the scope is still on the stack so that
// Entry::scopes reflects the stack *including* this scope, matching the
// ScopeEnter entry.
m_owner->emit_scope_boundary(
Kind::ScopeExit,
m_name,
m_level,
std::source_location{}); // no meaningful caller site
if (!s_scope_stack.empty()) {
s_scope_stack.pop_back();
}
}
Logger::ScopedContext::ScopedContext(ScopedContext&& other) noexcept
: m_owner(std::exchange(other.m_owner, nullptr)),
m_name(std::move(other.m_name)), m_level(other.m_level),
m_active(std::exchange(other.m_active, false))
{
}
// =============================================================================
// Logger — lifetime
// =============================================================================
Logger::Logger(Mode mode, std::size_t capacity) noexcept
: m_mode(mode), m_buffer_capacity(capacity)
{
if (m_mode == Mode::Buffered) {
m_buffer.reserve(m_buffer_capacity);
}
}
// =============================================================================
// Configuration
// =============================================================================
void Logger::set_level(Level level) noexcept
{
std::lock_guard lock(m_mutex);
m_level = level;
}
Level Logger::level() const noexcept
{
std::lock_guard lock(m_mutex);
return m_level;
}
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;
if (m_mode == Mode::Buffered) {
m_buffer.reserve(m_buffer_capacity);
}
}
if (!to_flush.empty()) {
on_flush(to_flush); // called outside the lock
}
}
Mode Logger::mode() const noexcept
{
std::lock_guard lock(m_mutex);
return m_mode;
}
void Logger::set_buffer_capacity(std::size_t n) noexcept
{
std::lock_guard lock(m_mutex);
m_buffer_capacity = n;
}
std::size_t Logger::buffer_capacity() const noexcept
{
std::lock_guard lock(m_mutex);
return m_buffer_capacity;
}
// =============================================================================
// Scoped context
// =============================================================================
Logger::ScopedContext Logger::push_scope(std::string name,
Level level,
std::source_location loc) noexcept
{
return ScopedContext(*this, std::move(name), level, loc);
}
void Logger::scope(std::string_view name,
Level level,
std::source_location loc)
{
// Emit a pair of scope boundary entries back-to-back.
// The scope stack is NOT modified — this is the "lightweight" variant.
emit_scope_boundary(Kind::ScopeEnter, name, level, loc);
emit_scope_boundary(Kind::ScopeExit, name, level,
std::source_location{});
}
std::span<const std::string> Logger::current_scopes() noexcept
{
return s_scope_stack;
}
// =============================================================================
// Preset factory
// =============================================================================
Logger::Preset Logger::make_preset(Level level, std::string prefix) noexcept
{
return Preset(*this, level, std::move(prefix));
}
// =============================================================================
// Core logging
// =============================================================================
void Logger::log(Level level, std::string_view message,
std::source_location location)
{
// Early level check outside the lock to avoid allocations on the hot
// path.
{
std::lock_guard lock(m_mutex);
if (level < m_level) {
return;
}
}
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 = s_scope_stack, // snapshot — s_scope_stack is thread-local
};
submit(std::move(entry));
}
void Logger::trace(std::string_view msg, std::source_location loc)
{
log(Level::Trace, msg, loc);
}
void Logger::debug(std::string_view msg, std::source_location loc)
{
log(Level::Debug, msg, loc);
}
void Logger::info(std::string_view msg, std::source_location loc)
{
log(Level::Info, msg, loc);
}
void Logger::warning(std::string_view msg, std::source_location loc)
{
log(Level::Warning, msg, loc);
}
void Logger::error(std::string_view msg, std::source_location loc)
{
log(Level::Error, msg, loc);
}
void Logger::fatal(std::string_view msg, std::source_location loc)
{
log(Level::Fatal, msg, loc);
}
// =============================================================================
// Flush
// =============================================================================
void Logger::flush()
{
std::vector<Entry> to_flush;
{
std::lock_guard lock(m_mutex);
to_flush = std::move(m_buffer);
m_buffer = {};
}
// Call the virtual method outside the lock so derived classes can
// safely do blocking I/O, acquire their own mutexes, etc.
if (!to_flush.empty()) {
on_flush(to_flush);
}
}
void Logger::on_flush(std::span<const Entry> entries)
{
for (const auto& entry : entries) {
write(entry);
}
}
// =============================================================================
// Private — emit_scope_boundary
// =============================================================================
void Logger::emit_scope_boundary(Kind kind,
std::string_view name,
Level level,
std::source_location loc)
{
// Respect the configured minimum level for scope entries too.
{
std::lock_guard lock(m_mutex);
if (level < m_level) {
return;
}
}
Entry entry{
.kind = kind,
.level = level,
.message = std::string(name),
.timestamp = std::chrono::system_clock::now(),
.location = loc,
.thread_id = std::this_thread::get_id(),
.scopes = s_scope_stack, // snapshot at boundary time
};
submit(std::move(entry));
}
// =============================================================================
// Private — submit
// =============================================================================
void Logger::submit(Entry entry)
{
bool write_now = false;
std::vector<Entry> batch;
{
std::lock_guard lock(m_mutex);
// Re-check level under the lock; set_level() may have raced.
if (entry.level < m_level) {
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);
}
}
} // ← mutex released here
// 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);
}
}
} // namespace Void::Logging
+53
View File
@@ -0,0 +1,53 @@
if(NOT VOID_ENABLE_TESTING)
message("Tests disabled")
return()
endif()
enable_testing()
# Get the list of modules that were actually successfully created
get_property(ACTIVE_MODULES GLOBAL PROPERTY VOID_MODULES)
# ------------------------------------------------------------------------------
# PART 1: Internal "Kitchen Sink" Test (One Executable to rule them all)
# ------------------------------------------------------------------------------
file(GLOB_RECURSE INTERNAL_SOURCES CONFIGURE_DEPENDS "internal/*.cpp")
if(INTERNAL_SOURCES)
add_executable(VoidInternalTests ${INTERNAL_SOURCES})
# Always link the Testing framework
target_link_libraries(VoidInternalTests PRIVATE Void::Testing)
# Link against EVERY active module in the project
foreach(mod ${ACTIVE_MODULES})
# Avoid self-linking if Testing is in the list
if(NOT mod STREQUAL "Testing")
target_link_libraries(VoidInternalTests PRIVATE Void::${mod})
endif()
endforeach()
add_test(NAME AllInternalTests COMMAND VoidInternalTests)
endif()
# ------------------------------------------------------------------------------
# PART 2: Standalone Tests (Isolated Executables per Module)
# ------------------------------------------------------------------------------
foreach(mod ${ACTIVE_MODULES})
# Look for a subdirectory in standalone/ that matches the module name
set(STANDALONE_MOD_DIR "${CMAKE_CURRENT_SOURCE_DIR}/standalone/${mod}")
if(IS_DIRECTORY ${STANDALONE_MOD_DIR})
file(GLOB test_files CONFIGURE_DEPENDS "${STANDALONE_MOD_DIR}/*.cpp")
foreach(test_src ${test_files})
get_filename_component(test_file_name ${test_src} NAME_WE)
set(EXE_NAME "test_standalone_${mod}_${test_file_name}")
add_executable(${EXE_NAME} ${test_src})
# Only links against its specific module
target_link_libraries(${EXE_NAME} PRIVATE Void::${mod})
add_test(NAME ${EXE_NAME} COMMAND ${EXE_NAME})
endforeach()
endif()
endforeach()
+427
View File
@@ -0,0 +1,427 @@
#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;
}