From 827c9e150a622f5a2e9322dd171b84ed00918267 Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 6 Jul 2026 14:42:28 +0300 Subject: [PATCH] change rotation Signed-off-by: faumaray --- CMakeLists.txt | 8 ++ cmake/Dependencies.cmake | 4 +- include/Void/Log/Detail/RollingFile.hpp | 61 +++++++++++-- include/Void/Log/SplitFileLogger.hpp | 25 +++++- src/Log/RollingFile.cpp | 114 ++++++++++++++++++++---- src/Log/SplitFileLogger.cpp | 38 +++++++- tests/standalone/Log/FileSinks.cpp | 4 +- 7 files changed, 221 insertions(+), 33 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b4a1f5f..1fbceca 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -5,8 +5,16 @@ option(VOID_WARNINGS_AS_ERRORS "Treat compiler warnings as errors" OFF) option(VOID_ENABLE_ASAN "Enable AddressSanitizer (Clang/GCC)" OFF) option(VOID_ENABLE_UBSAN "Enable UndefinedBehaviorSanitizer (Clang/GCC)" OFF) option(VOID_ENABLE_COVERAGE "Enable code coverage instrumentation" OFF) + set(CMAKE_CXX_STANDARD 26) set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) +set(CMAKE_CXX_MODULE_MAP_FORMAT "gcc") +set(CXX_SCAN_FOR_MODULES OFF) +# , , etc. +if(CMAKE_CXX_COMPILER_ID STREQUAL "GNU" AND CMAKE_CXX_COMPILER_VERSION VERSION_GREATER_EQUAL 16) + add_compile_options($<$:-freflection>) +endif() include(GNUInstallDirs) include(CMakePackageConfigHelpers) diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index 7e502fb..8be9e35 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -46,8 +46,8 @@ function(void_fetch_dependency DEP_NAME) return() endif() - if(DEP_NAME STREQUAL "SQLite") - if(NOT TARGET SQLite::SQLite3) + if(DEP_NAME STREQUAL "SQLite3") + if(NOT TARGET SQLite3::SQLite3) find_package(SQLite3 REQUIRED) endif() return() diff --git a/include/Void/Log/Detail/RollingFile.hpp b/include/Void/Log/Detail/RollingFile.hpp index 13b20a7..40deb65 100644 --- a/include/Void/Log/Detail/RollingFile.hpp +++ b/include/Void/Log/Detail/RollingFile.hpp @@ -1,8 +1,10 @@ #pragma once +#include #include #include #include +#include #include namespace Void::Logging::Detail @@ -12,27 +14,70 @@ namespace Void::Logging::Detail std::size_t max_files = 5; }; + /// 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. /// - /// On reaching max_bytes the files shift (`app.log` → `app.log.1` → …); - /// at most max_files rotated files are kept, the oldest is removed. With - /// max_files == 0 the file is truncated on rotation instead of kept. + /// 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 `-` — 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//`). + /// max_files does not apply to this path: nothing is ever deleted, + /// every snapshot is kept. class RollingFile { public: - RollingFile(std::filesystem::path path, RollingFileOptions opt); + RollingFile(std::filesystem::path path, RollingFileOptions opt, + bool self_rotate = true); /// Open for append (creating parent dirs). False on failure. [[nodiscard]] bool open(); - /// Append a line (a trailing '\n' is added) and rotate if the - /// file then exceeds max_bytes. No-op if not open. + /// 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(); + /// 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 { return m_file.is_open(); @@ -46,11 +91,15 @@ namespace Void::Logging::Detail private: void rotate(); + void prune_archives(); std::filesystem::path m_path; RollingFileOptions m_opt; + bool m_self_rotate; std::ofstream m_file; std::size_t m_current_bytes{0}; + std::chrono::time_point m_creationTime; + std::chrono::time_point m_rotationTime; }; } // namespace Void::Logging::Detail diff --git a/include/Void/Log/SplitFileLogger.hpp b/include/Void/Log/SplitFileLogger.hpp index 6d7e403..d9437fa 100644 --- a/include/Void/Log/SplitFileLogger.hpp +++ b/include/Void/Log/SplitFileLogger.hpp @@ -6,6 +6,7 @@ #include #include +#include #include #include #include @@ -21,6 +22,9 @@ namespace Void::Logging /// to the per-level files. bool combined = true; std::size_t max_bytes = 1024 * 1024; + /// Unused. Rotation here is a synchronized, unbounded history + /// (see class comment) rather than a max_files-bounded rotation, + /// so this has no effect — kept only for API compatibility. std::size_t max_files = 5; Mode mode = Mode::Async; std::size_t capacity = 512; @@ -29,9 +33,18 @@ namespace Void::Logging /// File sink that routes each entry to a per-level file /// (`/.log`, e.g. `error.log`, lazily created) and, when - /// enabled, also to a single combined `/all.log`. Each file rolls - /// independently. Async by default. An installed Formatter replaces the - /// default "[level] message" rendering (no color in files). + /// enabled, also to a single combined `/all.log`. Async by default. + /// An installed Formatter replaces the default "[level] message" + /// rendering (no color in files). + /// + /// Rotation is synchronized across the whole group rather than + /// per-file: as soon as any one file — a per-level file or the + /// combined file — reaches max_bytes, every file currently open (even + /// ones well under the limit) is moved, under its own name unchanged, + /// into `/history//`, where `` + /// marks when this batch of files started filling up. Fresh, empty + /// files then continue at their usual paths. Every snapshot is kept + /// indefinitely — see SplitFileOptions::max_files. class SplitFileLogger final : public Logger { public: @@ -74,11 +87,17 @@ namespace Void::Logging Detail::RollingFile& file_for(Level level); void append(const Entry& entry); + /// If any owned file has reached max_bytes, sweep every + /// owned file into a shared history/ snapshot + /// directory and start each one fresh. + void maybe_rotate_group(); + std::filesystem::path m_dir; Options m_options; std::map m_per_level; std::unique_ptr m_combined; std::shared_ptr m_formatter; + std::chrono::system_clock::time_point m_epoch_start; }; } // namespace Void::Logging diff --git a/src/Log/RollingFile.cpp b/src/Log/RollingFile.cpp index 41bd4b1..5fdb532 100644 --- a/src/Log/RollingFile.cpp +++ b/src/Log/RollingFile.cpp @@ -1,14 +1,45 @@ #include +#include +#include +#include #include #include #include +#include namespace Void::Logging::Detail { + namespace + { + std::tm to_utc_tm(std::time_t tt) + { + std::tm tm{}; +#if defined(_WIN32) + gmtime_s(&tm, &tt); +#else + gmtime_r(&tt, &tm); +#endif + return tm; + } + } // namespace - RollingFile::RollingFile(std::filesystem::path path, RollingFileOptions opt) - : m_path(std::move(path)), m_opt(opt) + std::string format_timestamp(std::chrono::system_clock::time_point tp) + { + using namespace std::chrono; + const auto since_epoch = tp.time_since_epoch(); + const auto secs = duration_cast(since_epoch); + const auto us = duration_cast(since_epoch - secs); + const std::tm tm = to_utc_tm(system_clock::to_time_t(tp)); + return std::format("{:04d}{:02d}{:02d}-{:02d}{:02d}{:02d}-{:06d}", + tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec, + static_cast(us.count())); + } + + RollingFile::RollingFile(std::filesystem::path path, RollingFileOptions opt, + bool self_rotate) + : m_path(std::move(path)), m_opt(opt), m_self_rotate(self_rotate) { } @@ -23,6 +54,7 @@ namespace Void::Logging::Detail std::filesystem::file_size(m_path, ec)); } m_file.open(m_path, std::ios::app); + m_creationTime = std::chrono::system_clock::now(); return m_file.is_open(); } @@ -34,7 +66,7 @@ namespace Void::Logging::Detail m_file.write(line.data(), static_cast(line.size())); m_file.put('\n'); m_current_bytes += line.size() + 1; - if (m_current_bytes >= m_opt.max_bytes) { + if (m_self_rotate && m_current_bytes >= m_opt.max_bytes) { rotate(); } } @@ -48,29 +80,79 @@ namespace Void::Logging::Detail void RollingFile::rotate() { + m_rotationTime = std::chrono::system_clock::now(); m_file.close(); std::error_code ec; - const auto numbered = [&](std::size_t n) { - auto p = m_path; - p += std::format(".{}", n); - return p; - }; - std::filesystem::remove(numbered(m_opt.max_files), ec); - for (std::size_t n = m_opt.max_files; n > 1; --n) { - const auto from = numbered(n - 1); - if (std::filesystem::exists(from, ec)) { - std::filesystem::rename(from, numbered(n), ec); - } - } if (m_opt.max_files > 0) { - std::filesystem::rename(m_path, numbered(1), ec); + // 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); + + // Build new name: -. + auto stem = m_path.stem(); + auto ext = m_path.extension(); + auto new_filename = stem.string() + "-" + + format_timestamp(m_rotationTime) + ext.string(); + auto archived = history_dir / new_filename; + + std::filesystem::rename(m_path, archived, ec); + prune_archives(); // now looks inside history/ } else { std::filesystem::remove(m_path, ec); } m_file.open(m_path, std::ios::trunc); 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)) { + return; + } + + auto stem = m_path.stem().string(); + std::vector archives; + std::error_code ec; + try { + for (const auto& entry : + std::filesystem::directory_iterator(history_dir, ec)) { + if (ec) { + return; + } + auto filename = entry.path().filename().string(); + if (filename.starts_with(stem + "-")) { + archives.push_back(entry.path()); + } + } + } catch (const std::filesystem::filesystem_error&) { + return; // best-effort pruning only + } + + std::sort(archives.begin(), archives.end()); + while (archives.size() > m_opt.max_files) { + std::filesystem::remove(archives.front(), ec); + archives.erase(archives.begin()); + } + } + + void RollingFile::snapshot_into(const std::filesystem::path& dir) + { + m_rotationTime = std::chrono::system_clock::now(); + m_file.close(); + std::error_code ec; + std::filesystem::create_directories(dir, ec); + std::filesystem::rename(m_path, dir / m_path.filename(), ec); + + m_file.open(m_path, std::ios::trunc); + m_current_bytes = 0; + m_creationTime = m_rotationTime; } } // namespace Void::Logging::Detail diff --git a/src/Log/SplitFileLogger.cpp b/src/Log/SplitFileLogger.cpp index 20f80be..70119b2 100644 --- a/src/Log/SplitFileLogger.cpp +++ b/src/Log/SplitFileLogger.cpp @@ -24,7 +24,8 @@ namespace Void::Logging SplitFileLogger::SplitFileLogger(std::filesystem::path dir, Options options) : Logger(options.mode, options.capacity, options.policy), - m_dir(std::move(dir)), m_options(options) + m_dir(std::move(dir)), m_options(options), + m_epoch_start(std::chrono::system_clock::now()) { std::error_code ec; std::filesystem::create_directories(m_dir, ec); @@ -34,9 +35,10 @@ namespace Void::Logging } if (m_options.combined) { m_combined = std::make_unique( - m_dir / "all.log", + m_dir / "trace.log", Detail::RollingFileOptions{m_options.max_bytes, - m_options.max_files}); + m_options.max_files}, + /*self_rotate=*/false); (void)m_combined->open(); } Void::Log::debug("Log.Split", "split logging into '{}'", @@ -63,7 +65,8 @@ namespace Void::Logging Detail::RollingFile file{ m_dir / level_filename(level), Detail::RollingFileOptions{m_options.max_bytes, - m_options.max_files}}; + m_options.max_files}, + /*self_rotate=*/false}; (void)file.open(); it = m_per_level.emplace(level, std::move(file)).first; } @@ -83,6 +86,33 @@ namespace Void::Logging if (m_combined) { m_combined->write(line); } + maybe_rotate_group(); + } + + void SplitFileLogger::maybe_rotate_group() + { + bool any_exceeds = m_combined && m_combined->exceeds_limit(); + if (!any_exceeds) { + for (const auto& [level, file] : m_per_level) { + if (file.exceeds_limit()) { + any_exceeds = true; + break; + } + } + } + if (!any_exceeds) { + return; + } + + const auto snapshot_dir = + m_dir / "history" / Detail::format_timestamp(m_epoch_start); + for (auto& [level, file] : m_per_level) { + file.snapshot_into(snapshot_dir); + } + if (m_combined) { + m_combined->snapshot_into(snapshot_dir); + } + m_epoch_start = std::chrono::system_clock::now(); } void SplitFileLogger::write(const Entry& entry) diff --git a/tests/standalone/Log/FileSinks.cpp b/tests/standalone/Log/FileSinks.cpp index 43f1fc7..b9d6d07 100644 --- a/tests/standalone/Log/FileSinks.cpp +++ b/tests/standalone/Log/FileSinks.cpp @@ -62,7 +62,7 @@ class SplitFileLoggerTests : public Void::Testing::Fixture log.info("info one"); log.error("error one"); } - const auto all = slurp(dir / "all.log"); + const auto all = slurp(dir / "trace.log"); Void::Testing::expect(all.find("info one") != std::string::npos); Void::Testing::expect(all.find("error one") != std::string::npos); } @@ -75,7 +75,7 @@ class SplitFileLoggerTests : public Void::Testing::Fixture .mode = Void::Logging::Mode::Immediate}}; log.info("solo"); } - Void::Testing::expect(!std::filesystem::exists(dir / "all.log")); + Void::Testing::expect(!std::filesystem::exists(dir / "trace.log")); Void::Testing::expect(std::filesystem::exists(dir / "info.log")); } };