33 changed files with 3925 additions and 1337 deletions

No files matched your search

+5
View File
@@ -1,6 +1,7 @@
set_property(GLOBAL PROPERTY VOID_MODULES "")
set_property(GLOBAL PROPERTY VOID_MODULE_DEPENDENCY_RECORDS "")
set_property(GLOBAL PROPERTY VOID_PENDING_OPTIONAL_DEPS "")
set_property(GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "")
function(void_add_module MODULE_NAME)
cmake_parse_arguments(ARG "" ""
@@ -61,6 +62,10 @@ function(void_add_module MODULE_NAME)
add_library(${ALIAS} ALIAS ${TGT})
set_property(GLOBAL APPEND PROPERTY VOID_MODULES ${MODULE_NAME})
foreach(_hdr IN LISTS HDR)
file(RELATIVE_PATH _rel_hdr "${CMAKE_CURRENT_SOURCE_DIR}/include" "${_hdr}")
set_property(GLOBAL APPEND PROPERTY VOID_ACTIVE_PUBLIC_HEADERS "${_rel_hdr}")
endforeach()
set(_module_external_deps "")
foreach(ext_dep IN LISTS ARG_EXTERNAL_DEPS)
# FindSQLite3's package name and imported-target namespace differ.
+1
View File
@@ -72,3 +72,4 @@ plans requiring updates. Do not record a proposal as user approval.
| D-029 | Follow `MIGRATION.md` Wave A+B: keep 1.x public APIs and existing tests compiling/passing while introducing NEW APIs and adapters beside them | CONFIRMED by user |
| D-030 | Create dedicated git branch (`feat/roadmap-p0-p1-foundations`) and make focused commits per completed milestone/task; leave local untracked files (`.env`, `.serena/`, `WG.conf`, `keys`) untouched | CONFIRMED by user |
| D-031 | Proceed continuously across roadmap waves without pausing for confirmation between waves, and merge verified waves locally into `main` (without pushing to remote) | CONFIRMED by user |
| D-032 | Push verified `main` (and active feature branches) to `origin` (`git@git.faumaray.com:Void/VoidLibrary.git`) after each verified wave merge, superseding the local-only constraint in `D-031` | CONFIRMED by user ("dont forget to push") |
+44 -8
View File
@@ -1,8 +1,8 @@
# Workflow state
Updated: 2026-11-24.
Repository: VoidLibrary; active branch `feat/roadmap-p1-wave4b` (from `main`
at `2e5d1ef`, merged Waves 1–4A).
Repository: VoidLibrary; active branch `feat/roadmap-p2-wave5` (from `main`
at `1e901ce`, merged Waves 1–4B and pushed to `origin/main`).
## Completed objective
@@ -72,10 +72,11 @@ at `2e5d1ef`, merged Waves 1–4A).
## Baseline and authorization
User decisions D-027..D-031 authorize continuous roadmap-order execution on branch
`feat/roadmap-p0-p1-foundations`, per-task workflow specs in `docs/agent-workflow/tasks/`,
Wave A+B API compatibility, and local merges of verified waves into `main` (without
pushing to remote) while leaving local untracked files untouched.
User decisions D-027..D-032 authorize continuous roadmap-order execution across dedicated
wave branches (`feat/roadmap-*`), per-task workflow specs in
`docs/agent-workflow/tasks/`, Wave A+B API compatibility, `--no-ff` merges of verified
waves into `main`, and pushing verified `main` and active feature branches to `origin`
while leaving local untracked files untouched.
## Verification already observed (P0)
@@ -180,7 +181,42 @@ pushing to remote) while leaving local untracked files untouched.
`binary_reader_u64_be` 1.35 ns, `data_json_parse_small_object` 316.78 ns,
`data_json_serialize_small_object` 168.16 ns.
## Verification already observed (Wave 5 — P2 Operations Foundations)
- `ObservabilityHooks` + `Observability` (`fe99051`): `Observability*` 4/4 passed
(12.1 ms); `ctest` 2/2 passed (including `ObservabilityHooksOnly` &
`ObservabilityOnly`, 7.03 s).
- `Resilience` + `ResilienceAsync` + P2 error domains (`18a623a`): standalone 21/21
(2.8 ms) + `AsyncPolicy*` 6/6 (1.3 ms); `ctest` 2/2 (5.99 s including `ResilienceOnly`).
- `LogState` + `Log` + `LogConfig` (`a74a402`): `Log;Testing` `724 ✔`, `2 ⊘`
(`broken_feature`, `unquoted_skip`), `0 ✘` (799.2 ms); `ctest` 2/2 (`LogOnly` 7.15 s,
total 8.09 s); `LogConfig;Testing` 12/12 (28.9 ms).
- CMake `VOID_ACTIVE_PUBLIC_HEADERS` fix (`3d8dfb0`) + `Stacktrace` (`7b57b35`):
`Stacktrace;Testing` `Stacktrace*` 4/4 passed (374.2 ms) without selecting `Log`.
- Full RelWithDebInfo + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w5-full`, 37 modules,
`7b57b35`): `VoidTests` 1,378 tests — 1,375 passed, 3 intentional skips
(`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (7.49 s);
`ctest` 2/2 passed (`VoidTests` 8.09 s, `VoidInstalledComponentConsumers` all 16 consumers
66.12 s, total 74.22 s).
- Full Debug ASan + UBSan + `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w5-asan`, 37
modules, `7b57b35`): initial run hit 1 timing assertion in unrelated existing
`internal_fsm_service_hot_reload_under_load` (`FsmServiceHotReload.cpp:119`); clean
re-run passed all 1,378 tests — 1,375 passed, 3 skipped, 0 failed (50.16 s), 0 leaks,
0 UB.
- Wave 5 Debug TSan subset (`/tmp/void-w5-tsan`, 15 modules, `7b57b35`):
`Observability*|ResilienceHardening*|AsyncPolicy*|Log*|AsyncLogger*|LogScopeSnapshot*|Io*|OperationScope*`
68/68 passed (7.01 s), 0 TSan data races.
- `VoidFoundationBench` post-W5 (`rev=7b57b355cd75`, `/tmp/void-w5-full`, `post-w5.json`):
`harness_empty_loop` 0.75 ns, `core_uuid_parse_hyphenated` 43.49 ns,
`core_uuid_to_string` 32.51 ns, `core_hash_fnv1a64_256b` 213.37 ns,
`core_hash_murmur3_256b` 92.34 ns, `functional_result_ok_chain` 1.65 ns,
`functional_error_with_context` 94.82 ns, `math_checked_add_loop` 0.86 ns,
`containers_spsc_ring_push_pop` 10.76 ns, `containers_lru_get_put` 31.99 ns,
`binary_reader_u64_be` 2.24 ns, `data_json_parse_small_object` 576.81 ns,
`data_json_serialize_small_object` 284.87 ns.
## Ownership and next step
Waves 1–4B (`P0` and `P1`) are complete and verified on `feat/roadmap-p1-wave4b` and ready
to merge locally into `main`, before planning and executing **P2 Wave 5**.
Waves 1–5 (`P0`, `P1`, and `P2` Operations Foundations: `Observability`, `Resilience`,
`Log`, `Stacktrace`) are complete and verified on `feat/roadmap-p2-wave5`, ready to merge
into `main`, push to `origin`, and proceed continuously to **P2 Wave 6**.
+11
View File
@@ -59,6 +59,17 @@ These tasks author plans. Future feature task IDs inside those plans remain plan
| S-RUNTIME-01 | `CMakeLists.txt` explicit `void_add_module` keyword matching fix, `src/Runtime/module.cmake` (`Core Functional Time Memory Algorithms Async IO`), `Options.hpp`, `ResourceGraph.hpp`, `Host.hpp`, `RuntimeOnly` consumer (`1b3331e`) | [S-RUNTIME-01](tasks/S-RUNTIME-01.md) | VERIFIED | `RuntimeHost` 3/3, `RuntimeOnly` & `ctest` 2/2 passed (11-module closure); full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) |
| M-TESTING-02, M-TESTING-03 | `OwningJUnitReporter`, strict CLI/config validation (`--allow-empty`, `--selftest-child`), bounded assertion/failure capture, `Subprocess` POSIX runner, frozen v1 `DeterministicRng`/`ReplayToken`/`check_property` shrinker & `DeterministicRun` (`de8a981`) | [M-TESTING-02-03](tasks/M-TESTING-02-03.md) | VERIFIED | `Core;Testing` 14 ✔ / 2 ⊘ & `ctest` 2/2 passed; full RelWithDebInfo (1,356 ✔) & ASan+UBSan (0 leaks/UB) |
## Wave 5 — P2 Operations Foundations (`feat/roadmap-p2-wave5`)
| ID | Deliverable | Spec | State | Verification summary |
| --- | --- | --- | --- | --- |
| Wave 5 specs & P2 error domains | Per-task specs under `docs/agent-workflow/tasks/` and reserved P2 domain IDs (`kRuntimeErrorDomain = 11`, `kLogErrorDomain = 12`, `kStacktraceErrorDomain = 13`, `kObservabilityErrorDomain = 14`, `kResilienceErrorDomain = 15`) (`809b6f5`, fixed in `18a623a`) | — | VERIFIED | Integrated RelWithDebInfo & ASan+UBSan passed with zero domain collisions |
| S-OBSERVABILITY-01..04 | `ObservabilityHooks` std-only `INTERFACE`, `Observability` (`Hooks`, `Context`, `AsyncContext`, thread-sharded `Metrics`, sampled/budgeted `Tracing`), `ObservabilityHooksOnly` & `ObservabilityOnly` consumers (`fe99051`) | [S-OBSERVABILITY-01-04](tasks/S-OBSERVABILITY-01-04.md) | VERIFIED | `Observability` 4/4, Debug TSan 4/4 (0 races), `ObservabilityHooksOnly`/`ObservabilityOnly` consumers, full RelWithDebInfo (1,375 ✔) & ASan+UBSan (0 leaks/UB) |
| M-RESILIENCE-01..04 | `Resilience` (`Types`, `RateLimiter`, bounded cursor `KeyedRateLimiter`, generation-bound `Breaker`/`BreakerPermit`, overflow-safe `ResourceMonitor`/`ResourcePermit`) & `ResilienceAsync` (`AsyncPolicy` FIFO `Bulkhead`, `execute_resilient`), `ResilienceOnly` consumer (`18a623a`) | [M-RESILIENCE-01-04](tasks/M-RESILIENCE-01-04.md) | VERIFIED | Standalone 21/21 & `AsyncPolicy` 6/6, Debug TSan `ResilienceHardening`+`AsyncPolicy` 6/6 (0 races), `ResilienceOnly` consumer, full RelWithDebInfo (1,375 ✔) & ASan+UBSan |
| M-LOG-01..05 | Hardened `LogState` (`SinkRegistration`, `detach_and_drain`, reentrancy cap 8), bounded `Logger` (`DeliveryLimits`, `LoggerOptions`, `try_submit`, `flush_through`, quarantine, `set_mode` barrier), redaction/escaping `Formatter`, `MultiLogger::try_add` cap 8 + cycle check, `FileLogger`/`RotatingFileLogger` `fsync`/`reopen`, separate `LogConfig`, `LogOnly` consumer (`a74a402`) | [M-LOG-01-05](tasks/M-LOG-01-05.md) | VERIFIED | `Log;Testing` 724 ✔ / 2 ⊘ & `LogConfig;Testing` 12/12, Debug TSan 36/36 (`Log*`, `AsyncLogger*`, `LogScopeSnapshot*`, `LogHardening*`), `LogOnly` consumer, full RelWithDebInfo & ASan+UBSan |
| CMake test header check fix | Track `VOID_ACTIVE_PUBLIC_HEADERS` in `cmake/Module.cmake` so `tests/CMakeLists.txt` maps split `EXTRA_HEADERS` (e.g. `Void/Log/Log.hpp` -> `LogState`) accurately (`3d8dfb0`) | — | VERIFIED | `Stacktrace;Testing` discovers and passes `Stacktrace*` 4/4 without `Log`; full suite discovers all 1,378 tests |
| M-STACKTRACE-01..04 | `src/Stacktrace/module.cmake` (`INTERNAL_DEPS Functional Time LogState`), split `capture()` (<=256 frames, zero log/source IO) & `Resolver` (1024-entry / 4 MiB cache, `invalidate_module`), `Capabilities`, checked `read_source_snippet_checked` (roots, symlink-escape & `..` rejection, overflow-safe `int64_t` math), `format_resolved_trace`, `write_fatal_signal_marker`, `tests/standalone/Stacktrace/Stacktrace.cpp` (`7b57b35`) | [M-STACKTRACE-01-04](tasks/M-STACKTRACE-01-04.md) | VERIFIED | `Stacktrace;Testing` `Stacktrace*` 4/4 (374.2ms), full RelWithDebInfo (1,375 ✔) & ASan+UBSan (0 leaks/UB) |
All workers share the checkout and have disjoint file ownership defined in their
persisted task specifications. Root owns all cross-cutting files and resolves contract
changes. No worker owns application code, build files, existing docs/short-url.md, or Git
+15
View File
@@ -215,3 +215,18 @@ Branch: `feat/roadmap-p1-wave4b` (branched from `main` at `2e5d1ef`). Toolchain
| Full Integrated ASan+UBSan (`de8a981`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w4b-asan`, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w4b-asan/tests/VoidTests` | 33 active modules; `VoidTests`: 1,359 tests — 1,356 passed, 3 skipped, 0 failed (14.87s), 0 leaks, 0 UB |
| Wave 4B TSan Subset (`de8a981`) | `dev cpp-gcc -c` Debug (`IO;Async;Containers;Time;Testing`, `/tmp/void-w4b-tsan`, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w4b-tsan/tests/VoidTests --filter "Io*\|OperationScope*\|Executor*\|Ring*\|Pool*\|Clock*"` | 9 active modules; 80/80 passed (60.7ms), 0 TSan data races |
| Post-W4B Benchmark (`de8a981`, `rev=de8a981893d8`) | `VoidFoundationBench` in `/tmp/void-w4b-full` (`post-w4b.json`) | Medians: `harness_empty_loop` 0.39ns, `core_uuid_parse_hyphenated` 25.28ns, `core_uuid_to_string` 16.94ns, `core_hash_fnv1a64_256b` 184.30ns, `core_hash_murmur3_256b` 69.63ns, `functional_result_ok_chain` 1.16ns, `functional_error_with_context` 60.17ns, `math_checked_add_loop` 0.48ns, `containers_spsc_ring_push_pop` 9.06ns, `containers_lru_get_put` 21.30ns, `binary_reader_u64_be` 1.35ns, `data_json_parse_small_object` 316.78ns, `data_json_serialize_small_object` 168.16ns |
## Wave 5 / P2 Operations Foundations Verification (2026-11-24)
Branch: `feat/roadmap-p2-wave5` (branched from `main` at `1e901ce`, which was pushed to `origin/main`). Toolchain via `dev cpp-gcc`: GCC 16.2.0, CMake 4.4.4, Ninja 1.13.2.
| Scope | Command & configuration | Observed outcome |
| --- | --- | --- |
| S-OBSERVABILITY-01..04 (`fe99051`) | `Observability;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` `/tmp/void-w5-obs` (`VoidTests --filter "Observability*"`, `ctest`) | `Observability` 4/4 passed (12.1ms); `ctest` 2/2 passed (`VoidTests` 0.41s, `VoidInstalledComponentConsumers` including `ObservabilityHooksOnly` & `ObservabilityOnly` 6.62s, total 7.03s) |
| M-RESILIENCE-01..04 (`18a623a`) | `Resilience;Testing` (`/tmp/void-w5-resilience`) & `ResilienceAsync;Testing` (`/tmp/void-w5-resilience-async`) RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` | `Resilience` `CircuitBreaker*\|RateLimiter*\|KeyedRateLimiter*\|ResourceMonitor*\|ResilienceHardening*` 21/21 (2.8ms) & `ctest` 2/2 (`5.99s` including `ResilienceOnly`); `ResilienceAsync` `AsyncPolicy*\|ResilienceHardening*` 6/6 (1.3ms) |
| M-LOG-01..05 (`a74a402`) | `Log;Testing` (`/tmp/void-w5-log`, 10 modules) & `LogConfig;Testing` (`/tmp/void-w5-logconfig`, 13 modules) RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` | `Log;Testing` `VoidTests`: 726 tests — 724 passed, 2 intentional skips (`broken_feature`, `unquoted_skip`), 0 failed (799.2ms) & `ctest` 2/2 (8.09s including `LogOnly` 7.15s); `LogConfig;Testing` `LogHardening*\|FromConfig*` 12/12 (28.9ms) |
| M-STACKTRACE-01..04 & CMake fix (`3d8dfb0`, `7b57b35`) | `Stacktrace;Testing` RelWithDebInfo `-DVOID_WARNINGS_AS_ERRORS=ON` (`/tmp/void-w5-stacktrace`, 6 active modules, Boost cached) | `Stacktrace*` 4/4 passed (374.2ms); `Log` not required thanks to `VOID_ACTIVE_PUBLIC_HEADERS` mapping |
| Full Integrated RelWithDebInfo (`7b57b35`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` full build (`/tmp/void-w5-full`, 37 modules, `-DVOID_WARNINGS_AS_ERRORS=ON -DVOID_ENABLE_BENCHMARKS=ON`), `/tmp/void-w5-full/tests/VoidTests`, `ctest --test-dir /tmp/void-w5-full --output-on-failure --timeout 180` | `VoidTests`: 1,378 tests — 1,375 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (7.49s); `ctest`: 2/2 passed (`VoidTests` 8.09s + `VoidInstalledComponentConsumers` all 16 consumers 66.12s, total 74.22s) |
| Full Integrated ASan+UBSan (`7b57b35`) | `dev cpp-gcc -p libarchive -p openssl -p sqlite -p libsodium` Debug (`/tmp/void-w5-asan`, 37 modules, `-DVOID_ENABLE_ASAN=ON -DVOID_ENABLE_UBSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `ASAN_OPTIONS=detect_leaks=1:halt_on_error=1 UBSAN_OPTIONS=print_stacktrace=1:halt_on_error=1 /tmp/void-w5-asan/tests/VoidTests` | Initial run hit 1 timing assertion in unrelated existing `internal_fsm_service_hot_reload_under_load` (`FsmServiceHotReload.cpp:119`, 0 leaks/UB); full re-run on same binary passed 1,378 tests — 1,375 passed, 3 intentional skips (`plugin_load_and_query_skipped`, `broken_feature`, `unquoted_skip`), 0 failed (50.16s), 0 ASan/LSan leaks, 0 UBSan errors |
| Wave 5 TSan Subset (`7b57b35`) | `dev cpp-gcc -c` Debug (`Observability;ResilienceAsync;Log;IO;Async;Time;Testing`, `/tmp/void-w5-tsan`, 15 modules, `-DVOID_ENABLE_TSAN=ON -DVOID_WARNINGS_AS_ERRORS=ON`), `/tmp/void-w5-tsan/tests/VoidTests --filter "Observability*\|ResilienceHardening*\|AsyncPolicy*\|Log*\|AsyncLogger*\|LogScopeSnapshot*\|Io*\|OperationScope*"` | 68/68 passed (7.01s, including `AsyncLogger::async_multi_producer_no_loss` 6.53s, `Observability` 4/4, `ResilienceHardening` 4/4, `AsyncPolicy` 2/2, `Log` 12/12, `LogHardening` 4/4, `LogScopeSnapshot` 3/3, `IoDriver` 4/4, `OperationScope` 5/5), 0 TSan data races |
| Post-W5 Benchmark (`7b57b35`, `rev=7b57b355cd75`) | `/tmp/void-w5-full/benchmarks/VoidFoundationBench --json /tmp/void-w5-full/post-w5.json` (RelWithDebInfo, warmup=5, reps=20, ops=10000) | Medians: `harness_empty_loop` 0.75ns, `core_uuid_parse_hyphenated` 43.49ns, `core_uuid_to_string` 32.51ns, `core_hash_fnv1a64_256b` 213.37ns, `core_hash_murmur3_256b` 92.34ns, `functional_result_ok_chain` 1.65ns, `functional_error_with_context` 94.82ns, `math_checked_add_loop` 0.86ns, `containers_spsc_ring_push_pop` 10.76ns, `containers_lru_get_put` 31.99ns, `binary_reader_u64_be` 2.24ns, `data_json_parse_small_object` 576.81ns, `data_json_serialize_small_object` 284.87ns |
+6 -43
View File
@@ -1,5 +1,7 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <chrono>
#include <cstddef>
#include <filesystem>
@@ -12,37 +14,12 @@ namespace Void::Logging::Detail
struct RollingFileOptions {
std::size_t max_bytes = 1024 * 1024;
std::size_t max_files = 5;
bool create_directories = true;
};
/// Format a time point as a filesystem-safe, lexicographically (and
/// therefore chronologically) sortable UTC timestamp:
/// `YYYYMMDD-HHMMSS-ffffff` (microseconds).
[[nodiscard]] std::string
format_timestamp(std::chrono::system_clock::time_point tp);
/// A single append-only log file with size-based rotation. Not thread
/// safe — each sink owns one and drives it from its single worker.
///
/// Two rotation modes, selected by the `self_rotate` constructor
/// argument:
///
/// - self_rotate = true (default), "solo": write() rotates on its
/// own once the file exceeds max_bytes. The live file is closed
/// and renamed in place to `<name>-<rotation_time>` — same
/// directory, no subfolder. At most max_files such archives are
/// kept; the oldest (by name, which sorts chronologically) is
/// deleted. With max_files == 0 nothing is kept — the file is
/// just truncated.
///
/// - self_rotate = false, "grouped": write() only tracks size and
/// never rotates by itself. The owner polls exceeds_limit()
/// across a set of RollingFiles and, once any one of them crosses
/// the threshold, calls snapshot_into(dir) on every file in that
/// set so they all land — under their original names — in the
/// same directory at the same moment (e.g. so several files can
/// roll together into one shared `history/<creation_time>/`).
/// max_files does not apply to this path: nothing is ever deleted,
/// every snapshot is kept.
class RollingFile
{
public:
@@ -50,32 +27,18 @@ namespace Void::Logging::Detail
RollingFile(std::filesystem::path path, RollingFileOptions opt,
bool self_rotate = true);
/// Open for append (creating parent dirs). False on failure.
[[nodiscard]] bool open();
[[nodiscard]] bool reopen();
/// Append a line (a trailing '\n' is added). In solo mode,
/// rotates automatically once max_bytes is exceeded; in
/// grouped mode this only updates the byte count — the
/// caller drives rotation via exceeds_limit()/snapshot_into().
/// No-op if not open.
void write(std::string_view line);
void flush();
[[nodiscard]] Void::Result::Result<void> sync();
/// True once the current file has reached max_bytes. Meant
/// for grouped (self_rotate == false) use, so an owner can
/// check a whole set of files and decide when to roll them
/// together.
[[nodiscard]] bool exceeds_limit() const noexcept
{
return m_current_bytes >= m_opt.max_bytes;
}
/// Move the live file — same name, unmodified — into `dir`
/// (created if needed), then continue with a fresh file at
/// path(). Ignores max_files; nothing is ever deleted here.
/// Intended to be called on every file in a group so they
/// land together.
void snapshot_into(const std::filesystem::path& dir);
[[nodiscard]] bool is_open() const noexcept
@@ -102,4 +65,4 @@ namespace Void::Logging::Detail
std::chrono::time_point<std::chrono::system_clock> m_rotationTime;
};
} // namespace Void::Logging::Detail
} // namespace Void::Logging::Detail
+7 -18
View File
@@ -11,14 +11,6 @@
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
@@ -44,18 +36,15 @@ namespace Void::Logging
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.
/// time.
std::vector<std::string> scopes{};
/// Structured key/value fields attached to this entry — a frozen
/// snapshot of the thread-local FieldScope stack at log time.
/// Formatters expose them as custom pattern tokens
/// (`{field:key}`) and in JSON/logfmt output. Later duplicate
/// keys win.
/// Structured key/value fields attached to this entry.
std::vector<std::pair<std::string, std::string>> fields{};
/// True when explicit oversize-truncation policy clipped message,
/// fields, scopes, or formatted payload.
bool truncated{false};
};
} // namespace Void::Logging
} // namespace Void::Logging
+17 -20
View File
@@ -12,21 +12,6 @@
namespace Void::Logging
{
/// Logger sink that appends formatted entries to a file on disk.
///
/// Defaults to Mode::Async — entries are queued lock-free and written
/// in batches by the logger's worker thread (one ofstream flush per
/// batch). The destructor flushes any remaining entries. Pass
/// Mode::Immediate/Buffered to opt out of the worker thread.
///
/// Two construction paths:
/// - `FileLogger::open(path)` returns
/// `Result<unique_ptr<FileLogger>, Error>` and never throws —
/// prefer this in code that already uses Void::Result for error
/// plumbing.
/// - The throwing constructor stays for callers that prefer
/// exceptions; it throws std::runtime_error if the path cannot
/// be opened for append.
class FileLogger final : public Logger
{
public:
@@ -35,6 +20,9 @@ namespace Void::Logging
Mode mode = Mode::Async,
std::size_t capacity = 512);
explicit FileLogger(const std::filesystem::path& path,
LoggerOptions options);
~FileLogger() noexcept override;
FileLogger(const FileLogger&) = delete;
@@ -42,21 +30,30 @@ namespace Void::Logging
FileLogger(FileLogger&&) = delete;
FileLogger& operator=(FileLogger&&) = delete;
/// Non-throwing factory. On failure returns
/// `Failure<Error>{Error{"FileLogger: cannot open '<path>'"}}`.
[[nodiscard]] static Void::Result::
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
open(const std::filesystem::path& path,
Mode mode = Mode::Async,
std::size_t capacity = 512);
/// Install a formatter replacing the default "[Level] message"
/// rendering. Call before logging starts.
[[nodiscard]] static Void::Result::
Result<std::unique_ptr<FileLogger>, Void::Result::Error>
open(const std::filesystem::path& path,
LoggerOptions options);
void set_formatter(std::shared_ptr<const Formatter> formatter)
{
m_formatter = std::move(formatter);
}
[[nodiscard]] Void::Result::Result<void> reopen();
[[nodiscard]] Void::Result::Result<void> sync_files() override;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
}
protected:
void write(const Entry& entry) override;
@@ -71,4 +68,4 @@ namespace Void::Logging
std::shared_ptr<const Formatter> m_formatter;
};
} // namespace Void::Logging
} // namespace Void::Logging
+73 -91
View File
@@ -1,8 +1,10 @@
#pragma once
#include <Void/Functional/Result.hpp>
#include <Void/Log/Entry.hpp>
#include <Void/Log/Level.hpp>
#include <cstddef>
#include <functional>
#include <string>
#include <string_view>
@@ -11,11 +13,6 @@
namespace Void::Logging
{
/// Renders one Entry into a single output line (no trailing newline —
/// the sink appends its own record separator).
///
/// Formatters must be safe to share between sinks: format() is const
/// and implementations hold no mutable state.
class Formatter
{
public:
@@ -26,8 +23,6 @@ namespace Void::Logging
format(const Entry& entry) const = 0;
};
// ── colour ────────────────────────────────────────────────────────────
enum class AnsiColor {
Default,
Black,
@@ -48,99 +43,24 @@ namespace Void::Logging
BrightWhite,
};
/// Parse a colour name ("red", "bright_black", "cyan", ...). Returns
/// AnsiColor::Default for unknown names.
[[nodiscard]] AnsiColor parse_color(std::string_view name) noexcept;
/// SGR escape for a colour ("\x1b[31m"); empty for Default.
[[nodiscard]] std::string_view ansi_code(AnsiColor color) noexcept;
inline constexpr std::string_view kAnsiReset = "\x1b[0m";
/// Colour configuration for a PatternFormatter. Disabled by default;
/// ConsoleLogger turns it on when the stream is a colour-capable TTY.
struct ColorPolicy {
bool enabled = false;
std::unordered_map<Level, AnsiColor> level_colors;
std::unordered_map<std::string, AnsiColor> token_colors;
/// Sensible per-level defaults (Trace dim → Fatal bright magenta).
[[nodiscard]] static ColorPolicy defaults();
};
// ── PatternFormatter ──────────────────────────────────────────────────
//
// Placeholder pattern with per-token appearance and colour.
//
// {token} — substitute the token
// {token:spec} — spec = [align][width][,colour]
// align : '<' left (default), '>' right, '^'
// centre width : decimal field width (padded with
// spaces) colour: a name ("cyan") or "auto" (=
// level colour)
//
// Built-in tokens: time, level, thread, scopes, message, file, line,
// kind. An unknown token resolves against registered custom tokens
// (register_token), then against Entry::fields by key, and otherwise
// stays literal — so `{request_id:>8}` prints a structured field.
//
// Default pattern: "{time} [{level}] {scopes}{message}"
class PatternFormatter final : public Formatter
{
public:
explicit PatternFormatter(
std::string pattern = "{time} [{level}] {scopes}{message}");
[[nodiscard]] std::string format(const Entry& entry) const override;
/// Add a custom token. `name` becomes usable as `{name}`.
/// Overrides a built-in of the same name.
void register_token(std::string name,
std::function<std::string(const Entry&)>
renderer);
void set_color_policy(ColorPolicy policy)
{
m_colors = std::move(policy);
}
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
{
return m_colors;
}
private:
enum class Align { Left, Right, Center };
enum class ColorMode { None, Auto, Fixed };
struct Segment {
bool literal{true};
std::string text; // literal text, or the token name
Align align{Align::Left};
std::size_t width{0};
ColorMode color_mode{ColorMode::None};
AnsiColor color{AnsiColor::Default};
};
[[nodiscard]] std::string render_token(const Segment& seg,
const Entry& entry) const;
std::vector<Segment> m_segments;
std::unordered_map<std::string,
std::function<std::string(const Entry&)>>
m_custom;
ColorPolicy m_colors;
};
/// An allow/deny list applied to an entry's structured fields by the
/// json/logfmt sinks. `include` empty means "all keys" (still subject to
/// `exclude`); a non-empty `include` admits only those keys. `exclude`
/// always wins.
struct FieldFilter {
std::vector<std::string> include;
std::vector<std::string> exclude;
std::vector<std::string> include{};
std::vector<std::string> exclude{};
std::vector<std::string> redact{};
std::string redaction_mask{"[REDACTED]"};
[[nodiscard]] bool allows(std::string_view key) const
{
@@ -159,9 +79,68 @@ namespace Void::Logging
}
return false;
}
[[nodiscard]] bool is_redacted(std::string_view key) const
{
for (const auto& r : redact) {
if (r == key) {
return true;
}
}
return false;
}
};
class PatternFormatter final : public Formatter
{
public:
explicit PatternFormatter(
std::string pattern = "{time} [{level}] {scopes}{message}");
[[nodiscard]] std::string format(const Entry& entry) const override;
void register_token(std::string name,
std::function<std::string(const Entry&)>
renderer);
void set_color_policy(ColorPolicy policy)
{
m_colors = std::move(policy);
}
[[nodiscard]] const ColorPolicy& color_policy() const noexcept
{
return m_colors;
}
void set_field_filter(FieldFilter f) { m_fields = std::move(f); }
private:
enum class Align { Left, Right, Center };
enum class ColorMode { None, Auto, Fixed };
struct Segment {
bool literal{true};
std::string text;
Align align{Align::Left};
std::size_t width{0};
ColorMode color_mode{ColorMode::None};
AnsiColor color{AnsiColor::Default};
};
[[nodiscard]] std::string render_token(const Segment& seg,
const Entry& entry) const;
std::vector<Segment> m_segments;
std::unordered_map<std::string,
std::function<std::string(const Entry&)>>
m_custom;
ColorPolicy m_colors;
FieldFilter m_fields;
};
/// One compact JSON object per entry (includes fields when present).
class JsonLinesFormatter final : public Formatter
{
public:
@@ -175,7 +154,6 @@ namespace Void::Logging
FieldFilter m_fields;
};
/// logfmt: time=... level=... thread=... msg="..." plus scopes/fields.
class LogfmtFormatter final : public Formatter
{
public:
@@ -189,15 +167,19 @@ namespace Void::Logging
FieldFilter m_fields;
};
[[nodiscard]] Void::Result::Result<std::string>
format_bounded(const Formatter& formatter,
const Entry& entry,
std::size_t max_bytes = 64ULL * 1024ULL,
bool truncate = false);
namespace FormatDetail
{
/// ISO-8601 UTC with milliseconds, e.g. "2026-06-12T10:30:00.123Z".
[[nodiscard]] std::string
iso8601(std::chrono::system_clock::time_point tp);
/// Dotted scope breadcrumb ("net.tls"); empty when no scopes.
[[nodiscard]] std::string
scope_breadcrumb(const std::vector<std::string>& scopes);
} // namespace FormatDetail
} // namespace Void::Logging
} // namespace Void::Logging
+208 -53
View File
@@ -1,8 +1,12 @@
#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>
@@ -11,6 +15,7 @@
#include <type_traits>
#include <unordered_map>
#include <utility>
#include <vector>
// ── Void::Log — the emission facade
// ─────────────────────────────────────────── Header-only apart from its
@@ -18,18 +23,6 @@
// 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.
//
// Integration contract:
// * No sink installed (the default) — every call is a single relaxed
// atomic load; format arguments are NOT formatted. This is the
// "no logging at all" path.
// * set_sink(...) routes everything to any callable — your own logging
// library plugs in here.
// * set_min_level(Level::Disabled) silences without removing the sink.
// * Per-module overrides: set_module_level("Fsm", Level::Trace).
//
// The API is deliberately macro-free: leveled function templates take a
// std::format_string and only format after the level/sink gate passes.
namespace Void::Log
{
@@ -44,23 +37,24 @@ namespace Void::Log
Disabled
};
/// Signature for any log consumer. Four arguments:
/// level — severity of the event
/// module — short library-internal label (e.g. "System.Process")
/// message — human-readable description
/// location — the call site that emitted the event (file/line/function)
/// 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
{
// std::source_location cannot follow a variadic pack in a parameter
// list, so this wrapper captures the format string together with the
// caller's source location in its (consteval) constructor.
// std::type_identity_t<Args>... keeps Args non-deduced here, so they
// are deduced solely from the trailing argument pack.
template <typename... Args> struct FmtLoc {
std::format_string<Args...> fmt;
std::source_location location;
@@ -74,36 +68,176 @@ namespace Void::Log
}
};
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.
Sink sink;
// 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;
};
// The process's one State, defined in Void::LogState (a static in an
// inline function would be one per DLL on Windows).
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 the global sink. Any previously installed sink is replaced.
/// Pass a default-constructed (empty) Sink to silence all output.
/// Thread-safe: the new sink is visible to all threads after this returns.
inline void set_sink(Sink sink)
/// 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::unique_lock lock{s.mutex};
s.sink = std::move(sink);
s.has_sink.store(static_cast<bool>(s.sink), std::memory_order_release);
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);
}
/// Global minimum level. Events below it are discarded before
/// formatting. Default: Trace (everything passes; the sink filters).
inline void set_min_level(Level level) noexcept
{
Detail::state().min_level.store(level, std::memory_order_relaxed);
@@ -114,8 +248,6 @@ namespace Void::Log
return Detail::state().min_level.load(std::memory_order_relaxed);
}
/// Per-module minimum level override (exact label match). Overrides take
/// precedence over the global minimum — they can both raise and lower it.
inline void set_module_level(std::string_view module, Level level)
{
auto& s = Detail::state();
@@ -124,7 +256,6 @@ namespace Void::Log
s.has_module_levels.store(true, std::memory_order_release);
}
/// Remove a per-module override.
inline void clear_module_level(std::string_view module)
{
auto& s = Detail::state();
@@ -134,7 +265,6 @@ namespace Void::Log
std::memory_order_release);
}
/// Would an event at `level` from `module` currently be emitted?
[[nodiscard]] inline bool enabled(Level level, std::string_view module)
{
auto& s = Detail::state();
@@ -154,15 +284,8 @@ namespace Void::Log
return level >= s.min_level.load(std::memory_order_relaxed);
}
/// Emit one pre-formatted log event through the global sink.
/// No-op (zero allocation) when disabled.
namespace Detail
{
// Single, non-overloaded dispatch to the sink. The formatted paths
// must forward through this rather than through log() itself: a
// log(level, module, std::string, source_location) call would also
// match the variadic log() overload (deducing source_location as a
// format argument) and fail in FmtLoc's consteval constructor.
inline void emit(Level level, std::string_view module,
std::string_view message,
const std::source_location& location)
@@ -171,10 +294,45 @@ namespace Void::Log
if (!::Void::Log::enabled(level, module)) {
return;
}
std::shared_lock lock{s.mutex};
if (s.sink) {
s.sink(level, module, message, location);
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
@@ -186,9 +344,6 @@ namespace Void::Log
Detail::emit(level, module, message, location);
}
/// Leveled, lazily-formatted emission: arguments are formatted only
/// after the level/sink gate passes. The call-site source location is
/// captured transparently via FmtLoc.
template <typename... Args>
void log(Level level, std::string_view module,
Detail::FmtLoc<std::type_identity_t<Args>...> fmt, Args&&... args)
@@ -243,4 +398,4 @@ namespace Void::Log
log(Level::Fatal, module, fmt, std::forward<Args>(args)...);
}
} // namespace Void::Log
} // namespace Void::Log
+244 -263
View File
@@ -1,18 +1,25 @@
#pragma once
#include "Void/Log/Field.hpp"
#include <Void/Async/MpscQueue.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 <semaphore>
#include <optional>
#include <set>
#include <source_location>
#include <span>
#include <string>
@@ -23,104 +30,159 @@
namespace Void::Logging
{
/// Dispatch strategy.
/// Async — (default) entries are queued lock-free and delivered in
/// batches by a logger-owned worker thread.
/// Immediate — write() is called inline on the logging thread.
/// Buffered — entries accumulate and flush at capacity / on flush().
enum class Mode { Async, Immediate, Buffered };
/// What happens in Async mode when pending entries reach capacity.
/// Block — (default) the logging thread waits for space; nothing
/// is ever lost.
/// DropNewest — the incoming entry is discarded.
/// DropOldest — the oldest pending entries are discarded by the worker
/// when it falls behind (soft bound: memory can briefly
/// exceed capacity until the next drain).
enum class OverflowPolicy { Block, DropNewest, DropOldest };
/// Abstract base class for all Void loggers.
///
/// ## Responsibilities
/// - Level filtering (thread-safe, lock-free gate)
/// - Entry construction: timestamp, thread_id, scope snapshot
/// - Dispatch: Async (default, lock-free queue + owned worker thread
/// delivering batches), Immediate (inline), or Buffered (flush at
/// capacity). Switch at runtime with set_mode() — no separate
/// async/sync classes.
/// - Thread-safe submission — virtual extension points are called
/// *outside* any internal lock (from the worker thread in Async
/// mode) 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.
///
/// ## Async mode notes
/// - capacity bounds the pending-entry queue; OverflowPolicy decides
/// what happens at the bound (Block by default — nothing is lost).
/// - flush() blocks until every entry submitted *before* the call has
/// been delivered.
/// - In Async mode write()/on_flush() run on the worker thread; sinks
/// need no additional synchronization of their own state.
///
/// ## 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 (the base destructor only stops and joins
/// the worker — it never invokes the virtuals).
/// 4. Stop logging from other threads before destroying the logger;
/// entries submitted concurrently with destruction are dropped.
///
/// ## 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
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:
// =========================================================================
// 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:
@@ -131,8 +193,6 @@ namespace Void::Logging
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;
@@ -146,23 +206,6 @@ namespace Void::Logging
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:
@@ -174,16 +217,11 @@ namespace Void::Logging
{
}
// 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
@@ -197,22 +235,6 @@ namespace Void::Logging
}
}
// =========================================================================
// 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;
@@ -227,12 +249,6 @@ namespace Void::Logging
}
};
// -----------------------------------------------------------------
// 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,
@@ -249,7 +265,6 @@ namespace Void::Logging
m_owner->log(m_level, msg, fwl.location);
}
// Accessors
[[nodiscard]] Level level() const noexcept
{
return m_level;
@@ -273,18 +288,13 @@ namespace Void::Logging
// =========================================================================
// Lifetime
// =========================================================================
/// @param mode Dispatch strategy; Async by default.
/// @param capacity Async: pending-queue bound (fixed for the
/// logger's lifetime). Buffered: auto-flush
/// threshold (adjustable).
/// @param policy Async overflow behaviour at capacity.
explicit Logger(
Mode mode = Mode::Async,
std::size_t capacity = 512,
OverflowPolicy policy = OverflowPolicy::Block) noexcept;
/// Stops and joins the worker thread (Async). Does NOT flush
/// remaining entries — see class-level note.
explicit Logger(LoggerOptions options);
virtual ~Logger() noexcept;
Logger(const Logger&) = delete;
@@ -293,103 +303,75 @@ namespace Void::Logging
Logger& operator=(Logger&&) = delete;
// =========================================================================
// Configuration (all setters are thread-safe)
// Configuration
// =========================================================================
/// 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 dispatch strategy at runtime (e.g. Async → Immediate
/// to make the logger synchronous). Pending entries are flushed
/// before the switch takes effect.
void set_mode(Mode mode) noexcept;
[[nodiscard]] Mode mode() const noexcept;
/// Maximum number of entries held before an automatic flush
/// (Buffered mode only; the Async queue bound is fixed at
/// construction).
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;
}
// =========================================================================
// Flush
// 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;
/// Deliver all pending entries. Async: blocks until everything
/// submitted before this call has been written. Buffered: drains
/// the buffer via on_flush(). Immediate: no-op. Thread-safe.
/// Virtual so composite sinks can propagate the flush to
/// children.
virtual void flush();
// =========================================================================
// Scoped context
// =========================================================================
[[nodiscard]] LoggerStats stats() const;
[[nodiscard]] bool is_quarantined() const noexcept;
[[nodiscard]] std::string last_error_summary() const;
void reset_quarantine() noexcept;
/// 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).
// =========================================================================
// Scoped context & Presets
// =========================================================================
[[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
// Core & Formatted Logging (legacy compatibility adapters)
// =========================================================================
inline void log(
Level level, std::string_view message,
std::source_location location = std::source_location::current())
{
// Early level check outside the lock to avoid allocations on
// the hot path.
{
std::lock_guard lock(m_mutex);
if (level < m_level) {
return;
}
if (level < m_level.load(std::memory_order_relaxed)) {
return;
}
const auto fields = current_fields();
Entry entry{
.kind = Kind::Message,
@@ -398,7 +380,6 @@ namespace Void::Logging
.timestamp = std::chrono::system_clock::now(),
.location = location,
.thread_id = std::this_thread::get_id(),
// Snapshot here through the existing DLL function boundary.
.scopes = [] {
const auto scopes = Logger::current_scopes();
return std::vector<std::string>(
@@ -406,14 +387,9 @@ namespace Void::Logging
}(),
.fields = {fields.begin(), fields.end()},
};
submit(std::move(entry));
(void)try_submit(std::move(entry));
}
/// Route a fully-built Entry through this logger's level filter
/// and dispatch (queue / buffer / inline write). Meant for
/// composite sinks (e.g. MultiLogger) that fan entries out to
/// children without re-stamping timestamp/thread/scopes.
void relay(Entry entry);
void trace(
@@ -435,10 +411,6 @@ namespace Void::Logging
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>...>
@@ -498,81 +470,90 @@ namespace Void::Logging
log(Level::Fatal, fwl, std::forward<Args>(args)...);
}
[[nodiscard]] virtual Void::Result::Result<void> sync_files();
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 the queue, write() or the
/// buffer depending on the active mode.
void submit(Entry entry);
enum class TerminalOutcome : std::uint8_t {
Delivered = 0,
Dropped,
Failed
};
/// Async path: bounded enqueue honoring the overflow policy.
void async_submit(Entry entry);
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;
/// Start the worker thread on first use (Async mode).
void start_worker();
/// Wake the worker if it parked itself.
void wake_worker() noexcept;
/// Worker: drain → on_flush batches → park when idle.
void worker_loop();
/// Async: block until everything submitted so far is written.
void drain_async();
/// Emit a raw scope boundary entry; shared by push_scope and
/// scope().
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;
std::size_t m_async_capacity;
OverflowPolicy m_policy;
mutable std::mutex m_mutex;
std::vector<Entry> m_buffer; // Buffered mode only
LoggerOptions m_options;
std::size_t m_buffer_capacity;
// ── Async machinery ──────────────────────────────────────────
Void::Async::MpscQueue<Entry> m_queue;
std::counting_semaphore<> m_space; // Block policy bound
// Counting (not binary): the worker's un-park path can leave a
// stale token behind, and a fresh release on top of it must
// not overflow. Extra tokens only cause spurious wakes, which
// the worker loop absorbs.
std::counting_semaphore<> m_wakeup{0};
std::atomic<bool> m_sleeping{false};
std::atomic<bool> m_stop{false};
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::uint64_t> m_submitted{0};
std::atomic<std::uint64_t> m_completed{0};
std::atomic<std::thread::id> m_worker_id{};
/// Per-thread scope stack. ScopedContext pushes/pops into this.
static thread_local std::vector<std::string> s_scope_stack;
};
} // namespace Void::Logging
} // namespace Void::Logging
+17 -12
View File
@@ -13,21 +13,25 @@
namespace Void::Logging
{
/// File sink with size-based rotation.
///
/// When the current file reaches `max_bytes` after a batch, files are
/// shifted (`app.log` → `app.log.1` → `app.log.2` …); at most
/// `max_files` rotated files are kept, the oldest is deleted.
///
/// Defaults to Async dispatch — rotation and writes happen on the
/// worker thread. An optional Formatter overrides the default
/// "[Level] message" rendering; set it before logging starts.
struct RotatingFileOptions {
std::size_t max_bytes = 1024 * 1024;
std::size_t max_files = 5;
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::Block;
bool create_directories = true;
[[nodiscard]] static constexpr RotatingFileOptions
roadmap_defaults() noexcept
{
return RotatingFileOptions{
.max_bytes = 16ULL * 1024ULL * 1024ULL,
.max_files = 5,
.mode = Mode::Async,
.capacity = 4096,
.policy = OverflowPolicy::DropNewest,
.create_directories = false};
}
};
class RotatingFileLogger final : public Logger
@@ -46,17 +50,18 @@ namespace Void::Logging
RotatingFileLogger(RotatingFileLogger&&) = delete;
RotatingFileLogger& operator=(RotatingFileLogger&&) = delete;
/// Non-throwing factory.
[[nodiscard]] static Void::Result::
Result<std::unique_ptr<RotatingFileLogger>, Void::Result::Error>
open(const std::filesystem::path& path, Options options = {});
/// Install a formatter. Call before logging starts.
void set_formatter(std::shared_ptr<const Formatter> formatter)
{
m_formatter = std::move(formatter);
}
[[nodiscard]] Void::Result::Result<void> reopen();
[[nodiscard]] Void::Result::Result<void> sync_files() override;
[[nodiscard]] const std::filesystem::path& path() const noexcept
{
return m_path;
@@ -76,4 +81,4 @@ namespace Void::Logging
std::shared_ptr<const Formatter> m_formatter;
};
} // namespace Void::Logging
} // namespace Void::Logging
+79 -13
View File
@@ -9,12 +9,17 @@
namespace Void::Logging
{
/// Discards everything. Useful as a placeholder or for benchmarks.
inline constexpr std::size_t kDefaultMaxFanoutChildren = 8;
class NullLogger final : public Logger
{
public:
explicit NullLogger(Mode mode = Mode::Immediate) : Logger(mode) {}
explicit NullLogger(LoggerOptions options)
: Logger(std::move(options))
{
}
~NullLogger() noexcept override { flush(); }
@@ -23,8 +28,6 @@ namespace Void::Logging
void write(const Entry&) override {}
};
/// Forwards every entry to a user callback. The simplest way to splice
/// an external logging library into the Logger framework.
class CallbackLogger final : public Logger
{
public:
@@ -41,6 +44,11 @@ namespace Void::Logging
{
}
explicit CallbackLogger(Callback callback, LoggerOptions options)
: Logger(std::move(options)), m_callback(std::move(callback))
{
}
~CallbackLogger() noexcept override { flush(); }
protected:
@@ -57,10 +65,6 @@ namespace Void::Logging
Callback m_callback;
};
/// Tee: relays every entry to each child logger. Children keep their
/// own modes, levels, and formatters. The MultiLogger itself defaults
/// to Immediate dispatch — the children already decide whether they
/// queue asynchronously, so double-queueing only adds latency.
class MultiLogger final : public Logger
{
public:
@@ -72,15 +76,41 @@ namespace Void::Logging
{
}
explicit MultiLogger(
std::vector<std::shared_ptr<Logger>> children,
LoggerOptions options)
: Logger(std::move(options)), m_children(std::move(children))
{
}
~MultiLogger() noexcept override { flush(); }
/// Add a child sink. Not thread-safe with concurrent logging —
/// assemble the tree before use.
void add(std::shared_ptr<Logger> child)
{
if (child) {
m_children.push_back(std::move(child));
(void)try_add(std::move(child));
}
[[nodiscard]] Void::Result::Result<void>
try_add(std::shared_ptr<Logger> child,
std::size_t max_children = kDefaultMaxFanoutChildren)
{
if (!child) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"MultiLogger::try_add: null child"));
}
if (m_children.size() >= max_children) {
return Void::Result::fail(make_log_error(
LogErrorCode::queue_full,
"MultiLogger child fan-out limit exceeded"));
}
if (reaches_self(*child)) {
return Void::Result::fail(make_log_error(
LogErrorCode::cycle_detected,
"MultiLogger fan-out cycle detected"));
}
m_children.push_back(std::move(child));
return {};
}
[[nodiscard]] std::size_t child_count() const noexcept
@@ -88,7 +118,6 @@ namespace Void::Logging
return m_children.size();
}
/// Flush own pending entries, then every child.
void flush() override
{
Logger::flush();
@@ -97,6 +126,26 @@ namespace Void::Logging
}
}
[[nodiscard]] Void::Result::Result<void> sync_files() override
{
if (m_children.empty()) {
return Logger::sync_files();
}
bool any_synced = false;
for (const auto& child : m_children) {
auto res = child->sync_files();
if (res) {
any_synced = true;
} else if (res.error().code().value !=
static_cast<std::int32_t>(
LogErrorCode::unsupported_capability)) {
return res;
}
}
return any_synced ? Void::Result::Result<void>{}
: Logger::sync_files();
}
protected:
void write(const Entry& entry) override
@@ -108,7 +157,24 @@ namespace Void::Logging
private:
[[nodiscard]] bool reaches_self(const Logger& candidate) const
{
if (&candidate == this) {
return true;
}
const auto* nested = dynamic_cast<const MultiLogger*>(&candidate);
if (nested == nullptr) {
return false;
}
for (const auto& grandchild : nested->m_children) {
if (grandchild && reaches_self(*grandchild)) {
return true;
}
}
return false;
}
std::vector<std::shared_ptr<Logger>> m_children;
};
} // namespace Void::Logging
} // namespace Void::Logging
+201 -18
View File
@@ -1,31 +1,214 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <optional>
#include <ostream>
#include <stop_token>
#include <string>
#include <string_view>
#include <vector>
namespace Void::Stacktrace
{
struct StackFrame {
std::string function_name;
std::string source_file;
int source_line{0};
std::string source_snippet;
};
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames = 0,
unsigned max_frames = 32);
inline constexpr std::size_t kMaxCaptureFrames = 256;
inline constexpr std::size_t kDefaultMaxSnippetBytes = 4096;
inline constexpr std::size_t kDefaultMaxRenderedBytes = 65536;
inline constexpr std::size_t kDefaultMaxSourceScanBytes = 1048576;
inline constexpr std::size_t kDefaultMaxLineLength = 4096;
inline constexpr std::size_t kDefaultResolverCacheEntries = 1024;
inline constexpr std::size_t kDefaultResolverCacheBytes = 4ULL * 1024ULL * 1024ULL;
/// Read a snippet of source around `line`. On failure (file missing,
/// not readable, etc.) returns Failure<Error> instead of an empty
/// string — callers that want the silent fallback can still do
/// `read_source_snippet(...).value_or("")`.
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file, int line,
int context_lines = 3);
enum class StacktraceErrorCode : std::int32_t {
invalid_argument = 1,
unsafe_path = 2,
source_unreadable = 3,
scan_limit_exceeded = 4,
cancelled = 5,
timeout = 6,
backend_failed = 7
};
[[nodiscard]] inline Void::Result::Error
make_stacktrace_error(StacktraceErrorCode code, std::string message = {})
{
using Void::Result::Error;
using Void::Result::ErrorCode;
using Void::Result::ErrorKind;
ErrorKind kind = ErrorKind::internal;
switch (code) {
case StacktraceErrorCode::invalid_argument:
case StacktraceErrorCode::unsafe_path:
kind = ErrorKind::invalid_argument;
break;
case StacktraceErrorCode::source_unreadable:
kind = ErrorKind::not_found;
break;
case StacktraceErrorCode::scan_limit_exceeded:
kind = ErrorKind::exhausted;
break;
case StacktraceErrorCode::cancelled:
kind = ErrorKind::cancelled;
break;
case StacktraceErrorCode::timeout:
kind = ErrorKind::timeout;
break;
case StacktraceErrorCode::backend_failed:
kind = ErrorKind::internal;
break;
}
return Error{
kind,
std::move(message),
ErrorCode{Void::Result::kStacktraceErrorDomain,
static_cast<std::int32_t>(code)}};
}
struct Capabilities {
bool raw_capture{true};
bool symbols{true};
bool line_info{true};
bool async_signal_safe{false};
std::string_view backend_name{"boost.stacktrace"};
};
[[nodiscard]] Capabilities capabilities() noexcept;
struct CaptureOptions {
unsigned skip{0};
unsigned max_frames{32};
};
struct RawFrame {
std::uintptr_t address{0};
std::uintptr_t module_offset{0};
std::string module_path{};
std::string module_id{};
};
struct RawTrace {
std::vector<RawFrame> frames{};
bool truncated{false};
};
/// Capture raw instruction addresses and owned module identity metadata without
/// reading source files or emitting Void::Log events.
[[nodiscard]] Void::Result::Result<RawTrace>
capture(CaptureOptions options = {});
enum class FrameResolveStatus : std::uint8_t {
resolved = 0,
symbols_only,
unresolved,
unsupported,
cancelled,
timed_out
};
struct ResolveOptions {
bool resolve_symbols{true};
bool source_snippets{false};
std::vector<std::filesystem::path> allowed_source_roots{};
std::vector<std::string> redact_prefixes{};
int context_lines{3};
std::size_t max_snippet_bytes{kDefaultMaxSnippetBytes};
std::size_t max_bytes{kDefaultMaxRenderedBytes};
std::size_t max_source_scan_bytes{kDefaultMaxSourceScanBytes};
std::size_t max_line_bytes{kDefaultMaxLineLength};
std::stop_token stop{};
std::optional<Void::Time::MonotonicClock::time_point> deadline{};
const Void::Time::MonotonicClock* clock{
&Void::Time::SystemMonotonicClock::instance()};
};
struct ResolvedFrame {
RawFrame raw{};
std::string function_name{};
std::string source_file{};
int source_line{0};
std::string source_snippet{};
FrameResolveStatus status{FrameResolveStatus::unresolved};
std::optional<Void::Result::Error> diagnostic{};
};
struct ResolvedTrace {
std::vector<ResolvedFrame> frames{};
bool truncated{false};
bool incomplete{false};
std::size_t rendered_bytes{0};
};
/// Stateful bounded LRU resolver cache keyed by owned (module_id, module_offset).
class Resolver
{
public:
explicit Resolver(std::size_t max_entries = kDefaultResolverCacheEntries,
std::size_t max_bytes = kDefaultResolverCacheBytes);
~Resolver();
Resolver(const Resolver&) = delete;
Resolver& operator=(const Resolver&) = delete;
Resolver(Resolver&&) noexcept = delete;
Resolver& operator=(Resolver&&) noexcept = delete;
[[nodiscard]] Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options = {});
std::size_t invalidate_module(std::string_view module_id);
void clear_cache();
[[nodiscard]] std::size_t cache_entries() const;
[[nodiscard]] std::size_t cache_bytes() const;
private:
struct Impl;
std::unique_ptr<Impl> impl_;
};
[[nodiscard]] Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options = {});
[[nodiscard]] Void::Result::Result<std::string>
read_source_snippet_checked(const std::filesystem::path& file,
int line,
const ResolveOptions& options);
[[nodiscard]] std::string format_resolved_trace(
const ResolvedTrace& trace,
std::size_t max_bytes = kDefaultMaxRenderedBytes);
/// Async-signal-safe fixed-buffer fatal diagnostic marker writer using only
/// stack storage and raw descriptor write().
bool write_fatal_signal_marker(int fd, int sig) noexcept;
// ── Legacy compatibility API ─────────────────────────────────────────────────
struct StackFrame {
std::string function_name;
std::string source_file;
int source_line{0};
std::string source_snippet;
};
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames = 0,
unsigned max_frames = 32);
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file,
int line,
int context_lines = 3);
std::string format_stacktrace(const std::vector<StackFrame>& frames);
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames);
std::string format_stacktrace(const std::vector<StackFrame>& frames);
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames);
} // namespace Void::Stacktrace
+119 -8
View File
@@ -1,7 +1,15 @@
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Log.hpp>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <format>
#include <mutex>
#include <stdexcept>
namespace Void::Logging
@@ -20,6 +28,18 @@ namespace Void::Logging
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
}
FileLogger::FileLogger(const std::filesystem::path& path,
LoggerOptions options)
: Logger(std::move(options)), m_path(path), m_file(path, std::ios::app)
{
if (!m_file.is_open()) {
Void::Log::warn("Logging", "FileLogger: cannot open '{}'", path.string());
throw std::runtime_error(
std::format("FileLogger: cannot open '{}'", path.string()));
}
Void::Log::debug("Logging", "FileLogger: opened '{}'", path.string());
}
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
FileLogger::open(const std::filesystem::path& path,
Mode mode,
@@ -29,7 +49,21 @@ namespace Void::Logging
return Void::Result::ok(
std::make_unique<FileLogger>(path, mode, capacity));
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
Void::Result::Result<std::unique_ptr<FileLogger>, Void::Result::Error>
FileLogger::open(const std::filesystem::path& path,
LoggerOptions options)
{
try {
return Void::Result::ok(
std::make_unique<FileLogger>(path, std::move(options)));
} catch (const std::exception& e) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
@@ -37,13 +71,70 @@ namespace Void::Logging
{
flush();
Void::Log::debug("Logging", "FileLogger: closed '{}'",
m_path.string());
m_path.string());
}
Void::Result::Result<void> FileLogger::reopen()
{
flush();
m_file.close();
m_file.clear();
m_file.open(m_path, std::ios::app);
if (!m_file.is_open()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::reopen failed for '{}'",
m_path.string())));
}
return {};
}
Void::Result::Result<void> FileLogger::sync_files()
{
flush();
if (is_quarantined()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, last_error_summary()));
}
m_file.flush();
if (!m_file.good()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files flush failure for '{}'",
m_path.string())));
}
#ifndef _WIN32
const int fd = ::open(m_path.c_str(), O_RDONLY);
if (fd < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files open('{}') failed: {}",
m_path.string(), std::strerror(errno))));
}
int rc = 0;
do {
rc = ::fsync(fd);
} while (rc < 0 && errno == EINTR);
const int saved_err = errno;
::close(fd);
if (rc < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("FileLogger::sync_files fsync('{}') failed: {}",
m_path.string(), std::strerror(saved_err))));
}
#endif
return {};
}
void FileLogger::write(const Entry& entry)
{
append(entry);
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: flush failure on '{}'", m_path.string()));
}
}
void FileLogger::on_flush(std::span<const Entry> entries)
@@ -52,17 +143,37 @@ namespace Void::Logging
append(e);
}
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: batch flush failure on '{}'", m_path.string()));
}
}
void FileLogger::append(const Entry& entry)
{
if (m_formatter) {
m_file << m_formatter->format(entry) << '\n';
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"FileLogger: file not open for '{}'", m_path.string()));
}
else {
m_file << std::format(
"[{}] {}\n", to_string(entry.level), entry.message);
std::string line;
if (m_formatter) {
auto bounded = format_bounded(
*m_formatter,
entry,
delivery_limits().max_format_scratch_bytes,
delivery_limits().truncate_oversize);
if (!bounded) {
throw std::runtime_error(bounded.error().message());
}
line = std::move(*bounded);
} else {
line = std::format("[{}] {}", to_string(entry.level), entry.message);
}
m_file << line << '\n';
if (!m_file.good()) {
throw std::runtime_error(std::format(
"FileLogger: write failure on '{}'", m_path.string()));
}
}
} // namespace Void::Logging
} // namespace Void::Logging
+114 -73
View File
@@ -1,9 +1,11 @@
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Logger.hpp>
#include <Void/Data/Json.hpp>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <format>
#include <sstream>
@@ -12,8 +14,6 @@
namespace Void::Logging
{
// ── colour ────────────────────────────────────────────────────────────
AnsiColor parse_color(std::string_view name) noexcept
{
struct Pair {
@@ -43,7 +43,6 @@ namespace Void::Logging
return c;
}
}
// "dim"/"gray" aliases
if (name == "dim" || name == "gray" || name == "grey") {
return AnsiColor::BrightBlack;
}
@@ -53,40 +52,23 @@ namespace Void::Logging
std::string_view ansi_code(AnsiColor color) noexcept
{
switch (color) {
case AnsiColor::Default:
return "";
case AnsiColor::Black:
return "\x1b[30m";
case AnsiColor::Red:
return "\x1b[31m";
case AnsiColor::Green:
return "\x1b[32m";
case AnsiColor::Yellow:
return "\x1b[33m";
case AnsiColor::Blue:
return "\x1b[34m";
case AnsiColor::Magenta:
return "\x1b[35m";
case AnsiColor::Cyan:
return "\x1b[36m";
case AnsiColor::White:
return "\x1b[37m";
case AnsiColor::BrightBlack:
return "\x1b[90m";
case AnsiColor::BrightRed:
return "\x1b[91m";
case AnsiColor::BrightGreen:
return "\x1b[92m";
case AnsiColor::BrightYellow:
return "\x1b[93m";
case AnsiColor::BrightBlue:
return "\x1b[94m";
case AnsiColor::BrightMagenta:
return "\x1b[95m";
case AnsiColor::BrightCyan:
return "\x1b[96m";
case AnsiColor::BrightWhite:
return "\x1b[97m";
case AnsiColor::Default: return "";
case AnsiColor::Black: return "\x1b[30m";
case AnsiColor::Red: return "\x1b[31m";
case AnsiColor::Green: return "\x1b[32m";
case AnsiColor::Yellow: return "\x1b[33m";
case AnsiColor::Blue: return "\x1b[34m";
case AnsiColor::Magenta: return "\x1b[35m";
case AnsiColor::Cyan: return "\x1b[36m";
case AnsiColor::White: return "\x1b[37m";
case AnsiColor::BrightBlack: return "\x1b[90m";
case AnsiColor::BrightRed: return "\x1b[91m";
case AnsiColor::BrightGreen: return "\x1b[92m";
case AnsiColor::BrightYellow: return "\x1b[93m";
case AnsiColor::BrightBlue: return "\x1b[94m";
case AnsiColor::BrightMagenta: return "\x1b[95m";
case AnsiColor::BrightCyan: return "\x1b[96m";
case AnsiColor::BrightWhite: return "\x1b[97m";
}
return "";
}
@@ -103,13 +85,10 @@ namespace Void::Logging
{Level::Error, AnsiColor::BrightRed},
{Level::Fatal, AnsiColor::BrightMagenta},
};
// The level token defaults to the level's own colour.
p.token_colors = {};
return p;
}
// ── FormatDetail ──────────────────────────────────────────────────────
namespace FormatDetail
{
@@ -143,12 +122,9 @@ namespace Void::Logging
std::string_view kind_str(Kind kind)
{
switch (kind) {
case Kind::Message:
return "Message";
case Kind::ScopeEnter:
return "ScopeEnter";
case Kind::ScopeExit:
return "ScopeExit";
case Kind::Message: return "Message";
case Kind::ScopeEnter: return "ScopeEnter";
case Kind::ScopeExit: return "ScopeExit";
}
return "?";
}
@@ -168,7 +144,7 @@ namespace Void::Logging
const std::string* found = nullptr;
for (const auto& [k, v] : entry.fields) {
if (k == key) {
found = &v; // later duplicates win
found = &v;
}
}
return found;
@@ -177,8 +153,6 @@ namespace Void::Logging
} // namespace FormatDetail
// ── PatternFormatter ──────────────────────────────────────────────────
PatternFormatter::PatternFormatter(std::string pattern)
{
std::string literal;
@@ -206,10 +180,9 @@ namespace Void::Logging
literal += rest;
break;
}
const auto body = rest.substr(1, close - 1); // inside braces
const auto body = rest.substr(1, close - 1);
rest.remove_prefix(close + 1);
// Split "token:spec".
std::string_view token = body;
std::string_view spec;
if (const auto colon = body.find(':');
@@ -222,7 +195,6 @@ namespace Void::Logging
seg.literal = false;
seg.text = std::string{token};
// spec = [align][width][,colour]
std::string_view color_name;
if (const auto comma = spec.find(',');
comma != std::string_view::npos) {
@@ -292,15 +264,18 @@ namespace Void::Logging
if (name == "kind") {
return std::string{kind_str(entry.kind)};
}
// Custom token?
if (const auto it = m_custom.find(name); it != m_custom.end()) {
return it->second(entry);
}
// Structured field?
if (const auto* v = find_field(entry, name)) {
if (!m_fields.allows(name)) {
return {};
}
if (m_fields.is_redacted(name)) {
return m_fields.redaction_mask;
}
return *v;
}
// Unknown — keep literal so misspellings are visible.
return "{" + name + "}";
}
@@ -315,7 +290,6 @@ namespace Void::Logging
std::string text = render_token(seg, entry);
// Width / alignment.
if (seg.width > text.size()) {
const std::size_t pad = seg.width - text.size();
switch (seg.align) {
@@ -337,7 +311,6 @@ namespace Void::Logging
}
}
// Colour.
if (m_colors.enabled && seg.color_mode != ColorMode::None) {
AnsiColor color = AnsiColor::Default;
if (seg.color_mode == ColorMode::Auto) {
@@ -355,7 +328,6 @@ namespace Void::Logging
continue;
}
}
// Per-token colour from the policy (no inline ,colour spec).
if (m_colors.enabled && seg.color_mode == ColorMode::None) {
if (const auto it = m_colors.token_colors.find(seg.text);
it != m_colors.token_colors.end() &&
@@ -371,8 +343,6 @@ namespace Void::Logging
return out;
}
// ── JsonLinesFormatter ────────────────────────────────────────────────
std::string JsonLinesFormatter::format(const Entry& entry) const
{
auto obj = Json::object();
@@ -383,6 +353,9 @@ namespace Void::Logging
o.emplace_back("kind", Json::Value{FormatDetail::kind_str(entry.kind)});
o.emplace_back("thread",
Json::Value{FormatDetail::thread_str(entry.thread_id)});
if (entry.truncated) {
o.emplace_back("truncated", Json::Value{true});
}
if (!entry.scopes.empty()) {
auto arr = Json::array();
arr.as_array().reserve(entry.scopes.size());
@@ -397,7 +370,11 @@ namespace Void::Logging
if (!m_fields.allows(k)) {
continue;
}
fobj.as_object().emplace_back(k, Json::Value{v});
fobj.as_object().emplace_back(
k,
Json::Value{m_fields.is_redacted(k)
? m_fields.redaction_mask
: v});
}
if (!fobj.as_object().empty()) {
o.emplace_back("fields", std::move(fobj));
@@ -408,26 +385,56 @@ namespace Void::Logging
o.emplace_back("file", Json::Value{file});
o.emplace_back(
"line",
Json::Value{static_cast<double>(entry.location.line())});
Json::Value{static_cast<std::int64_t>(entry.location.line())});
}
return Json::serialize(obj);
}
// ── LogfmtFormatter ───────────────────────────────────────────────────
namespace
{
void append_quoted(std::string& out, std::string_view value)
{
out += '"';
for (const char c : value) {
if (c == '"' || c == '\\') {
out += '\\';
for (const unsigned char uc : value) {
switch (uc) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (uc < 0x20 || uc == 0x7F) {
out += std::format("\\u{:04x}", uc);
} else {
out += static_cast<char>(uc);
}
break;
}
out += c;
}
out += '"';
}
[[nodiscard]] bool is_safe_bare_token(std::string_view sv) noexcept
{
if (sv.empty()) {
return false;
}
for (const unsigned char uc : sv) {
if (uc <= 0x20 || uc == 0x7F || uc == '=' || uc == '"') {
return false;
}
}
return true;
}
void append_key_or_token(std::string& out, std::string_view token)
{
if (is_safe_bare_token(token)) {
out += token;
} else {
append_quoted(out, token);
}
}
} // namespace
std::string LogfmtFormatter::format(const Entry& entry) const
@@ -439,23 +446,27 @@ namespace Void::Logging
out += to_string(entry.level);
out += " thread=";
out += FormatDetail::thread_str(entry.thread_id);
if (entry.truncated) {
out += " truncated=true";
}
if (auto crumb = FormatDetail::scope_breadcrumb(entry.scopes);
!crumb.empty()) {
out += " scopes=";
out += crumb;
append_key_or_token(out, crumb);
}
for (const auto& [k, v] : entry.fields) {
if (!m_fields.allows(k)) {
continue;
}
out += ' ';
out += k;
append_key_or_token(out, k);
out += '=';
append_quoted(out, v);
append_quoted(
out, m_fields.is_redacted(k) ? m_fields.redaction_mask : v);
}
if (auto file = FormatDetail::file_basename(entry); !file.empty()) {
out += " file=";
out += file;
append_key_or_token(out, file);
out += ':';
out += std::to_string(entry.location.line());
}
@@ -464,4 +475,34 @@ namespace Void::Logging
return out;
}
} // namespace Void::Logging
Void::Result::Result<std::string>
format_bounded(const Formatter& formatter,
const Entry& entry,
std::size_t max_bytes,
bool truncate)
{
if (max_bytes == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"format_bounded requires max_bytes > 0"));
}
std::string rendered = formatter.format(entry);
if (rendered.size() <= max_bytes) {
return rendered;
}
if (!truncate) {
return Void::Result::fail(make_log_error(
LogErrorCode::entry_too_large,
"Formatted log entry exceeds max_format_scratch_bytes"));
}
constexpr std::string_view kMarker = "...[truncated]";
if (max_bytes <= kMarker.size()) {
rendered.resize(max_bytes);
return rendered;
}
rendered.resize(max_bytes - kMarker.size());
rendered += kMarker;
return rendered;
}
} // namespace Void::Logging
-325
View File
@@ -1,325 +0,0 @@
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/SyslogLogger.hpp>
#include <format>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace Void::Logging
{
namespace
{
std::vector<std::string> split_list(std::string_view csv)
{
std::vector<std::string> out;
std::size_t start = 0;
while (start <= csv.size()) {
auto comma = csv.find(',', start);
if (comma == std::string_view::npos) {
comma = csv.size();
}
auto item = csv.substr(start, comma - start);
while (!item.empty() && item.front() == ' ') {
item.remove_prefix(1);
}
while (!item.empty() && item.back() == ' ') {
item.remove_suffix(1);
}
if (!item.empty()) {
out.emplace_back(item);
}
start = comma + 1;
}
return out;
}
std::optional<Level> parse_level(std::string_view name)
{
std::string lower;
for (const char c : name) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "trace") {
return Level::Trace;
}
if (lower == "debug") {
return Level::Debug;
}
if (lower == "info") {
return Level::Info;
}
if (lower == "warning" || lower == "warn") {
return Level::Warning;
}
if (lower == "error") {
return Level::Error;
}
if (lower == "fatal") {
return Level::Fatal;
}
if (lower == "disabled" || lower == "off") {
return Level::Disabled;
}
return std::nullopt;
}
std::optional<Void::Log::Level>
parse_facade_level(std::string_view name)
{
const auto l = parse_level(name);
if (!l.has_value()) {
return std::nullopt;
}
switch (*l) {
case Level::Trace:
return Void::Log::Level::Trace;
case Level::Debug:
return Void::Log::Level::Debug;
case Level::Info:
return Void::Log::Level::Info;
case Level::Warning:
return Void::Log::Level::Warning;
case Level::Error:
return Void::Log::Level::Error;
case Level::Fatal:
return Void::Log::Level::Fatal;
case Level::Disabled:
return Void::Log::Level::Disabled;
}
return std::nullopt;
}
// Field allow/deny lists for the structured (json/logfmt) sinks, from
// the per-sink keys `fields.include` / `fields.exclude` (comma lists).
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
return f;
}
std::shared_ptr<const Formatter>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "pattern") {
auto fmt =
std::make_shared<PatternFormatter>(std::string{cfg.get_or(
"pattern", "{time} [{level}] {scopes}{message}")});
if (cfg.get_or_as<bool>("color", false)) {
fmt->set_color_policy(ColorPolicy::defaults());
}
return fmt;
}
if (format == "json") {
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
if (format == "logfmt") {
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return fmt;
}
return nullptr; // "default": per-sink built-in rendering
}
struct Dispatch {
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::Block;
};
Dispatch make_dispatch(const Configuration::Config& cfg)
{
Dispatch d;
if (!cfg.get_or_as<bool>("async", true)) {
d.mode = Mode::Immediate;
}
d.capacity = cfg.get_or_as<std::size_t>("capacity", 512);
const auto overflow = cfg.get_or("overflow", "block");
if (overflow == "drop_newest") {
d.policy = OverflowPolicy::DropNewest;
} else if (overflow == "drop_oldest") {
d.policy = OverflowPolicy::DropOldest;
}
return d;
}
} // namespace
Void::Result::Result<std::shared_ptr<Logger>, Void::Result::Error>
from_config(const Configuration::Config& cfg, std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
const auto dispatch = make_dispatch(sub);
const auto formatter = make_formatter(sub);
std::vector<std::shared_ptr<Logger>> sinks;
for (const auto& name : split_list(sub.get_or("sinks", "console"))) {
if (name == "console") {
const bool to_stdout =
sub.get_or("console.stream", "stderr") == "stdout";
auto sink = std::make_shared<ConsoleLogger>(
to_stdout ? std::cout : std::cerr, dispatch.mode,
dispatch.capacity);
if (formatter) {
sink->set_formatter(formatter);
}
sinks.push_back(std::move(sink));
} else if (name == "file") {
const auto path = sub.get_or("file.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'file' needs "
"file.path");
}
auto sink = FileLogger::open(std::filesystem::path{path},
dispatch.mode,
dispatch.capacity);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "rotating") {
const auto path = sub.get_or("rotating.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'rotating' needs "
"rotating.path");
}
RotatingFileLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("rotating.max_kb", 1024) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("rotating.max_files", 5);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
RotatingFileLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "split") {
const auto dir = sub.get_or("split.dir");
if (dir.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'split' needs "
"split.dir");
}
SplitFileLogger::Options opt;
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes =
sub.get_or_as<std::size_t>("split.max_kb", 1024) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("split.max_files", 5);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "history") {
const auto path = sub.get_or("history.path");
if (path.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'history' needs "
"history.path");
}
HistoryLogger::Options opt;
opt.max_bytes =
sub.get_or_as<std::size_t>("history.max_kb", 8192) * 1024;
opt.max_files =
sub.get_or_as<std::size_t>("history.max_files", 10);
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "syslog") {
#ifdef VOID_HAS_SYSLOG
const auto identity = sub.get_or("syslog.identity");
if (identity.empty()) {
return Void::Result::fail(
"Logging::from_config: sink 'syslog' needs "
"syslog.identity");
}
sinks.push_back(std::make_shared<SyslogLogger>(
std::string{identity}, dispatch.mode, dispatch.capacity));
#else
return Void::Result::fail(
"Logging::from_config: syslog is not available on "
"this platform");
#endif
} else {
return Void::Result::fail(std::format(
"Logging::from_config: unknown sink '{}'", name));
}
}
std::shared_ptr<Logger> root;
if (sinks.empty()) {
root = std::make_shared<NullLogger>();
} else if (sinks.size() == 1) {
root = std::move(sinks.front());
} else {
root = std::make_shared<MultiLogger>(std::move(sinks));
}
if (const auto level = parse_level(sub.get_or("level", "trace"));
level.has_value()) {
root->set_level(*level);
}
Void::Log::debug("Logging", "from_config: built logger tree");
return Void::Result::ok(std::move(root));
}
void apply_facade_config(const Configuration::Config& cfg,
std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
if (const auto level = parse_facade_level(sub.get_or("level", ""));
level.has_value()) {
Void::Log::set_min_level(*level);
}
for (const auto& key : sub.subtree("module_levels").keys()) {
const auto value = sub.get_or(std::string{"module_levels."} + key);
if (const auto level = parse_facade_level(value);
level.has_value()) {
Void::Log::set_module_level(key, *level);
}
}
}
} // namespace Void::Logging
+712 -241
View File
File diff suppressed because it is too large. Load diff
+86 -10
View File
@@ -1,9 +1,18 @@
#include <Void/Log/Detail/RollingFile.hpp>
#include <Void/Log/Logger.hpp>
#ifndef _WIN32
#include <cerrno>
#include <cstring>
#include <fcntl.h>
#include <unistd.h>
#endif
#include <algorithm>
#include <chrono>
#include <ctime>
#include <format>
#include <stdexcept>
#include <system_error>
#include <utility>
#include <vector>
@@ -46,25 +55,46 @@ namespace Void::Logging::Detail
bool RollingFile::open()
{
std::error_code ec;
if (m_path.has_parent_path()) {
if (m_opt.create_directories && m_path.has_parent_path()) {
std::filesystem::create_directories(m_path.parent_path(), ec);
if (ec) {
return false;
}
}
if (std::filesystem::exists(m_path, ec)) {
m_current_bytes = static_cast<std::size_t>(
std::filesystem::file_size(m_path, ec));
} else {
m_current_bytes = 0;
}
m_file.clear();
m_file.open(m_path, std::ios::app);
m_creationTime = std::chrono::system_clock::now();
return m_file.is_open();
}
bool RollingFile::reopen()
{
if (m_file.is_open()) {
m_file.flush();
m_file.close();
}
m_file.clear();
return open();
}
void RollingFile::write(std::string_view line)
{
if (!m_file.is_open()) {
return;
throw std::runtime_error(std::format(
"RollingFile: stream closed for '{}'", m_path.string()));
}
m_file.write(line.data(), static_cast<std::streamsize>(line.size()));
m_file.put('\n');
if (!m_file.good()) {
throw std::runtime_error(std::format(
"RollingFile: write failure on '{}'", m_path.string()));
}
m_current_bytes += line.size() + 1;
if (m_self_rotate && m_current_bytes >= m_opt.max_bytes) {
rotate();
@@ -73,9 +103,46 @@ namespace Void::Logging::Detail
void RollingFile::flush()
{
if (m_file.is_open()) {
m_file.flush();
if (!m_file.is_open()) {
return;
}
m_file.flush();
if (!m_file.good()) {
throw std::runtime_error(std::format(
"RollingFile: flush failure on '{}'", m_path.string()));
}
}
Void::Result::Result<void> RollingFile::sync()
{
try {
flush();
} catch (const std::exception& e) {
return Void::Result::fail(
make_log_error(LogErrorCode::io_error, e.what()));
}
#ifndef _WIN32
const int fd = ::open(m_path.c_str(), O_RDONLY);
if (fd < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RollingFile::sync open('{}') failed: {}",
m_path.string(), std::strerror(errno))));
}
int rc = 0;
do {
rc = ::fsync(fd);
} while (rc < 0 && errno == EINTR);
const int saved_err = errno;
::close(fd);
if (rc < 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RollingFile::sync fsync('{}') failed: {}",
m_path.string(), std::strerror(saved_err))));
}
#endif
return {};
}
void RollingFile::rotate()
@@ -85,12 +152,15 @@ namespace Void::Logging::Detail
std::error_code ec;
if (m_opt.max_files > 0) {
// Create the history/ subdirectory next to the original file
auto parent = m_path.parent_path();
auto history_dir = parent / "history";
std::filesystem::create_directories(history_dir, ec);
if (ec) {
throw std::runtime_error(std::format(
"RollingFile: cannot create history dir '{}'",
history_dir.string()));
}
// Build new name: <stem>-<timestamp>.<ext>
auto stem = m_path.stem();
auto ext = m_path.extension();
auto new_filename = stem.string() + "-" +
@@ -98,19 +168,24 @@ namespace Void::Logging::Detail
auto archived = history_dir / new_filename;
std::filesystem::rename(m_path, archived, ec);
prune_archives(); // now looks inside history/
prune_archives();
} else {
std::filesystem::remove(m_path, ec);
}
m_file.clear();
m_file.open(m_path, std::ios::trunc);
if (!m_file.is_open()) {
throw std::runtime_error(std::format(
"RollingFile: reopen after rotate failed on '{}'",
m_path.string()));
}
m_current_bytes = 0;
m_creationTime = m_rotationTime;
}
void RollingFile::prune_archives()
{
// Prune only from the history/ subdirectory
auto parent = m_path.parent_path();
auto history_dir = parent / "history";
if (!std::filesystem::exists(history_dir)) {
@@ -132,7 +207,7 @@ namespace Void::Logging::Detail
}
}
} catch (const std::filesystem::filesystem_error&) {
return; // best-effort pruning only
return;
}
std::sort(archives.begin(), archives.end());
@@ -150,9 +225,10 @@ namespace Void::Logging::Detail
std::filesystem::create_directories(dir, ec);
std::filesystem::rename(m_path, dir / m_path.filename(), ec);
m_file.clear();
m_file.open(m_path, std::ios::trunc);
m_current_bytes = 0;
m_creationTime = m_rotationTime;
}
} // namespace Void::Logging::Detail
} // namespace Void::Logging::Detail
+51 -6
View File
@@ -9,9 +9,23 @@ namespace Void::Logging
RotatingFileLogger::RotatingFileLogger(const std::filesystem::path& path,
Options options)
: Logger(options.mode, options.capacity, options.policy), m_path(path),
m_file(path, Detail::RollingFileOptions{options.max_bytes,
options.max_files})
: Logger(LoggerOptions{
.mode = options.mode,
.policy = options.policy,
.limits = DeliveryLimits{
.entries = options.capacity > 0 ? options.capacity : 1,
.owned_bytes = std::max<std::size_t>(
8ULL * 1024ULL * 1024ULL,
(options.capacity > 0 ? options.capacity : 1) * 1024ULL),
.max_fields = 64,
.max_scopes = 64},
.failure_policy = FailurePolicy::Quarantine,
.suppress_reentrancy = false}),
m_path(path),
m_file(path,
Detail::RollingFileOptions{options.max_bytes,
options.max_files,
options.create_directories})
{
if (!m_file.open()) {
throw std::runtime_error(std::format(
@@ -29,12 +43,35 @@ namespace Void::Logging
return Void::Result::ok(
std::make_unique<RotatingFileLogger>(path, options));
} catch (const std::exception& e) {
return Void::Result::fail(std::string{e.what()});
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, std::string{e.what()}));
}
}
RotatingFileLogger::~RotatingFileLogger() noexcept { flush(); }
Void::Result::Result<void> RotatingFileLogger::reopen()
{
flush();
if (!m_file.reopen()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error,
std::format("RotatingFileLogger::reopen failed for '{}'",
m_path.string())));
}
return {};
}
Void::Result::Result<void> RotatingFileLogger::sync_files()
{
flush();
if (is_quarantined()) {
return Void::Result::fail(make_log_error(
LogErrorCode::io_error, last_error_summary()));
}
return m_file.sync();
}
void RotatingFileLogger::write(const Entry& entry)
{
append(entry);
@@ -52,11 +89,19 @@ namespace Void::Logging
void RotatingFileLogger::append(const Entry& entry)
{
if (m_formatter) {
m_file.write(m_formatter->format(entry));
auto bounded = format_bounded(
*m_formatter,
entry,
delivery_limits().max_format_scratch_bytes,
delivery_limits().truncate_oversize);
if (!bounded) {
throw std::runtime_error(bounded.error().message());
}
m_file.write(*bounded);
} else {
m_file.write(
std::format("[{}] {}", to_string(entry.level), entry.message));
}
}
} // namespace Void::Logging
} // namespace Void::Logging
+2 -2
View File
@@ -1,5 +1,5 @@
void_add_module(Log
INTERNAL_DEPS Async Core Data Functional Configuration LogState
INTERNAL_DEPS Async Core Data Functional Memory Time LogState
OPTIONAL_DEPS Stacktrace
EXCLUDE_HEADERS Void/Log/Log.hpp
EXCLUDE_HEADERS Void/Log/Log.hpp Void/Log/FromConfig.hpp
)
+449
View File
@@ -0,0 +1,449 @@
#include <Void/Log/FromConfig.hpp>
#include <Void/Log/ConsoleLogger.hpp>
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/History.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Log/SplitFileLogger.hpp>
#include <Void/Log/SyslogLogger.hpp>
#include <cctype>
#include <format>
#include <iostream>
#include <string>
#include <vector>
namespace Void::Logging
{
namespace
{
std::vector<std::string> split_list(std::string_view csv)
{
std::vector<std::string> out;
std::size_t start = 0;
while (start <= csv.size()) {
auto comma = csv.find(',', start);
if (comma == std::string_view::npos) {
comma = csv.size();
}
auto item = csv.substr(start, comma - start);
while (!item.empty() && item.front() == ' ') {
item.remove_prefix(1);
}
while (!item.empty() && item.back() == ' ') {
item.remove_suffix(1);
}
if (!item.empty()) {
out.emplace_back(item);
}
start = comma + 1;
}
return out;
}
std::optional<Level> parse_level(std::string_view name)
{
std::string lower;
for (const char c : name) {
lower += static_cast<char>(
std::tolower(static_cast<unsigned char>(c)));
}
if (lower == "trace") {
return Level::Trace;
}
if (lower == "debug") {
return Level::Debug;
}
if (lower == "info") {
return Level::Info;
}
if (lower == "warning" || lower == "warn") {
return Level::Warning;
}
if (lower == "error") {
return Level::Error;
}
if (lower == "fatal") {
return Level::Fatal;
}
if (lower == "disabled" || lower == "off") {
return Level::Disabled;
}
return std::nullopt;
}
std::optional<Void::Log::Level>
parse_facade_level(std::string_view name)
{
const auto l = parse_level(name);
if (!l.has_value()) {
return std::nullopt;
}
switch (*l) {
case Level::Trace: return Void::Log::Level::Trace;
case Level::Debug: return Void::Log::Level::Debug;
case Level::Info: return Void::Log::Level::Info;
case Level::Warning: return Void::Log::Level::Warning;
case Level::Error: return Void::Log::Level::Error;
case Level::Fatal: return Void::Log::Level::Fatal;
case Level::Disabled: return Void::Log::Level::Disabled;
}
return std::nullopt;
}
FieldFilter make_field_filter(const Configuration::Config& cfg)
{
FieldFilter f;
f.include = split_list(cfg.get_or("fields.include", ""));
f.exclude = split_list(cfg.get_or("fields.exclude", ""));
f.redact = split_list(cfg.get_or("fields.redact", ""));
return f;
}
Void::Result::Result<std::shared_ptr<const Formatter>,
Void::Result::Error>
make_formatter(const Configuration::Config& cfg)
{
const auto format = cfg.get_or("format", "default");
if (format == "default") {
return Void::Result::ok<std::shared_ptr<const Formatter>>(nullptr);
}
if (format == "pattern") {
auto fmt = std::make_shared<PatternFormatter>(std::string{
cfg.get_or("pattern",
"{time} [{level}] {scopes}{message}")});
if (const auto col = cfg.get_as<std::string>("color");
col.has_value()) {
const auto parsed = cfg.get_as<bool>("color");
if (!parsed.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: invalid bool "
"'{}' for color",
*col)));
}
if (*parsed) {
fmt->set_color_policy(ColorPolicy::defaults());
}
}
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
if (format == "json") {
auto fmt = std::make_shared<JsonLinesFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
if (format == "logfmt") {
auto fmt = std::make_shared<LogfmtFormatter>();
fmt->set_field_filter(make_field_filter(cfg));
return Void::Result::ok<std::shared_ptr<const Formatter>>(
std::move(fmt));
}
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown format '{}'",
format)));
}
struct Dispatch {
Mode mode = Mode::Async;
std::size_t capacity = 512;
OverflowPolicy policy = OverflowPolicy::DropNewest;
};
Void::Result::Result<Dispatch, Void::Result::Error>
make_dispatch(const Configuration::Config& cfg)
{
Dispatch d;
if (cfg.get_as<std::string>("async").has_value()) {
const auto async_val = cfg.get_as<bool>("async");
if (!async_val.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: invalid async bool"));
}
d.mode = *async_val ? Mode::Async : Mode::Immediate;
}
if (cfg.get_as<std::string>("capacity").has_value()) {
const auto cap_val = cfg.get_as<std::size_t>("capacity");
if (!cap_val.has_value() || *cap_val == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: capacity must be positive"));
}
d.capacity = *cap_val;
}
if (const auto overflow = cfg.get_as<std::string>("overflow");
overflow.has_value()) {
if (*overflow == "block") {
d.policy = OverflowPolicy::Block;
} else if (*overflow == "drop_newest") {
d.policy = OverflowPolicy::DropNewest;
} else if (*overflow == "drop_oldest") {
d.policy = OverflowPolicy::DropOldest;
} else {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown overflow "
"policy '{}'",
*overflow)));
}
}
return d;
}
Void::Result::Result<std::size_t, Void::Result::Error>
positive_size_or(const Configuration::Config& cfg,
std::string_view key,
std::size_t fallback)
{
if (!cfg.get_as<std::string>(key).has_value()) {
return fallback;
}
const auto parsed = cfg.get_as<std::size_t>(key);
if (!parsed.has_value() || *parsed == 0) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: '{}' must be > 0",
key)));
}
return *parsed;
}
} // namespace
Void::Result::Result<std::shared_ptr<Logger>, Void::Result::Error>
from_config(const Configuration::Config& cfg, std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
Level parsed_level = Level::Trace;
if (const auto raw_lvl = sub.get_as<std::string>("level");
raw_lvl.has_value()) {
const auto lvl = parse_level(*raw_lvl);
if (!lvl.has_value()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown level '{}'",
*raw_lvl)));
}
parsed_level = *lvl;
}
auto dispatch_res = make_dispatch(sub);
if (!dispatch_res.has_value()) {
return Void::Result::fail(std::move(dispatch_res).error());
}
const auto dispatch = *dispatch_res;
auto formatter_res = make_formatter(sub);
if (!formatter_res.has_value()) {
return Void::Result::fail(std::move(formatter_res).error());
}
const auto formatter = std::move(*formatter_res);
const LoggerOptions base_opts{
.mode = dispatch.mode,
.policy = dispatch.policy,
.limits = DeliveryLimits{
.entries = dispatch.capacity,
.owned_bytes = std::max<std::size_t>(
8ULL * 1024ULL * 1024ULL, dispatch.capacity * 1024ULL),
.max_fields = 64,
.max_scopes = 64},
.failure_policy = FailurePolicy::Quarantine,
.suppress_reentrancy = true};
std::vector<std::shared_ptr<Logger>> sinks;
for (const auto& name : split_list(sub.get_or("sinks", "console"))) {
if (name == "console") {
const auto stream = sub.get_or("console.stream", "stderr");
if (stream != "stderr" && stream != "stdout") {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown "
"console.stream '{}'",
stream)));
}
auto sink = std::make_shared<ConsoleLogger>(
stream == "stdout" ? std::cout : std::cerr, dispatch.mode,
dispatch.capacity);
if (formatter) {
sink->set_formatter(formatter);
}
sinks.push_back(std::move(sink));
} else if (name == "file") {
const auto path = sub.get_or("file.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'file' needs file.path"));
}
auto sink =
FileLogger::open(std::filesystem::path{path}, base_opts);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "rotating") {
const auto path = sub.get_or("rotating.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'rotating' needs "
"rotating.path"));
}
auto max_kb = positive_size_or(sub, "rotating.max_kb", 1024);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files =
positive_size_or(sub, "rotating.max_files", 5);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
RotatingFileLogger::Options opt;
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
RotatingFileLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "split") {
const auto dir = sub.get_or("split.dir");
if (dir.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'split' needs split.dir"));
}
auto max_kb = positive_size_or(sub, "split.max_kb", 1024);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files = positive_size_or(sub, "split.max_files", 5);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
SplitFileLogger::Options opt;
opt.combined = sub.get_or_as<bool>("split.combined", true);
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
SplitFileLogger::open(std::filesystem::path{dir}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
if (formatter) {
(*sink)->set_formatter(formatter);
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "history") {
const auto path = sub.get_or("history.path");
if (path.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'history' needs "
"history.path"));
}
auto max_kb = positive_size_or(sub, "history.max_kb", 8192);
if (!max_kb) {
return Void::Result::fail(std::move(max_kb).error());
}
auto max_files =
positive_size_or(sub, "history.max_files", 10);
if (!max_files) {
return Void::Result::fail(std::move(max_files).error());
}
HistoryLogger::Options opt;
opt.max_bytes = *max_kb * 1024;
opt.max_files = *max_files;
opt.mode = dispatch.mode;
opt.capacity = dispatch.capacity;
opt.policy = dispatch.policy;
auto sink =
HistoryLogger::open(std::filesystem::path{path}, opt);
if (!sink.has_value()) {
return Void::Result::fail(std::move(sink).error());
}
sinks.push_back(std::shared_ptr<Logger>{std::move(*sink)});
} else if (name == "syslog") {
#ifdef VOID_HAS_SYSLOG
const auto identity = sub.get_or("syslog.identity");
if (identity.empty()) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: sink 'syslog' needs "
"syslog.identity"));
}
sinks.push_back(std::make_shared<SyslogLogger>(
std::string{identity}, dispatch.mode, dispatch.capacity));
#else
return Void::Result::fail(make_log_error(
LogErrorCode::unsupported_capability,
"Logging::from_config: syslog is not available on "
"this platform"));
#endif
} else {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
std::format("Logging::from_config: unknown sink '{}'",
name)));
}
}
std::shared_ptr<Logger> root;
if (sinks.empty()) {
root = std::make_shared<NullLogger>(base_opts);
} else if (sinks.size() == 1) {
root = std::move(sinks.front());
} else {
if (sinks.size() > kDefaultMaxFanoutChildren) {
return Void::Result::fail(make_log_error(
LogErrorCode::invalid_argument,
"Logging::from_config: too many sinks"));
}
root = std::make_shared<MultiLogger>(std::move(sinks));
}
root->set_level(parsed_level);
Void::Log::debug("Logging", "from_config: built logger tree");
return Void::Result::ok(std::move(root));
}
void apply_facade_config(const Configuration::Config& cfg,
std::string_view prefix)
{
const auto sub = cfg.subtree(prefix);
if (const auto level = parse_facade_level(sub.get_or("level", ""));
level.has_value()) {
Void::Log::set_min_level(*level);
}
for (const auto& key : sub.subtree("module_levels").keys()) {
const auto value = sub.get_or(std::string{"module_levels."} + key);
if (const auto level = parse_facade_level(value);
level.has_value()) {
Void::Log::set_module_level(key, *level);
}
}
}
} // namespace Void::Logging
+4
View File
@@ -0,0 +1,4 @@
void_add_module(LogConfig
INTERNAL_DEPS Log Configuration Functional
EXTRA_HEADERS Void/Log/FromConfig.hpp
)
+7 -1
View File
@@ -12,4 +12,10 @@ namespace Void::Log::Detail
static State s;
return s;
}
} // namespace Void::Log::Detail
std::vector<const SinkRegistration*>& active_registrations_tls() noexcept
{
static thread_local std::vector<const SinkRegistration*> stack;
return stack;
}
} // namespace Void::Log::Detail
+732 -102
View File
@@ -1,114 +1,744 @@
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Stacktrace/Color.hpp>
#include <Void/Log/Log.hpp>
#include <algorithm>
#include <filesystem>
#include <format>
#include <fstream>
#include <sstream>
#include <Void/Stacktrace/Color.hpp>
#ifndef _WIN32
#include <dlfcn.h>
#include <sys/stat.h>
#include <unistd.h>
#endif
#include <boost/core/demangle.hpp>
#include <boost/stacktrace.hpp>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <filesystem>
#include <format>
#include <fstream>
#include <list>
#include <mutex>
#include <sstream>
#include <unordered_map>
#include <utility>
namespace Void::Stacktrace
{
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
unsigned max_frames)
{
std::vector<StackFrame> result;
try {
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
for (auto it = bt.begin(); it != bt.end(); ++it) {
StackFrame frame;
std::string name = it->name();
if (!name.empty()) {
frame.function_name = boost::core::demangle(name.c_str());
}
frame.source_file = it->source_file();
frame.source_line = it->source_line();
if (!frame.source_file.empty() && frame.source_line > 0) {
frame.source_snippet =
read_source_snippet(frame.source_file,
frame.source_line, 2)
.value_or(std::string{});
}
result.push_back(std::move(frame));
}
} catch (...) {
}
Void::Log::debug("Stacktrace", "captured {} frames", result.size());
return result;
}
namespace
{
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file, int line,
int context_lines)
{
std::ifstream ifs{file};
if (!ifs.is_open()) {
Void::Log::warn("Stacktrace", "read_source_snippet: cannot open '{}'", file);
return Void::Result::fail(
std::format("read_source_snippet: cannot open '{}'", file));
}
std::ostringstream result;
std::string current_line;
int line_num = 1;
int start = std::max(1, line - context_lines);
int end = line + context_lines;
while (std::getline(ifs, current_line)) {
if (line_num >= start && line_num <= end) {
std::string prefix = (line_num == line) ? " >>> " : " ";
result << std::format("{:>4}{}{}\n", line_num, prefix,
current_line);
}
if (line_num > end) {
break;
}
++line_num;
}
return Void::Result::ok(result.str());
}
[[nodiscard]] RawFrame build_raw_frame(const void* addr_ptr)
{
RawFrame rf;
rf.address = reinterpret_cast<std::uintptr_t>(addr_ptr);
if (addr_ptr == nullptr) {
return rf;
}
#ifndef _WIN32
Dl_info info{};
if (::dladdr(addr_ptr, &info) != 0 && info.dli_fname != nullptr &&
info.dli_fname[0] != '\0') {
rf.module_path.assign(info.dli_fname);
const auto base = reinterpret_cast<std::uintptr_t>(info.dli_fbase);
rf.module_offset = (rf.address >= base) ? (rf.address - base) : 0;
struct stat st {};
if (::stat(info.dli_fname, &st) == 0) {
rf.module_id = std::format(
"{}:{}:{}:{}",
static_cast<unsigned long long>(st.st_dev),
static_cast<unsigned long long>(st.st_ino),
static_cast<unsigned long long>(st.st_size),
rf.module_path);
} else {
rf.module_id = rf.module_path;
}
}
#endif
return rf;
}
std::string format_stacktrace(const std::vector<StackFrame>& frames)
{
if (frames.empty()) {
return " <no stacktrace available>\n";
}
std::ostringstream oss;
for (size_t i = 0; i < frames.size(); ++i) {
const auto& frame = frames[i];
oss << std::format(" #{:02} ", i);
if (!frame.function_name.empty()) {
oss << (Color::g_color_enabled
? Color::apply(Color::bold_cyan,
frame.function_name)
: frame.function_name);
} else {
oss << "<unknown>";
}
if (!frame.source_file.empty() && frame.source_line > 0) {
std::filesystem::path p{frame.source_file};
oss << "\n at "
<< (Color::g_color_enabled
? Color::apply(Color::dim, p.filename().string())
: p.filename().string())
<< ":" << frame.source_line;
}
oss << "\n";
if (!frame.source_snippet.empty() && i < 5) {
oss << " "
<< (Color::g_color_enabled
? Color::apply(Color::dim, frame.source_snippet)
: frame.source_snippet);
}
}
return oss.str();
}
[[nodiscard]] std::string redact_source_path(
std::string_view raw_path,
const std::vector<std::string>& redact_prefixes)
{
if (raw_path.empty()) {
return {};
}
if (redact_prefixes.empty()) {
return std::filesystem::path{raw_path}.filename().string();
}
std::string_view best_match;
for (const auto& prefix : redact_prefixes) {
if (!prefix.empty() && raw_path.starts_with(prefix) &&
prefix.size() > best_match.size()) {
best_match = prefix;
}
}
if (!best_match.empty()) {
std::string_view rest = raw_path.substr(best_match.size());
while (!rest.empty() && (rest.front() == '/' || rest.front() == '\\')) {
rest.remove_prefix(1);
}
return std::string{rest};
}
return std::filesystem::path{raw_path}.filename().string();
}
void print_stacktrace(std::ostream& os,
const std::vector<StackFrame>& frames)
{
os << format_stacktrace(frames);
}
} // namespace Void::Stacktrace
[[nodiscard]] bool is_under_allowed_roots(
const std::filesystem::path& file,
const std::vector<std::filesystem::path>& roots,
std::filesystem::path& out_canonical,
Void::Result::Error& out_error)
{
if (roots.empty()) {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
"Source snippets require non-empty allowed_source_roots");
return false;
}
for (const auto& part : file) {
if (part == "..") {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
"Path traversal ('..') is rejected for source snippets");
return false;
}
}
std::error_code ec;
const auto canon_file = std::filesystem::canonical(file, ec);
if (ec) {
out_error = make_stacktrace_error(
StacktraceErrorCode::source_unreadable,
std::format("Cannot resolve snippet path '{}': {}",
file.string(), ec.message()));
return false;
}
if (!std::filesystem::is_regular_file(canon_file, ec) || ec) {
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
std::format("Snippet target '{}' is not a regular file",
canon_file.string()));
return false;
}
for (const auto& root : roots) {
std::error_code rec;
const auto canon_root = std::filesystem::canonical(root, rec);
if (rec) {
continue;
}
const auto rel = canon_file.lexically_relative(canon_root);
if (!rel.empty() && rel.native() != "." && *rel.begin() != "..") {
out_canonical = canon_file;
return true;
}
}
out_error = make_stacktrace_error(
StacktraceErrorCode::unsafe_path,
std::format("Snippet path '{}' escapes allowed_source_roots",
canon_file.string()));
return false;
}
struct CacheKey {
std::string module_id;
std::uintptr_t offset{0};
[[nodiscard]] bool operator==(const CacheKey&) const = default;
};
struct CacheKeyHash {
[[nodiscard]] std::size_t operator()(const CacheKey& k) const noexcept
{
std::size_t h1 = std::hash<std::string>{}(k.module_id);
std::size_t h2 = std::hash<std::uintptr_t>{}(k.offset);
return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2));
}
};
struct CacheValue {
std::string function_name;
std::string raw_source_file;
int source_line{0};
FrameResolveStatus status{FrameResolveStatus::unresolved};
std::size_t byte_cost{0};
};
} // namespace
Capabilities capabilities() noexcept
{
#if defined(_WIN32) && !defined(__CYGWIN__)
return Capabilities{
.raw_capture = true,
.symbols = true,
.line_info = true,
.async_signal_safe = false,
.backend_name = "boost.stacktrace.windbg"};
#else
return Capabilities{
.raw_capture = true,
.symbols = true,
.line_info = true,
.async_signal_safe = false,
.backend_name = "boost.stacktrace.addr2line"};
#endif
}
Void::Result::Result<RawTrace> capture(CaptureOptions options)
{
if (options.max_frames == 0 || options.max_frames > kMaxCaptureFrames) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
std::format("CaptureOptions::max_frames must be in [1, {}]",
kMaxCaptureFrames)));
}
RawTrace trace;
try {
const std::size_t probe_depth =
static_cast<std::size_t>(options.max_frames) + 1;
boost::stacktrace::stacktrace bt(
static_cast<std::size_t>(options.skip) + 1, probe_depth);
if (bt.size() > options.max_frames) {
trace.truncated = true;
}
const std::size_t count =
std::min<std::size_t>(bt.size(), options.max_frames);
trace.frames.reserve(count);
for (std::size_t i = 0; i < count; ++i) {
trace.frames.push_back(build_raw_frame(bt[i].address()));
}
return trace;
} catch (const std::exception& e) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::backend_failed,
std::string{"Stacktrace raw capture failed: "} + e.what()));
} catch (...) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::backend_failed,
"Stacktrace raw capture failed"));
}
}
struct Resolver::Impl {
using LruList = std::list<std::pair<CacheKey, CacheValue>>;
using LookupMap = std::unordered_map<CacheKey, LruList::iterator, CacheKeyHash>;
std::size_t max_entries;
std::size_t max_bytes;
mutable std::mutex mutex;
LruList lru;
LookupMap map;
std::size_t current_bytes{0};
Impl(std::size_t entries, std::size_t bytes)
: max_entries(entries), max_bytes(bytes)
{
}
[[nodiscard]] std::optional<CacheValue> find_and_touch(const CacheKey& key)
{
if (key.module_id.empty()) {
return std::nullopt;
}
std::lock_guard lock{mutex};
const auto it = map.find(key);
if (it == map.end()) {
return std::nullopt;
}
lru.splice(lru.begin(), lru, it->second);
return it->second->second;
}
void insert(const CacheKey& key, CacheValue val)
{
if (key.module_id.empty() || max_entries == 0 || max_bytes == 0) {
return;
}
val.byte_cost =
96 + key.module_id.size() + val.function_name.size() +
val.raw_source_file.size();
if (val.byte_cost > max_bytes) {
return;
}
std::lock_guard lock{mutex};
if (const auto it = map.find(key); it != map.end()) {
current_bytes -= std::min(current_bytes, it->second->second.byte_cost);
it->second->second = val;
current_bytes += val.byte_cost;
lru.splice(lru.begin(), lru, it->second);
return;
}
while (!lru.empty() &&
(lru.size() >= max_entries ||
val.byte_cost > max_bytes - std::min(current_bytes, max_bytes))) {
const auto last = std::prev(lru.end());
current_bytes -= std::min(current_bytes, last->second.byte_cost);
map.erase(last->first);
lru.pop_back();
}
lru.emplace_front(key, std::move(val));
map.emplace(key, lru.begin());
current_bytes += lru.front().second.byte_cost;
}
};
Resolver::Resolver(std::size_t max_entries, std::size_t max_bytes)
: impl_(std::make_unique<Impl>(max_entries, max_bytes))
{
}
Resolver::~Resolver() = default;
std::size_t Resolver::invalidate_module(std::string_view module_id)
{
std::lock_guard lock{impl_->mutex};
std::size_t removed = 0;
for (auto it = impl_->lru.begin(); it != impl_->lru.end();) {
if (it->first.module_id == module_id) {
impl_->current_bytes -=
std::min(impl_->current_bytes, it->second.byte_cost);
impl_->map.erase(it->first);
it = impl_->lru.erase(it);
++removed;
} else {
++it;
}
}
return removed;
}
void Resolver::clear_cache()
{
std::lock_guard lock{impl_->mutex};
impl_->map.clear();
impl_->lru.clear();
impl_->current_bytes = 0;
}
std::size_t Resolver::cache_entries() const
{
std::lock_guard lock{impl_->mutex};
return impl_->map.size();
}
std::size_t Resolver::cache_bytes() const
{
std::lock_guard lock{impl_->mutex};
return impl_->current_bytes;
}
Void::Result::Result<std::string>
read_source_snippet_checked(const std::filesystem::path& file,
int line,
const ResolveOptions& options)
{
if (line <= 0 || options.context_lines < 0 ||
options.max_snippet_bytes == 0 || options.max_source_scan_bytes == 0 ||
options.max_line_bytes == 0) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
"Invalid line or snippet budget options"));
}
const auto& clock =
options.clock != nullptr
? *options.clock
: Void::Time::SystemMonotonicClock::instance();
if (options.stop.stop_requested()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::cancelled,
"Source snippet read cancelled"));
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::timeout,
"Source snippet read deadline expired"));
}
std::filesystem::path canonical_file;
Void::Result::Error path_err;
if (!is_under_allowed_roots(
file, options.allowed_source_roots, canonical_file, path_err)) {
return Void::Result::fail(std::move(path_err));
}
std::ifstream ifs{canonical_file};
if (!ifs.is_open()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::source_unreadable,
std::format("Cannot open canonical snippet file '{}'",
canonical_file.string())));
}
const std::int64_t target = line;
const std::int64_t ctx = options.context_lines;
const std::int64_t start = std::max<std::int64_t>(1, target - ctx);
const std::int64_t end = target + ctx;
std::string out;
std::string current_line;
std::int64_t line_num = 1;
std::size_t scanned_bytes = 0;
while (std::getline(ifs, current_line)) {
if (options.stop.stop_requested()) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::cancelled,
"Source snippet read cancelled"));
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::timeout,
"Source snippet read deadline expired"));
}
scanned_bytes += current_line.size() + 1;
if (scanned_bytes > options.max_source_scan_bytes) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::scan_limit_exceeded,
"Source file scan byte budget exceeded"));
}
if (line_num >= start && line_num <= end) {
std::string_view clipped{current_line};
bool line_clipped = false;
if (clipped.size() > options.max_line_bytes) {
clipped = clipped.substr(0, options.max_line_bytes);
line_clipped = true;
}
const char* marker = (line_num == target) ? " >>> " : " ";
std::string formatted = std::format(
"{:>4}{}{}{}\n",
line_num,
marker,
clipped,
line_clipped ? "..." : "");
if (out.size() + formatted.size() > options.max_snippet_bytes) {
const std::size_t rem =
options.max_snippet_bytes -
std::min(out.size(), options.max_snippet_bytes);
out.append(formatted.data(), rem);
break;
}
out += formatted;
}
if (line_num >= end) {
break;
}
++line_num;
}
return out;
}
Void::Result::Result<ResolvedTrace>
Resolver::resolve(const RawTrace& raw, const ResolveOptions& options)
{
if (options.max_bytes == 0) {
return Void::Result::fail(make_stacktrace_error(
StacktraceErrorCode::invalid_argument,
"ResolveOptions::max_bytes must be positive"));
}
const auto& clock =
options.clock != nullptr
? *options.clock
: Void::Time::SystemMonotonicClock::instance();
ResolvedTrace trace;
trace.truncated = raw.truncated;
trace.frames.reserve(raw.frames.size());
for (const auto& rf : raw.frames) {
ResolvedFrame out_frame;
out_frame.raw = rf;
if (options.stop.stop_requested()) {
trace.incomplete = true;
out_frame.status = FrameResolveStatus::cancelled;
trace.frames.push_back(std::move(out_frame));
continue;
}
if (options.deadline.has_value() && clock.now() >= *options.deadline) {
trace.incomplete = true;
out_frame.status = FrameResolveStatus::timed_out;
trace.frames.push_back(std::move(out_frame));
continue;
}
if (!options.resolve_symbols) {
out_frame.status = FrameResolveStatus::unresolved;
trace.frames.push_back(std::move(out_frame));
continue;
}
const CacheKey key{rf.module_id, rf.module_offset};
std::optional<CacheValue> cached = impl_->find_and_touch(key);
if (!cached.has_value() && rf.address != 0) {
CacheValue resolved;
try {
boost::stacktrace::frame f{
reinterpret_cast<const void*>(rf.address)};
const std::string mangled = f.name();
if (!mangled.empty()) {
resolved.function_name =
boost::core::demangle(mangled.c_str());
}
resolved.raw_source_file = f.source_file();
resolved.source_line =
static_cast<int>(f.source_line());
if (!resolved.function_name.empty()) {
resolved.status =
(!resolved.raw_source_file.empty() &&
resolved.source_line > 0)
? FrameResolveStatus::resolved
: FrameResolveStatus::symbols_only;
} else {
resolved.status = FrameResolveStatus::unresolved;
}
} catch (...) {
resolved.status = FrameResolveStatus::unresolved;
}
impl_->insert(key, resolved);
cached = std::move(resolved);
}
if (cached.has_value()) {
out_frame.function_name = cached->function_name;
out_frame.source_line = cached->source_line;
out_frame.status = cached->status;
out_frame.source_file = redact_source_path(
cached->raw_source_file, options.redact_prefixes);
if (options.source_snippets && !cached->raw_source_file.empty() &&
cached->source_line > 0) {
auto snip = read_source_snippet_checked(
cached->raw_source_file, cached->source_line, options);
if (snip) {
out_frame.source_snippet = std::move(*snip);
} else {
out_frame.diagnostic = std::move(snip).error();
}
}
}
const std::size_t frame_bytes =
96 + out_frame.function_name.size() + out_frame.source_file.size() +
out_frame.source_snippet.size();
if (trace.rendered_bytes + frame_bytes > options.max_bytes) {
out_frame.source_snippet.clear();
trace.truncated = true;
}
trace.rendered_bytes +=
96 + out_frame.function_name.size() + out_frame.source_file.size() +
out_frame.source_snippet.size();
trace.frames.push_back(std::move(out_frame));
}
return trace;
}
Void::Result::Result<ResolvedTrace>
resolve(const RawTrace& raw, const ResolveOptions& options)
{
Resolver transient{0, 0};
return transient.resolve(raw, options);
}
std::string format_resolved_trace(
const ResolvedTrace& trace, std::size_t max_bytes)
{
if (trace.frames.empty()) {
return " <no stacktrace available>\n";
}
std::string out;
for (std::size_t i = 0; i < trace.frames.size(); ++i) {
const auto& fr = trace.frames[i];
std::string line = std::format(
" #{:02} 0x{:x} {}\n",
i,
fr.raw.address,
fr.function_name.empty() ? std::string{"<unknown>"}
: fr.function_name);
if (!fr.source_file.empty() && fr.source_line > 0) {
line += std::format(
" at {}:{}\n", fr.source_file, fr.source_line);
}
if (!fr.source_snippet.empty()) {
line += fr.source_snippet;
}
if (out.size() + line.size() > max_bytes) {
constexpr std::string_view kTrunc = " ... [truncated]\n";
if (out.size() + kTrunc.size() <= max_bytes) {
out += kTrunc;
}
break;
}
out += line;
}
return out;
}
bool write_fatal_signal_marker(int fd, int sig) noexcept
{
#ifdef _WIN32
(void)fd;
(void)sig;
return false;
#else
if (fd < 0) {
return false;
}
char buf[64]{};
std::size_t pos = 0;
constexpr char kPrefix[] = "VOID_FATAL_SIGNAL sig=";
for (std::size_t i = 0; i < sizeof(kPrefix) - 1; ++i) {
buf[pos++] = kPrefix[i];
}
unsigned int u = 0;
if (sig < 0) {
buf[pos++] = '-';
u = static_cast<unsigned int>(-(sig + 1)) + 1U;
} else {
u = static_cast<unsigned int>(sig);
}
char rev[16]{};
std::size_t rpos = 0;
do {
rev[rpos++] = static_cast<char>('0' + (u % 10U));
u /= 10U;
} while (u > 0U && rpos < sizeof(rev));
while (rpos > 0U) {
buf[pos++] = rev[--rpos];
}
buf[pos++] = '\n';
std::size_t written = 0;
while (written < pos) {
const auto n = ::write(fd, buf + written, pos - written);
if (n > 0) {
written += static_cast<std::size_t>(n);
} else if (n < 0 && errno == EINTR) {
continue;
} else {
return false;
}
}
return true;
#endif
}
// ── Legacy compatibility API ─────────────────────────────────────────────────
std::vector<StackFrame> capture_stacktrace(unsigned skip_frames,
unsigned max_frames)
{
std::vector<StackFrame> result;
try {
boost::stacktrace::stacktrace bt(skip_frames + 1, max_frames);
for (auto it = bt.begin(); it != bt.end(); ++it) {
StackFrame frame;
std::string name = it->name();
if (!name.empty()) {
frame.function_name = boost::core::demangle(name.c_str());
}
frame.source_file = it->source_file();
frame.source_line = it->source_line();
if (!frame.source_file.empty() && frame.source_line > 0) {
frame.source_snippet =
read_source_snippet(frame.source_file,
frame.source_line, 2)
.value_or(std::string{});
}
result.push_back(std::move(frame));
}
} catch (...) {
}
Void::Log::debug("Stacktrace", "captured {} frames", result.size());
return result;
}
Void::Result::Result<std::string, Void::Result::Error>
read_source_snippet(const std::string& file, int line, int context_lines)
{
std::ifstream ifs{file};
if (!ifs.is_open()) {
Void::Log::warn(
"Stacktrace", "read_source_snippet: cannot open '{}'", file);
return Void::Result::fail(
std::format("read_source_snippet: cannot open '{}'", file));
}
std::ostringstream result;
std::string current_line;
int line_num = 1;
const std::int64_t start = std::max<std::int64_t>(
1, static_cast<std::int64_t>(line) - context_lines);
const std::int64_t end =
static_cast<std::int64_t>(line) + context_lines;
while (std::getline(ifs, current_line)) {
if (line_num >= start && line_num <= end) {
std::string prefix = (line_num == line) ? " >>> " : " ";
result << std::format("{:>4}{}{}\n", line_num, prefix,
current_line);
}
if (line_num > end) {
break;
}
++line_num;
}
return Void::Result::ok(result.str());
}
std::string format_stacktrace(const std::vector<StackFrame>& frames)
{
if (frames.empty()) {
return " <no stacktrace available>\n";
}
std::ostringstream oss;
for (std::size_t i = 0; i < frames.size(); ++i) {
const auto& frame = frames[i];
oss << std::format(" #{:02} ", i);
if (!frame.function_name.empty()) {
oss << (Color::g_color_enabled
? Color::apply(Color::bold_cyan, frame.function_name)
: frame.function_name);
} else {
oss << "<unknown>";
}
if (!frame.source_file.empty() && frame.source_line > 0) {
std::filesystem::path p{frame.source_file};
oss << "\n at "
<< (Color::g_color_enabled
? Color::apply(Color::dim, p.filename().string())
: p.filename().string())
<< ":" << frame.source_line;
}
oss << "\n";
if (!frame.source_snippet.empty() && i < 5) {
oss << " "
<< (Color::g_color_enabled
? Color::apply(Color::dim, frame.source_snippet)
: frame.source_snippet);
}
}
return oss.str();
}
void print_stacktrace(std::ostream& os, const std::vector<StackFrame>& frames)
{
os << format_stacktrace(frames);
}
} // namespace Void::Stacktrace
+1 -1
View File
@@ -5,7 +5,7 @@ else()
endif()
void_add_module(Stacktrace
INTERNAL_DEPS Functional LogState
INTERNAL_DEPS Functional Time LogState
EXTERNAL_DEPS ${_void_stacktrace_target}
DEPS_UNIX dl
OPTIONS_UNIX -g -fno-omit-frame-pointer
+22 -11
View File
@@ -7,20 +7,31 @@ if(NOT TARGET Void::Testing)
endif()
get_property(ACTIVE_MODULES GLOBAL PROPERTY VOID_MODULES)
get_property(ACTIVE_HEADERS GLOBAL PROPERTY VOID_ACTIVE_PUBLIC_HEADERS)
function(_void_test_requires_satisfied src_file active_modules out_var)
function(_void_test_requires_satisfied src_file active_modules active_headers out_var)
file(READ "${src_file}" _src_content)
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+)/[^>\"]+[>\"]"
string(REGEX MATCHALL "#[ \t]*include[ \t]*[<\"](Void/[^/\">]+/[^>\"]+)[>\"]"
_matches "${_src_content}")
set(_ok TRUE)
foreach(_m IN LISTS _matches)
if(_m MATCHES "Void/([^/\">]+)/")
set(_req "${CMAKE_MATCH_1}")
if(NOT _req STREQUAL "Detail" AND NOT _req IN_LIST active_modules)
set(_ok FALSE)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires unselected module '${_req}')")
break()
if(_m MATCHES "(Void/([^/\">]+)/[^>\"]+)")
set(_hdr "${CMAKE_MATCH_1}")
set(_req "${CMAKE_MATCH_2}")
if(NOT _req STREQUAL "Detail")
if(EXISTS "${CMAKE_SOURCE_DIR}/include/${_hdr}")
if(NOT _hdr IN_LIST active_headers)
set(_ok FALSE)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires unselected header '${_hdr}')")
break()
endif()
elseif(NOT _req IN_LIST active_modules)
set(_ok FALSE)
message(STATUS
"[VoidTests] Skipping ${src_file} (requires unselected module '${_req}')")
break()
endif()
endif()
endif()
endforeach()
@@ -49,7 +60,7 @@ foreach(mod ${ACTIVE_MODULES})
file(GLOB _test_files CONFIGURE_DEPENDS "${_mod_dir}/*.cpp")
foreach(_src ${_test_files})
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" _deps_ok)
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" "${ACTIVE_HEADERS}" _deps_ok)
if(NOT _deps_ok)
continue()
endif()
@@ -76,7 +87,7 @@ endforeach()
file(GLOB_RECURSE _internal_sources CONFIGURE_DEPENDS "internal/*.cpp")
foreach(_src ${_internal_sources})
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" _deps_ok)
_void_test_requires_satisfied("${_src}" "${ACTIVE_MODULES}" "${ACTIVE_HEADERS}" _deps_ok)
if(NOT _deps_ok)
continue()
endif()
+5
View File
@@ -131,6 +131,11 @@ if(_has_resilience)
run_consumer(ResilienceOnly "${install_prefix}" "ResilienceOnly" ${_no_external_deps})
endif()
has_modules(_has_log Log Async Data Time Memory Functional Core LogState)
if(_has_log)
run_consumer(LogOnly "${install_prefix}" "LogOnly" ${_no_external_deps})
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
+10
View File
@@ -0,0 +1,10 @@
cmake_minimum_required(VERSION 4.0)
project(VoidLogOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Log)
add_executable(void_log_only_consumer main.cpp)
target_link_libraries(void_log_only_consumer PRIVATE Void::Log)
enable_testing()
add_test(NAME VoidLogOnlyConsumer COMMAND void_log_only_consumer)
+26
View File
@@ -0,0 +1,26 @@
#include <Void/Log/Log.hpp>
#include <Void/Log/LoggingAdapter.hpp>
#include <Void/Log/Sinks.hpp>
#include <atomic>
int main()
{
std::atomic<int> seen{0};
auto sink = std::make_shared<Void::Logging::CallbackLogger>(
[&](const Void::Logging::Entry&) {
seen.fetch_add(1, std::memory_order_relaxed);
},
Void::Logging::LoggerOptions{
.mode = Void::Logging::Mode::Immediate,
.policy = Void::Logging::OverflowPolicy::DropNewest});
const auto reg = Void::Log::register_sink(Void::Log::make_sink(sink), sink);
Void::Log::info("LogOnly", "hello consumer");
const auto dr = Void::Log::detach_and_drain(reg);
const auto rep = sink->close({});
return (dr == Void::Log::DrainResult::drained && rep.has_value() &&
seen.load() == 1)
? 0
: 1;
}
+372
View File
@@ -0,0 +1,372 @@
#include <Void/Log/FileLogger.hpp>
#include <Void/Log/Formatter.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Log/Logger.hpp>
#include <Void/Log/RotatingFileLogger.hpp>
#include <Void/Log/Sinks.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <filesystem>
#include <fstream>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <stop_token>
#include <string>
#include <thread>
#include <vector>
namespace
{
using namespace Void::Logging;
using namespace std::chrono_literals;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
struct FacadeGuard {
~FacadeGuard()
{
(void)Void::Log::detach_and_drain(0);
Void::Log::set_emergency_handler(nullptr);
Void::Log::set_min_level(Void::Log::Level::Trace);
}
};
std::atomic<int> g_emergency_calls{0};
void record_emergency(std::string_view) noexcept
{
g_emergency_calls.fetch_add(1, std::memory_order_relaxed);
}
} // namespace
Void::Testing::Test log_facade_reentrant_replace_drain_and_suppression()
{
FacadeGuard guard;
g_emergency_calls.store(0, std::memory_order_relaxed);
Void::Log::set_emergency_handler(&record_emergency);
const auto before_drops = Void::Log::reentrant_dropped();
std::atomic<bool> destroyed{false};
struct OwnerFlag {
std::atomic<bool>* flag;
~OwnerFlag() { flag->store(true, std::memory_order_release); }
};
auto owner = std::make_shared<OwnerFlag>(&destroyed);
std::mutex mu;
std::condition_variable cv;
bool in_cb = false;
bool release_cb = false;
std::atomic<bool> self_drain_blocked{false};
std::atomic<int> secondary_calls{0};
const auto id = Void::Log::register_sink(
[&](Void::Log::Level,
std::string_view,
std::string_view,
const std::source_location&) {
// Reentrant log into same registration is suppressed & routed to emergency hook.
Void::Log::info("LogHardening", "recursive call");
// Synchronous self-drain detects active registration -> would_deadlock.
if (Void::Log::detach_and_drain(0) == Void::Log::DrainResult::would_deadlock) {
self_drain_blocked.store(true, std::memory_order_release);
}
// Reentrant sink replacement must NOT deadlock; old registration stays
// alive via Hook/ActiveRegistrationGuard until callback exits.
Void::Log::set_sink([&](auto, auto, auto, auto) {
secondary_calls.fetch_add(1, std::memory_order_relaxed);
});
{
std::unique_lock lock{mu};
in_cb = true;
cv.notify_all();
cv.wait(lock, [&] { return release_cb; });
}
},
owner);
owner.reset();
std::thread emitter{[&] {
Void::Log::info("LogHardening", "outer event");
}};
{
std::unique_lock lock{mu};
cv.wait(lock, [&] { return in_cb; });
}
// Even after callback called set_sink(secondary), original owner must stay alive
// until detach_and_drain(id) finishes waiting on active_calls == 0.
std::atomic<Void::Log::DrainResult> dr{Void::Log::DrainResult::not_found};
std::atomic<bool> drain_done{false};
std::thread drainer{[&] {
dr.store(Void::Log::detach_and_drain(id), std::memory_order_release);
drain_done.store(true, std::memory_order_release);
}};
std::this_thread::sleep_for(10ms);
expect(!drain_done.load(std::memory_order_acquire));
expect(!destroyed.load(std::memory_order_acquire));
{
std::lock_guard lock{mu};
release_cb = true;
}
cv.notify_all();
emitter.join();
drainer.join();
expect(self_drain_blocked.load());
expect(dr.load() == Void::Log::DrainResult::drained);
expect(destroyed.load(std::memory_order_acquire));
expect(Void::Log::reentrant_dropped() > before_drops);
expect(g_emergency_calls.load() >= 1);
Void::Log::info("LogHardening", "after replace");
expect_eq(secondary_calls.load(), 1);
}
Void::Testing::Test log_bounded_permits_drop_oldest_and_tickets()
{
std::mutex mu;
std::condition_variable cv;
bool stalled = true;
std::atomic<bool> in_sink{false};
std::vector<std::string> delivered;
LoggerOptions opt;
opt.mode = Mode::Async;
opt.policy = OverflowPolicy::DropOldest;
opt.limits.entries = 3;
opt.limits.batch_entries = 1;
opt.limits.owned_bytes = 64 * 1024;
opt.suppress_reentrancy = true;
auto sink = std::make_shared<CallbackLogger>(
[&](const Entry& e) {
in_sink.store(true, std::memory_order_release);
{
std::unique_lock lock{mu};
cv.wait(lock, [&] { return !stalled; });
}
delivered.push_back(e.message);
},
opt);
// 1st entry starts executing in worker immediately and occupies in-flight permit (1/3).
auto r1 = sink->try_submit(Entry{.level = Level::Info, .message = "first"});
require(r1.has_value() && r1->state == SubmitState::Accepted);
while (!in_sink.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(1ms);
}
// Queue 2 more -> now queued(2) + in_flight(1) == 3 (at capacity!).
auto r2 = sink->try_submit(Entry{.level = Level::Info, .message = "second"});
auto r3 = sink->try_submit(Entry{.level = Level::Info, .message = "third"});
auto r4 = sink->try_submit(Entry{.level = Level::Info, .message = "fourth"});
require(r2.has_value() && r3.has_value() && r4.has_value());
expect(r4->state == SubmitState::Accepted);
// Total active (queued + in_flight) never exceeds capacity 3; "second" was evicted.
const auto st_stall = sink->stats();
expect(st_stall.queued_entries + st_stall.in_flight_entries <= 3);
expect_eq(st_stall.dropped, std::uint64_t{1});
// Release stalled worker and verify contiguous watermark & report include evicted loss.
{
std::lock_guard lock{mu};
stalled = false;
}
cv.notify_all();
auto rep = sink->flush_through(*r4->ticket, {});
require(rep.has_value());
expect_eq(rep->delivered, std::uint64_t{3});
expect_eq(rep->dropped, std::uint64_t{1});
expect_eq(rep->watermark, *r4->ticket);
expect_eq(delivered.size(), std::size_t{3});
expect_eq(delivered[0], std::string{"first"});
expect_eq(delivered[1], std::string{"third"});
expect_eq(delivered[2], std::string{"fourth"});
// Non-file sink must report unsupported_capability for SyncFiles durability.
auto sync_res = sink->flush_through(0, FlushOptions{FlushDurability::SyncFiles, {}});
expect(!sync_res.has_value());
expect_eq(sync_res.error().code().value,
static_cast<std::int32_t>(LogErrorCode::unsupported_capability));
auto close_rep = sink->close({});
require(close_rep.has_value());
auto after_close = sink->try_submit(Entry{.level = Level::Info, .message = "late"});
require(after_close.has_value());
expect(after_close->state == SubmitState::Closed);
}
Void::Testing::Test log_quarantine_reentrancy_and_block_cancel()
{
int attempts = 0;
LoggerOptions qopt;
qopt.mode = Mode::Immediate;
qopt.failure_policy = FailurePolicy::Quarantine;
qopt.suppress_reentrancy = true;
std::shared_ptr<CallbackLogger> qsink;
bool trigger_reenter = true;
qsink = std::make_shared<CallbackLogger>(
[&](const Entry&) {
++attempts;
if (trigger_reenter) {
trigger_reenter = false;
auto sub = qsink->try_submit(Entry{.level = Level::Info, .message = "inner"});
expect(sub.has_value() && sub->state == SubmitState::Dropped);
// Synchronous self-flush must return would_deadlock.
auto sf = qsink->flush_through(0, {});
expect(!sf.has_value());
expect_eq(sf.error().code().value,
static_cast<std::int32_t>(LogErrorCode::would_deadlock));
}
throw std::runtime_error{"disk fault"};
},
qopt);
auto r = qsink->try_submit(Entry{.level = Level::Error, .message = "fail"});
require(r.has_value());
expect(qsink->is_quarantined());
expect(qsink->last_error_summary().find("disk fault") != std::string::npos);
expect_eq(qsink->stats().failed, std::uint64_t{1});
expect_eq(qsink->stats().reentrant_dropped, std::uint64_t{1});
// Subsequent submissions fail with quarantined until operator resets quarantine.
auto blocked = qsink->try_submit(Entry{.level = Level::Error, .message = "next"});
expect(!blocked.has_value());
expect_eq(blocked.error().code().value,
static_cast<std::int32_t>(LogErrorCode::quarantined));
qsink->reset_quarantine();
expect(!qsink->is_quarantined());
// Cancellable Block submit stops cleanly when stalled.
std::mutex mu;
std::condition_variable cv;
bool hold = true;
std::atomic<bool> entered{false};
LoggerOptions bopt;
bopt.mode = Mode::Async;
bopt.policy = OverflowPolicy::Block;
bopt.limits.entries = 1;
bopt.limits.batch_entries = 1;
CallbackLogger blocker{
[&](const Entry&) {
entered.store(true, std::memory_order_release);
std::unique_lock lock{mu};
cv.wait(lock, [&] { return !hold; });
},
bopt};
expect(blocker.try_submit(Entry{.level = Level::Info, .message = "fill"})->state ==
SubmitState::Accepted);
while (!entered.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(1ms);
}
std::stop_source stop_src;
std::thread stopper{[&] {
std::this_thread::sleep_for(10ms);
stop_src.request_stop();
}};
auto cancelled = blocker.try_submit(
Entry{.level = Level::Info, .message = "wait"},
Void::Async::OperationOptions{.stop = stop_src.get_token()});
stopper.join();
expect(!cancelled.has_value());
expect_eq(cancelled.error().code().value,
static_cast<std::int32_t>(LogErrorCode::cancelled));
{
std::lock_guard lock{mu};
hold = false;
}
cv.notify_all();
expect(blocker.close({}).has_value());
}
Void::Testing::Test log_formatters_multilogger_and_file_sync_reopen()
{
// 1. Logfmt escaping + redaction + format_bounded.
Entry e;
e.level = Level::Warning;
e.message = "line1\nline2\t\"q\"";
e.truncated = true;
e.fields = {{"secret", "s3cr3t"}, {"note", "a\nb\rc"}};
LogfmtFormatter logfmt;
logfmt.set_field_filter(FieldFilter{.redact = {"secret"}});
const std::string line = logfmt.format(e);
expect(line.find("truncated=true") != std::string::npos);
expect(line.find("secret=\"[REDACTED]\"") != std::string::npos);
expect(line.find("s3cr3t") == std::string::npos);
expect(line.find("\\n") != std::string::npos);
expect(line.find("\\r") != std::string::npos);
expect(line.find("\\t") != std::string::npos);
const auto too_big = format_bounded(logfmt, e, 16, false);
expect(!too_big.has_value());
const auto trunc_ok = format_bounded(logfmt, e, 24, true);
require(trunc_ok.has_value());
expect_eq(trunc_ok->size(), std::size_t{24});
expect(trunc_ok->ends_with("...[truncated]"));
// 2. MultiLogger fanout cap (8) + cycle rejection.
auto root = std::make_shared<MultiLogger>();
auto child = std::make_shared<MultiLogger>();
expect(root->try_add(child).has_value());
auto self_cycle = child->try_add(root);
expect(!self_cycle.has_value());
expect_eq(self_cycle.error().code().value,
static_cast<std::int32_t>(LogErrorCode::cycle_detected));
for (int i = 0; i < 7; ++i) {
expect(root->try_add(std::make_shared<NullLogger>()).has_value());
}
auto ninth = root->try_add(std::make_shared<NullLogger>());
expect(!ninth.has_value());
expect_eq(ninth.error().code().value,
static_cast<std::int32_t>(LogErrorCode::queue_full));
// 3. RotatingFileOptions::roadmap_defaults rejects missing dir + FileLogger sync/reopen.
const auto base = std::filesystem::temp_directory_path() / "void_log_hardening_test";
std::filesystem::remove_all(base);
auto missing_rot = RotatingFileLogger::open(
base / "no_such_dir" / "app.log",
RotatingFileOptions::roadmap_defaults());
expect(!missing_rot.has_value());
std::filesystem::create_directories(base);
const auto file_path = base / "durable.log";
{
auto fl_res = FileLogger::open(file_path, LoggerOptions{.mode = Mode::Immediate});
require(fl_res.has_value());
auto& fl = *fl_res;
auto ticket = fl->try_submit(Entry{.level = Level::Info, .message = "before-reopen"});
require(ticket.has_value() && ticket->ticket.has_value());
auto synced = fl->flush_through(*ticket->ticket, FlushOptions{FlushDurability::SyncFiles, {}});
expect(synced.has_value());
expect(fl->reopen().has_value());
expect(fl->try_submit(Entry{.level = Level::Info, .message = "after-reopen"}).has_value());
expect(fl->close({}).has_value());
}
std::ifstream ifs{file_path};
std::string content{(std::istreambuf_iterator<char>(ifs)), {}};
expect(content.find("before-reopen") != std::string::npos);
expect(content.find("after-reopen") != std::string::npos);
std::filesystem::remove_all(base);
}
@@ -15,11 +15,10 @@ using Void::Configuration::Config;
Void::Testing::Test from_config_defaults_to_console()
{
Config cfg; // empty: console sink, trace level, async
Config cfg;
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
Void::Testing::expect((*logger)->mode() ==
Void::Logging::Mode::Async);
Void::Testing::expect((*logger)->mode() == Void::Logging::Mode::Async);
}
Void::Testing::Test from_config_builds_multi_sink_tree()
@@ -33,17 +32,14 @@ Void::Testing::Test from_config_builds_multi_sink_tree()
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
Void::Testing::expect((*logger)->mode() ==
Void::Logging::Mode::Immediate);
Void::Testing::expect((*logger)->level() ==
Void::Logging::Level::Warning);
Void::Testing::expect((*logger)->mode() == Void::Logging::Mode::Immediate);
Void::Testing::expect((*logger)->level() == Void::Logging::Level::Warning);
(*logger)->warning("to both sinks");
(*logger)->flush();
std::ifstream f(tmp.path() / "a.log");
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("to both sinks") !=
std::string::npos);
Void::Testing::expect(content.find("to both sinks") != std::string::npos);
}
Void::Testing::Test from_config_split_and_history_sinks()
@@ -62,13 +58,11 @@ Void::Testing::Test from_config_split_and_history_sinks()
std::ifstream err(tmp.path() / "split" / "error.log");
std::string err_content((std::istreambuf_iterator<char>(err)), {});
Void::Testing::expect(err_content.find("split me") !=
std::string::npos);
Void::Testing::expect(err_content.find("split me") != std::string::npos);
std::ifstream hist(tmp.path() / "history.jsonl");
std::string hist_content((std::istreambuf_iterator<char>(hist)), {});
Void::Testing::expect(hist_content.find("split me") !=
std::string::npos);
Void::Testing::expect(hist_content.find("split me") != std::string::npos);
}
Void::Testing::Test from_config_json_format_applies()
@@ -78,11 +72,15 @@ Void::Testing::Test from_config_json_format_applies()
cfg.set("log.sinks", "file");
cfg.set("log.file.path", (tmp.path() / "j.log").string());
cfg.set("log.format", "json");
cfg.set("log.fields.redact", "token");
cfg.set("log.async", "false");
const auto logger = Void::Logging::from_config(cfg);
Void::Testing::expect(logger.has_value());
(*logger)->info("structured");
{
Void::Logging::FieldScope fs{"token", "top-secret"};
(*logger)->info("structured");
}
(*logger)->flush();
std::ifstream f(tmp.path() / "j.log");
@@ -90,6 +88,8 @@ Void::Testing::Test from_config_json_format_applies()
std::getline(f, line);
Void::Testing::expect(line.find("\"message\":\"structured\"") !=
std::string::npos);
Void::Testing::expect(line.find("top-secret") == std::string::npos);
Void::Testing::expect(line.find("[REDACTED]") != std::string::npos);
}
Void::Testing::Test from_config_missing_file_path_is_error()
@@ -106,6 +106,38 @@ Void::Testing::Test from_config_unknown_sink_is_error()
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
Void::Testing::Test from_config_rejects_invalid_values()
{
{
Config cfg;
cfg.set("log.level", "loud");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Config cfg;
cfg.set("log.format", "xml");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Config cfg;
cfg.set("log.overflow", "drop_middle");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Config cfg;
cfg.set("log.capacity", "0");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
{
Void::FileSystem::TempDir tmp{"void_fromcfg_bad"};
Config cfg;
cfg.set("log.sinks", "rotating");
cfg.set("log.rotating.path", (tmp.path() / "r.log").string());
cfg.set("log.rotating.max_kb", "0");
Void::Testing::expect(!Void::Logging::from_config(cfg).has_value());
}
}
Void::Testing::Test apply_facade_config_sets_levels()
{
struct Reset {
@@ -122,9 +154,7 @@ Void::Testing::Test apply_facade_config_sets_levels()
Void::Logging::apply_facade_config(cfg);
Void::Log::set_sink([](auto, auto, auto, auto) {});
Void::Testing::expect(
!Void::Log::enabled(Void::Log::Level::Info, "Other"));
Void::Testing::expect(
Void::Log::enabled(Void::Log::Level::Trace, "Fsm"));
Void::Testing::expect(!Void::Log::enabled(Void::Log::Level::Info, "Other"));
Void::Testing::expect(Void::Log::enabled(Void::Log::Level::Trace, "Fsm"));
Void::Log::set_sink({});
}
+237
View File
@@ -0,0 +1,237 @@
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Subprocess.hpp>
#include <Void/Testing/Test.hpp>
#include <Void/Time/Clock.hpp>
#ifndef _WIN32
#include <unistd.h>
#endif
#include <atomic>
#include <chrono>
#include <csignal>
#include <filesystem>
#include <fstream>
#include <limits>
#include <stop_token>
#include <string>
#include <vector>
namespace
{
using namespace Void::Stacktrace;
using Void::Testing::expect;
using Void::Testing::expect_eq;
using Void::Testing::require;
[[gnu::noinline]] Void::Result::Result<RawTrace>
nested_capture_helper(CaptureOptions opt)
{
return capture(opt);
}
} // namespace
Void::Testing::Test stacktrace_capabilities_and_empty_formatting()
{
const auto caps = capabilities();
expect(caps.raw_capture);
expect(!caps.async_signal_safe);
expect(!caps.backend_name.empty());
expect_eq(format_stacktrace({}), std::string{" <no stacktrace available>\n"});
expect_eq(format_resolved_trace(ResolvedTrace{}),
std::string{" <no stacktrace available>\n"});
expect(!capture(CaptureOptions{.max_frames = 0}).has_value());
expect(!capture(CaptureOptions{.max_frames = kMaxCaptureFrames + 1}).has_value());
}
Void::Testing::Test stacktrace_capture_no_log_recursion_and_no_source_io()
{
std::atomic<int> log_calls{0};
struct LogReset {
~LogReset() { (void)Void::Log::detach_and_drain(0); }
} guard;
Void::Log::set_sink([&](Void::Log::Level,
std::string_view,
std::string_view,
const std::source_location&) {
log_calls.fetch_add(1, std::memory_order_relaxed);
});
auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 8});
require(raw.has_value());
expect(!raw->frames.empty());
expect_eq(log_calls.load(), 0);
// Asking for 1 frame on a deeper call stack sets truncated = true.
auto trunc = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 1});
require(trunc.has_value());
expect_eq(trunc->frames.size(), std::size_t{1});
expect(trunc->truncated);
// Default resolve() performs no snippet file reads and emits no Void::Log calls.
auto res = resolve(*raw, ResolveOptions{});
require(res.has_value());
expect_eq(res->frames.size(), raw->frames.size());
expect_eq(log_calls.load(), 0);
for (const auto& f : res->frames) {
expect(f.source_snippet.empty());
}
}
Void::Testing::Test stacktrace_resolver_cache_redaction_and_safe_snippets()
{
const auto base = std::filesystem::temp_directory_path() / "void_stacktrace_test";
std::filesystem::remove_all(base);
const auto allowed_root = base / "allowed";
const auto secret_root = base / "secret";
std::filesystem::create_directories(allowed_root);
std::filesystem::create_directories(secret_root);
const auto src_file = allowed_root / "sample.cpp";
{
std::ofstream os{src_file};
for (int i = 1; i <= 20; ++i) {
os << "int line_" << i << " = " << i << ";\n";
}
}
const auto outside_file = secret_root / "creds.txt";
{
std::ofstream os{outside_file};
os << "SECRET_KEY=12345\n";
}
ResolveOptions opt;
opt.allowed_source_roots = {allowed_root};
opt.redact_prefixes = {allowed_root.string()};
opt.context_lines = 1;
opt.max_snippet_bytes = 256;
// 1. Valid read under allowed root.
auto ok_snip = read_source_snippet_checked(src_file, 10, opt);
require(ok_snip.has_value());
expect(ok_snip->find(" >>> int line_10") != std::string::npos);
// 2. Rejects empty allowed_source_roots, traversal, outside file, and symlinks escaping root.
ResolveOptions no_roots = opt;
no_roots.allowed_source_roots.clear();
expect(!read_source_snippet_checked(src_file, 5, no_roots).has_value());
const auto traversal = allowed_root / ".." / "secret" / "creds.txt";
auto trav_res = read_source_snippet_checked(traversal, 1, opt);
expect(!trav_res.has_value());
expect_eq(trav_res.error().code().value,
static_cast<std::int32_t>(StacktraceErrorCode::unsafe_path));
#ifndef _WIN32
const auto sym_escape = allowed_root / "escape.txt";
std::error_code sym_ec;
std::filesystem::create_symlink(outside_file, sym_escape, sym_ec);
if (!sym_ec) {
auto sym_res = read_source_snippet_checked(sym_escape, 1, opt);
expect(!sym_res.has_value());
expect_eq(sym_res.error().code().value,
static_cast<std::int32_t>(StacktraceErrorCode::unsafe_path));
}
#endif
// 3. Overflow-safe INT_MAX line arithmetic and scan byte limit.
auto int_max_res = read_source_snippet_checked(
src_file, std::numeric_limits<int>::max(), opt);
expect(int_max_res.has_value());
ResolveOptions tiny_scan = opt;
tiny_scan.max_source_scan_bytes = 32;
auto scan_res = read_source_snippet_checked(src_file, 15, tiny_scan);
expect(!scan_res.has_value());
expect_eq(scan_res.error().code().value,
static_cast<std::int32_t>(StacktraceErrorCode::scan_limit_exceeded));
// 4. Resolver cache hit, module invalidation, and entry/byte cap eviction.
Resolver resolver{2, kDefaultResolverCacheBytes};
auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 4});
require(raw.has_value() && !raw->frames.empty());
ResolveOptions sym_opt = opt;
sym_opt.source_snippets = false;
auto r1 = resolver.resolve(*raw, sym_opt);
require(r1.has_value());
expect(resolver.cache_entries() <= 2);
std::string first_mod;
for (const auto& f : raw->frames) {
if (!f.module_id.empty()) {
first_mod = f.module_id;
break;
}
}
if (!first_mod.empty()) {
(void)resolver.invalidate_module(first_mod);
}
resolver.clear_cache();
expect_eq(resolver.cache_entries(), std::size_t{0});
expect_eq(resolver.cache_bytes(), std::size_t{0});
std::filesystem::remove_all(base);
}
Void::Testing::Test stacktrace_cancellation_deadline_and_subprocess_crash()
{
auto raw = nested_capture_helper(CaptureOptions{.skip = 0, .max_frames = 4});
require(raw.has_value() && !raw->frames.empty());
// Pre-cancelled stop_token marks incomplete = true while retaining raw frames.
std::stop_source ss;
ss.request_stop();
ResolveOptions cancelled_opt;
cancelled_opt.stop = ss.get_token();
auto cres = resolve(*raw, cancelled_opt);
require(cres.has_value());
expect(cres->incomplete);
expect_eq(cres->frames.size(), raw->frames.size());
expect(cres->frames[0].status == FrameResolveStatus::cancelled);
expect_eq(cres->frames[0].raw.address, raw->frames[0].address);
// Expired ManualClock deadline also marks incomplete = true cleanly.
Void::Time::ManualClock clock;
const auto past = clock.now();
(void)clock.advance(std::chrono::seconds{1});
ResolveOptions timeout_opt;
timeout_opt.clock = &clock;
timeout_opt.deadline = past;
auto tres = resolve(*raw, timeout_opt);
require(tres.has_value());
expect(tres->incomplete);
expect(tres->frames[0].status == FrameResolveStatus::timed_out);
#ifndef _WIN32
// Async-signal-safe fatal marker writer writes clean ASCII record.
int pipefd[2]{-1, -1};
require(::pipe(pipefd) == 0);
expect(write_fatal_signal_marker(pipefd[1], SIGABRT));
::close(pipefd[1]);
char buf[128]{};
const auto n = ::read(pipefd[0], buf, sizeof(buf) - 1);
::close(pipefd[0]);
require(n > 0);
const std::string marker{buf, static_cast<std::size_t>(n)};
expect(marker.find("VOID_FATAL_SIGNAL sig=") != std::string::npos);
// Subprocess crash isolation for fatal child aborts (replaced in-process signal UB).
const std::string self_exe = Void::Testing::current_executable_path();
if (!self_exe.empty()) {
const std::vector<std::string> args{"--selftest-child", "abort"};
const auto run = Void::Testing::run_isolated_subprocess(
self_exe,
args,
Void::Testing::ProcessTestOptions{.timeout = std::chrono::seconds{5}});
expect(run.outcome == Void::Testing::ProcessOutcome::crashed);
expect_eq(run.term_signal, SIGABRT);
}
#endif
}