Core: add configurable startup log rotation
This commit is contained in:
1 parent
a277f2102b
commit
9637f1eef7
9 files changed
+361
-27
No files matched your search
+22
-1
@@ -1,5 +1,11 @@
|
||||
cmake_minimum_required(VERSION 4.0.0)
|
||||
project(EchoionCore VERSION 1.0.0 LANGUAGES CXX)
|
||||
if(NOT DEFINED ECHOION_PRODUCT_VERSION)
|
||||
set(ECHOION_PRODUCT_VERSION 0.0.0)
|
||||
endif()
|
||||
if(NOT DEFINED ECHOION_COMPONENT_VERSION)
|
||||
set(ECHOION_COMPONENT_VERSION "${ECHOION_PRODUCT_VERSION}")
|
||||
endif()
|
||||
project(EchoionCore VERSION "${ECHOION_PRODUCT_VERSION}" LANGUAGES CXX)
|
||||
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
set(CMAKE_CXX_STANDARD 26)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -11,6 +17,8 @@ file(GLOB_RECURSE CORE_SOURCES
|
||||
"src/**.cpp"
|
||||
)
|
||||
add_library(EchoionCore SHARED ${CORE_SOURCES})
|
||||
target_compile_definitions(EchoionCore PRIVATE
|
||||
ECHOION_CORE_VERSION="${ECHOION_COMPONENT_VERSION}")
|
||||
|
||||
add_library(Echoion::Core ALIAS EchoionCore)
|
||||
|
||||
@@ -150,6 +158,19 @@ else()
|
||||
target_compile_options(EchoionCore PRIVATE -Wall -Wextra -Wpedantic)
|
||||
endif()
|
||||
|
||||
if(BUILD_TESTS)
|
||||
add_executable(echoion_log_rotation_tests
|
||||
tests/test_log_rotation.cpp
|
||||
src/LogRotation.cpp
|
||||
)
|
||||
target_include_directories(echoion_log_rotation_tests PRIVATE
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/include"
|
||||
)
|
||||
target_compile_features(echoion_log_rotation_tests PRIVATE cxx_std_26)
|
||||
add_test(NAME echoion_log_rotation_tests
|
||||
COMMAND echoion_log_rotation_tests)
|
||||
endif()
|
||||
|
||||
# Precompiled headers for the heavy translation units (MusicManager.cpp ~2.4k
|
||||
# lines, Core.cpp, YouTubeClient.cpp). These pull in the same expensive standard
|
||||
# and Void headers, so compiling them once cuts a large slice off build time.
|
||||
|
||||
@@ -187,7 +187,8 @@ namespace Echoion::Core
|
||||
|
||||
// Build the console + split-file logging stack and install it as
|
||||
// the global Void::Log sink (logSink_ must outlive logging).
|
||||
void installLogging(const std::filesystem::path& logDirectory);
|
||||
void installLogging(const std::filesystem::path& logDirectory,
|
||||
const Api::LoggingConfig& config);
|
||||
|
||||
// Guard helper: ok if initialized, else a ServiceUnavailable error.
|
||||
[[nodiscard]] Api::Result<void> requireInitialized() const noexcept;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <filesystem>
|
||||
#include <system_error>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
// Archive a non-empty active log into <directory>/history and prune the
|
||||
// oldest archives. This is intentionally performed before opening the
|
||||
// logger so every process start gets a fresh active file.
|
||||
[[nodiscard]] std::error_code
|
||||
rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept;
|
||||
} // namespace Echoion::Core
|
||||
@@ -28,6 +28,24 @@ namespace Echoion::Core
|
||||
config.bot.language = "en";
|
||||
}
|
||||
|
||||
const std::filesystem::path logFile{config.logging.fileName};
|
||||
if (config.logging.fileName.empty() || logFile.is_absolute() ||
|
||||
logFile.has_parent_path() || logFile.filename() != logFile ||
|
||||
logFile == "." || logFile == "..") {
|
||||
config.logging.fileName = "echoion.log";
|
||||
}
|
||||
config.logging.maxFileSizeBytes = std::clamp<uint64_t>(
|
||||
config.logging.maxFileSizeBytes, 64 * 1024, 1024ULL * 1024 * 1024);
|
||||
config.logging.maxFiles =
|
||||
std::clamp<uint32_t>(config.logging.maxFiles, 1, 1000);
|
||||
static constexpr std::array<std::string_view, 8> kLogLevels = {
|
||||
"trace", "debug", "info", "warning",
|
||||
"warn", "error", "critical", "fatal"};
|
||||
if (std::ranges::find(kLogLevels, config.logging.level) ==
|
||||
kLogLevels.end()) {
|
||||
config.logging.level = "debug";
|
||||
}
|
||||
|
||||
// Keep partially specified updater sections usable. Security-sensitive
|
||||
// URL/key validation happens in the host updater before the policy is
|
||||
// persisted or used; normalization here only supplies structural
|
||||
|
||||
+52
-24
@@ -1,6 +1,7 @@
|
||||
#include "PluginTypes.hpp"
|
||||
#include "echoion/core/ConfigLoader.hpp"
|
||||
#include "echoion/core/Core.hpp"
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
#include "echoion/core/PluginHost.hpp"
|
||||
#include "echoion/core/RpcDtos.hpp"
|
||||
#include "echoion/core/TeamSpeakDirectoryService.hpp"
|
||||
@@ -16,8 +17,8 @@
|
||||
#include <Void/Log/Formatter.hpp>
|
||||
#include <Void/Log/Log.hpp>
|
||||
#include <Void/Log/LoggingAdapter.hpp>
|
||||
#include <Void/Log/RotatingFileLogger.hpp>
|
||||
#include <Void/Log/Sinks.hpp>
|
||||
#include <Void/Log/SplitFileLogger.hpp>
|
||||
#include <Void/Text/Base64.hpp>
|
||||
#include <algorithm>
|
||||
#include <cstdlib>
|
||||
@@ -91,31 +92,57 @@ namespace Echoion::Core
|
||||
return "application/octet-stream";
|
||||
}
|
||||
|
||||
// Build the console + split-file logging stack and install it as the
|
||||
// process-wide Void::Log sink. Replaces the old ILogger/LoggerRegistry
|
||||
// indirection; every ECHOION_LOG_* macro is now a Void::Log:: call.
|
||||
// Build the configurable console + rolling-file logging stack.
|
||||
[[nodiscard]] std::shared_ptr<Void::Logging::MultiLogger>
|
||||
buildLogSink(const std::filesystem::path& logDirectory)
|
||||
buildLogSink(const std::filesystem::path& logDirectory,
|
||||
const Api::LoggingConfig& config)
|
||||
{
|
||||
namespace VL = Void::Logging;
|
||||
auto multi = std::make_shared<VL::MultiLogger>();
|
||||
auto formatter = std::make_shared<const VL::PatternFormatter>(
|
||||
"[{time}] [{level}] [{thread}] {file} - {message}");
|
||||
|
||||
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
|
||||
console->set_formatter(formatter);
|
||||
multi->add(std::move(console));
|
||||
if (config.console) {
|
||||
auto console = std::make_shared<VL::ConsoleLogger>(std::cout);
|
||||
console->set_formatter(formatter);
|
||||
multi->add(std::move(console));
|
||||
}
|
||||
|
||||
VL::SplitFileOptions opts;
|
||||
opts.combined = true;
|
||||
opts.max_bytes = 10 * 1024 * 1024;
|
||||
opts.max_files = 5;
|
||||
if (auto fileSink = VL::SplitFileLogger::open(logDirectory, opts)) {
|
||||
VL::RotatingFileOptions opts;
|
||||
opts.max_bytes = static_cast<std::size_t>(config.maxFileSizeBytes);
|
||||
opts.max_files = config.maxFiles;
|
||||
const auto logPath = logDirectory / config.fileName;
|
||||
if (auto rotationError =
|
||||
rotateLogOnStartup(logPath, config.maxFiles)) {
|
||||
std::cerr << "Echoion: cannot rotate startup log '" << logPath
|
||||
<< "': " << rotationError.message() << '\n';
|
||||
} else if (auto fileSink =
|
||||
VL::RotatingFileLogger::open(logPath, opts)) {
|
||||
(*fileSink)->set_formatter(formatter);
|
||||
multi->add(std::shared_ptr<VL::Logger>(std::move(*fileSink)));
|
||||
}
|
||||
return multi;
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Log::Level logLevel(std::string_view level)
|
||||
{
|
||||
if (level == "trace") {
|
||||
return Void::Log::Level::Trace;
|
||||
}
|
||||
if (level == "info") {
|
||||
return Void::Log::Level::Info;
|
||||
}
|
||||
if (level == "warning" || level == "warn") {
|
||||
return Void::Log::Level::Warning;
|
||||
}
|
||||
if (level == "error") {
|
||||
return Void::Log::Level::Error;
|
||||
}
|
||||
if (level == "critical" || level == "fatal") {
|
||||
return Void::Log::Level::Fatal;
|
||||
}
|
||||
return Void::Log::Level::Debug;
|
||||
}
|
||||
} // namespace
|
||||
} // namespace Echoion::Core
|
||||
|
||||
@@ -134,11 +161,12 @@ namespace Echoion::Core
|
||||
|
||||
Core::Core() = default;
|
||||
|
||||
void Core::installLogging(const std::filesystem::path& logDirectory)
|
||||
void Core::installLogging(const std::filesystem::path& logDirectory,
|
||||
const Api::LoggingConfig& config)
|
||||
{
|
||||
logSink_ = buildLogSink(logDirectory);
|
||||
logSink_ = buildLogSink(logDirectory, config);
|
||||
Void::Log::set_sink(Void::Log::make_sink(logSink_));
|
||||
Void::Log::set_min_level(Void::Log::Level::Debug);
|
||||
Void::Log::set_min_level(logLevel(config.level));
|
||||
}
|
||||
|
||||
Api::Result<void> Core::requireInitialized() const noexcept
|
||||
@@ -173,13 +201,6 @@ namespace Echoion::Core
|
||||
const auto stateDir = stateDirectory(configPath);
|
||||
std::error_code stateDirectoryError;
|
||||
std::filesystem::create_directories(stateDir, stateDirectoryError);
|
||||
installLogging(stateDir / "logs");
|
||||
if (stateDirectoryError) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to create state directory '{}': {}",
|
||||
stateDir.string(), stateDirectoryError.message()));
|
||||
}
|
||||
|
||||
// Load config from file (Core-internal, Plugin doesn't need to know
|
||||
// about AppConfig structure)
|
||||
@@ -201,6 +222,13 @@ namespace Echoion::Core
|
||||
} else {
|
||||
config_ = *configResult;
|
||||
}
|
||||
installLogging(stateDir / "logs", config_.logging);
|
||||
if (stateDirectoryError) {
|
||||
Void::Log::warn(
|
||||
"Core", "{}",
|
||||
std::format("Failed to create state directory '{}': {}",
|
||||
stateDir.string(), stateDirectoryError.message()));
|
||||
}
|
||||
|
||||
// Initialize global ConfigManager with loaded config
|
||||
configManager_.updateConfig(config_, false);
|
||||
@@ -1856,7 +1884,7 @@ namespace Echoion::Core
|
||||
return {};
|
||||
}
|
||||
|
||||
std::string Core::getVersion() const { return Api::VERSION_STRING; }
|
||||
std::string Core::getVersion() const { return ECHOION_CORE_VERSION; }
|
||||
|
||||
std::chrono::system_clock::time_point Core::getUptime() const
|
||||
{
|
||||
|
||||
+1
-1
@@ -115,7 +115,7 @@ extern "C"
|
||||
return Void::Plugin::PluginInfo{
|
||||
.abi_version = Void::Plugin::ABI_VERSION,
|
||||
.name = "Echoion",
|
||||
.plugin_version = Echoion::Api::VERSION_STRING,
|
||||
.plugin_version = ECHOION_CORE_VERSION,
|
||||
.description = "Echoion TeamSpeak music bot core"};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <ctime>
|
||||
#include <format>
|
||||
#include <vector>
|
||||
|
||||
namespace Echoion::Core
|
||||
{
|
||||
namespace
|
||||
{
|
||||
[[nodiscard]] std::string archiveTimestamp()
|
||||
{
|
||||
using namespace std::chrono;
|
||||
const auto now = system_clock::now();
|
||||
const auto secondsPart = floor<seconds>(now);
|
||||
const auto micros = duration_cast<microseconds>(now - secondsPart);
|
||||
const std::time_t raw = system_clock::to_time_t(now);
|
||||
std::tm utc{};
|
||||
#ifdef _WIN32
|
||||
gmtime_s(&utc, &raw);
|
||||
#else
|
||||
gmtime_r(&raw, &utc);
|
||||
#endif
|
||||
return std::format("{:04}{:02}{:02}-{:02}{:02}{:02}-{:06}",
|
||||
utc.tm_year + 1900, utc.tm_mon + 1, utc.tm_mday,
|
||||
utc.tm_hour, utc.tm_min, utc.tm_sec,
|
||||
micros.count());
|
||||
}
|
||||
|
||||
[[nodiscard]] bool isArchiveFor(const std::filesystem::path& path,
|
||||
const std::filesystem::path& active)
|
||||
{
|
||||
const auto name = path.filename().string();
|
||||
const auto prefix = active.stem().string() + "-";
|
||||
return name.starts_with(prefix) &&
|
||||
path.extension() == active.extension();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
std::error_code rotateLogOnStartup(const std::filesystem::path& activeLog,
|
||||
std::size_t maxFiles) noexcept
|
||||
{
|
||||
std::error_code error;
|
||||
const auto status = std::filesystem::symlink_status(activeLog, error);
|
||||
if (error && error != std::errc::no_such_file_or_directory) {
|
||||
return error;
|
||||
}
|
||||
error.clear();
|
||||
|
||||
const bool exists = std::filesystem::exists(status);
|
||||
if (exists && std::filesystem::is_symlink(status)) {
|
||||
return std::make_error_code(
|
||||
std::errc::too_many_symbolic_link_levels);
|
||||
}
|
||||
|
||||
const auto history = activeLog.parent_path() / "history";
|
||||
std::filesystem::create_directories(activeLog.parent_path(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
|
||||
if (exists) {
|
||||
if (!std::filesystem::is_regular_file(status)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
const auto size = std::filesystem::file_size(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (size == 0 || maxFiles == 0) {
|
||||
std::filesystem::remove(activeLog, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
} else {
|
||||
std::filesystem::create_directories(history, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
const auto timestamp = archiveTimestamp();
|
||||
auto archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp +
|
||||
activeLog.extension().string());
|
||||
for (std::size_t suffix = 1;
|
||||
std::filesystem::exists(archived, error) && !error;
|
||||
++suffix) {
|
||||
archived = history / (activeLog.stem().string() + "-" +
|
||||
timestamp + "-" +
|
||||
std::to_string(suffix) +
|
||||
activeLog.extension().string());
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::filesystem::rename(activeLog, archived, error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const auto historyStatus =
|
||||
std::filesystem::symlink_status(history, error);
|
||||
if (error == std::errc::no_such_file_or_directory ||
|
||||
historyStatus.type() == std::filesystem::file_type::not_found) {
|
||||
return {};
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (!std::filesystem::is_directory(historyStatus) ||
|
||||
std::filesystem::is_symlink(historyStatus)) {
|
||||
return std::make_error_code(std::errc::invalid_argument);
|
||||
}
|
||||
std::vector<std::filesystem::path> archives;
|
||||
for (std::filesystem::directory_iterator iterator(history, error), end;
|
||||
!error && iterator != end; iterator.increment(error)) {
|
||||
const auto entryStatus = iterator->symlink_status(error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
if (std::filesystem::is_regular_file(entryStatus) &&
|
||||
isArchiveFor(iterator->path(), activeLog)) {
|
||||
archives.push_back(iterator->path());
|
||||
}
|
||||
}
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
std::ranges::sort(archives);
|
||||
while (archives.size() > maxFiles) {
|
||||
std::filesystem::remove(archives.front(), error);
|
||||
if (error) {
|
||||
return error;
|
||||
}
|
||||
archives.erase(archives.begin());
|
||||
}
|
||||
return {};
|
||||
}
|
||||
} // namespace Echoion::Core
|
||||
@@ -41,6 +41,33 @@ int main()
|
||||
const auto defaults = ConfigLoader::createDefaultConfig();
|
||||
expect(!defaults.urlShortening.enabled,
|
||||
"generated defaults keep URL shortening disabled");
|
||||
expect(defaults.logging.fileName == "echoion.log" &&
|
||||
defaults.logging.maxFiles == 10,
|
||||
"generated defaults configure bounded rolling logs");
|
||||
|
||||
const auto logging = ConfigLoader::loadFromJson(R"({
|
||||
"logging": {
|
||||
"level": "verbose",
|
||||
"fileName": "../outside.log",
|
||||
"maxFileSizeBytes": 1,
|
||||
"maxFiles": 0
|
||||
}
|
||||
})");
|
||||
expect(logging.has_value(), "logging configuration parses");
|
||||
if (logging) {
|
||||
expect(logging->logging.level == "debug",
|
||||
"invalid log level is normalized");
|
||||
expect(logging->logging.fileName == "echoion.log",
|
||||
"log file cannot escape the state log directory");
|
||||
expect(logging->logging.maxFileSizeBytes == 64 * 1024,
|
||||
"log size is clamped to a safe minimum");
|
||||
expect(logging->logging.maxFiles == 1,
|
||||
"at least one rolled log is retained");
|
||||
}
|
||||
const auto parentLog =
|
||||
ConfigLoader::loadFromJson(R"({"logging":{"fileName":".."}})");
|
||||
expect(parentLog && parentLog->logging.fileName == "echoion.log",
|
||||
"parent-directory logging filename is normalized");
|
||||
|
||||
expectShortening("legacy disabled",
|
||||
R"({
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "echoion/core/LogRotation.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
#include <string_view>
|
||||
|
||||
namespace
|
||||
{
|
||||
int failures = 0;
|
||||
|
||||
void expect(bool condition, std::string_view message)
|
||||
{
|
||||
if (!condition) {
|
||||
std::cerr << "FAILED: " << message << '\n';
|
||||
++failures;
|
||||
}
|
||||
}
|
||||
|
||||
std::size_t archiveCount(const std::filesystem::path& history)
|
||||
{
|
||||
std::size_t count = 0;
|
||||
std::error_code error;
|
||||
for (std::filesystem::directory_iterator iterator(history, error), end;
|
||||
!error && iterator != end; iterator.increment(error)) {
|
||||
if (iterator->is_regular_file()) {
|
||||
++count;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
int main()
|
||||
{
|
||||
const auto root =
|
||||
std::filesystem::temp_directory_path() / "echoion-log-rotation-test";
|
||||
std::error_code error;
|
||||
std::filesystem::remove_all(root, error);
|
||||
std::filesystem::create_directories(root, error);
|
||||
const auto active = root / "echoion.log";
|
||||
|
||||
{
|
||||
std::ofstream file(active);
|
||||
file << "first run\n";
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(!error, "first startup rotation succeeds");
|
||||
expect(!std::filesystem::exists(active),
|
||||
"startup rotation leaves no old active file");
|
||||
expect(archiveCount(root / "history") == 1, "first run is archived");
|
||||
|
||||
for (int run = 0; run < 3; ++run) {
|
||||
{
|
||||
std::ofstream file(active);
|
||||
file << "run " << run << '\n';
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(!error, "subsequent startup rotation succeeds");
|
||||
}
|
||||
expect(archiveCount(root / "history") == 2,
|
||||
"startup rotation prunes to configured history count");
|
||||
|
||||
{
|
||||
std::ofstream file(active);
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(!error && !std::filesystem::exists(active),
|
||||
"empty active file is removed instead of archived");
|
||||
|
||||
std::filesystem::remove_all(root / "history", error);
|
||||
{
|
||||
std::ofstream invalidHistory(root / "history");
|
||||
invalidHistory << "not a directory\n";
|
||||
}
|
||||
error = Echoion::Core::rotateLogOnStartup(active, 2);
|
||||
expect(error == std::errc::invalid_argument,
|
||||
"non-directory history path was accepted");
|
||||
|
||||
std::filesystem::remove_all(root, error);
|
||||
return failures == 0 ? 0 : 1;
|
||||
}
|
||||
Reference in new issue
Block a user