From 2f1e75da37a6a73646e741cdbaac8ecdc8355e78 Mon Sep 17 00:00:00 2001 From: shweet Date: Sun, 22 Nov 2026 17:42:54 -0500 Subject: [PATCH] Keep the log file open, drop the stderr pipe thread A session log is written line by line through one open file. The last ten sessions are kept. FFmpeg's warnings and errors are appended to the log by the shell instead. --- src/log.cpp | 320 +++++++------------------------------------------ src/log.h | 24 +--- src/render.cpp | 31 ++--- 3 files changed, 59 insertions(+), 316 deletions(-) diff --git a/src/log.cpp b/src/log.cpp index c45942c..7a07895 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -1,169 +1,66 @@ #include "log.h" #include -#include -#include -#include #include #include #include -#include "file.h" -#include "path.h" #include "localization.h" +#include "path.h" #include "timestamp.h" -#if _WIN32 -#include -#include +#ifdef _WIN32 #include +#define getpid _getpid #else #include #endif -constexpr auto SESSION_LIMIT = 10; -constexpr std::uintmax_t DIRECTORY_SIZE_LIMIT = 100ull * 1024ull * 1024ull; -constexpr std::uintmax_t SESSION_SIZE_LIMIT = 25ull * 1024ull * 1024ull; +constexpr std::size_t SESSION_LIMIT = 10; -struct SessionFile +// Removes the oldest session logs, so that with the new one there are SESSION_LIMIT. Their names sort by time. +static void sessions_prune(const std::filesystem::path& directory) { - std::filesystem::path path; - std::filesystem::file_time_type time; - std::uintmax_t size = 0; -}; + std::vector paths; + std::error_code ec; + for (auto& entry : std::filesystem::directory_iterator(directory, ec)) + if (entry.path().extension() == ".log") + paths.push_back(entry.path()); + std::ranges::sort(paths); + for (std::size_t i = 0; i + SESSION_LIMIT <= paths.size(); ++i) + std::filesystem::remove(paths[i], ec); +} -static std::uint32_t process_id_get() +std::filesystem::path Logger::path() { -#if _WIN32 - return (std::uint32_t)_getpid(); + return logPath; +} + +void Logger::session_open(const std::filesystem::path& preferences) +{ + auto directory = preferences / "logs"; + std::error_code ec; + std::filesystem::create_directories(directory, ec); + sessions_prune(directory); + auto name = std::format("anm2ed_{}_{}.log", timestamp_get("%Y-%m-%d_%H-%M-%S"), (int)getpid()); + logPath = directory / path_from_utf8(name); +#ifdef _WIN32 + file = _wfopen(logPath.c_str(), L"ab"); #else - return (std::uint32_t)getpid(); + file = std::fopen(logPath.c_str(), "ab"); #endif + info(std::format("Initializing {}", localize.get(LABEL_APPLICATION_NAME, ENGLISH))); } -static std::filesystem::path session_path_get(const std::filesystem::path& directory) -{ - auto name = std::format("anm2ed_{}_{}.log", timestamp_get("%Y-%m-%d_%H-%M-%S"), process_id_get()); - return directory / "logs" / path_from_utf8(name); -} - -static std::vector session_files_get(const std::filesystem::path& directory, - const std::filesystem::path& currentPath) -{ - std::vector files; - std::error_code ec; - if (!std::filesystem::is_directory(directory, ec)) - return files; - - for (std::filesystem::directory_iterator it(directory, ec), end{}; !ec && it != end; it.increment(ec)) - { - auto path = it->path(); - if (path == currentPath || path.extension() != ".log") - continue; - std::error_code fileEc; - if (!std::filesystem::is_regular_file(path, fileEc)) - continue; - - auto size = std::filesystem::file_size(path, fileEc); - if (fileEc) - continue; - - auto time = std::filesystem::last_write_time(path, fileEc); - if (fileEc) - time = std::filesystem::file_time_type::min(); - - files.push_back({path, time, size}); - } - - return files; -} - -static void session_file_remove(const SessionFile& file, std::uintmax_t& totalSize) -{ - std::error_code ec; - std::filesystem::remove(file.path, ec); - if (!ec && totalSize >= file.size) - totalSize -= file.size; -} - -static void sessions_prune(const std::filesystem::path& directory, const std::filesystem::path& currentPath) -{ - auto files = session_files_get(directory, currentPath); - std::sort(files.begin(), files.end(), - [](const SessionFile& left, const SessionFile& right) { return left.time > right.time; }); - - std::uintmax_t totalSize = 0; - for (auto& file : files) - totalSize += file.size; - - while (files.size() >= SESSION_LIMIT) - { - session_file_remove(files.back(), totalSize); - files.pop_back(); - } - - while (totalSize > DIRECTORY_SIZE_LIMIT && !files.empty()) - { - session_file_remove(files.back(), totalSize); - files.pop_back(); - } -} - -static void legacy_log_remove(const std::filesystem::path& currentPath) -{ - auto directory = currentPath.parent_path().parent_path(); - if (directory.empty()) - return; - - auto legacyPath = directory / "log.txt"; - if (legacyPath == currentPath) - return; - - std::error_code ec; - std::filesystem::remove(legacyPath, ec); -} - -void Logger::write_raw(const std::string& message) +void Logger::write(Level level, const std::string& message) { + auto line = std::format("{} {} {}", LEVEL_STRINGS[level], timestamp_get("(%d-%B-%Y %I:%M:%S)"), message); std::lock_guard lock(mutex); - try - { - std::println("{}", message); - } - catch (...) - {} - if (!logPath.empty()) - { - try - { - auto lineSize = (std::uintmax_t)message.size() + 1; - auto isLineWithinLimit = logSize <= SESSION_SIZE_LIMIT && lineSize <= SESSION_SIZE_LIMIT - logSize; - if (isLineWithinLimit) - { - auto line = message + '\n'; - if (file_text_save(logPath, line, "ab")) - logSize += line.size(); - } - else if (!isLogLimitReached) - { - std::string line = - "[WARNING] Session log size limit reached; suppressing further file logs for this session.\n"; - if (logSize + line.size() <= SESSION_SIZE_LIMIT) - if (file_text_save(logPath, line, "ab")) - logSize += line.size(); - isLogLimitReached = true; - } - } - catch (...) - {} - } -} - -void Logger::write(const Level level, const std::string& message) -{ - std::string formatted = - std::format("{} {} {}", LEVEL_STRINGS[level], timestamp_get("(%d-%B-%Y %I:%M:%S)"), message); - write_raw(formatted); + std::println("{}", line); + if (!file) + return; + std::println(file, "{}", line); + std::fflush(file); } void Logger::info(const std::string& message) @@ -191,148 +88,12 @@ void Logger::command(const std::string& message) write(COMMAND, message); } -void Logger::stderr_pump() -{ - std::string pending; - std::array buffer = {}; - while (isStderrRedirecting) - { - int readBytes = 0; -#if _WIN32 - readBytes = _read(stderrPipeReadFd, buffer.data(), (unsigned int)buffer.size()); -#else - readBytes = (int)read(stderrPipeReadFd, buffer.data(), buffer.size()); -#endif - if (readBytes <= 0) - break; - - pending.append(buffer.data(), (std::size_t)readBytes); - - std::size_t lineEnd = 0; - while ((lineEnd = pending.find('\n')) != std::string::npos) - { - auto line = pending.substr(0, lineEnd); - if (!line.empty() && line.back() == '\r') - line.pop_back(); - if (!line.empty()) - write_raw(line); - pending.erase(0, lineEnd + 1); - } - } - - if (!pending.empty()) - write_raw(pending); -} - -void Logger::stderr_redirect_start() -{ - if (isStderrRedirecting) - return; - - int pipeFds[2]{-1, -1}; -#if _WIN32 - if (_pipe(pipeFds, 4096, _O_BINARY) != 0) - return; - stderrOriginalFd = _dup(_fileno(stderr)); - if (stderrOriginalFd < 0 || _dup2(pipeFds[1], _fileno(stderr)) != 0) - { - _close(pipeFds[0]); - _close(pipeFds[1]); - return; - } - _close(pipeFds[1]); -#else - if (pipe(pipeFds) != 0) - return; - stderrOriginalFd = dup(fileno(stderr)); - if (stderrOriginalFd < 0 || dup2(pipeFds[1], fileno(stderr)) < 0) - { - close(pipeFds[0]); - close(pipeFds[1]); - return; - } - close(pipeFds[1]); -#endif - - std::setvbuf(stderr, nullptr, _IONBF, 0); - - stderrPipeReadFd = pipeFds[0]; - isStderrRedirecting = true; - stderrThread = std::thread([this]() { stderr_pump(); }); -} - -void Logger::stderr_redirect_stop() -{ - if (!isStderrRedirecting) - return; - isStderrRedirecting = false; - - if (stderrOriginalFd >= 0) - { -#if _WIN32 - _dup2(stderrOriginalFd, _fileno(stderr)); - _close(stderrOriginalFd); -#else - dup2(stderrOriginalFd, fileno(stderr)); - close(stderrOriginalFd); -#endif - stderrOriginalFd = -1; - } - - if (stderrPipeReadFd >= 0) - { -#if _WIN32 - _close(stderrPipeReadFd); -#else - close(stderrPipeReadFd); -#endif - stderrPipeReadFd = -1; - } - - if (stderrThread.joinable()) - stderrThread.join(); -} - -void Logger::open(const std::filesystem::path& path) -{ - logPath = path; - logSize = 0; - isLogLimitReached = false; - if (!logPath.empty()) - { - std::error_code ec; - auto directory = logPath.parent_path(); - if (!directory.empty()) - std::filesystem::create_directories(directory, ec); - legacy_log_remove(logPath); - sessions_prune(directory, logPath); - logSize = std::filesystem::file_size(logPath, ec); - if (ec) - logSize = 0; - isLogLimitReached = logSize >= SESSION_SIZE_LIMIT; - } - stderr_redirect_start(); -} - -std::filesystem::path Logger::path() const -{ - return logPath; -} - -void Logger::session_open(const std::filesystem::path& directory) -{ - open(session_path_get(directory)); - info(std::format("Initializing {}", localize.get(LABEL_APPLICATION_NAME, ENGLISH))); -} - -Logger::Logger() = default; - Logger::~Logger() { - if (logPath.empty()) + if (!file) return; info("Exiting Anm2Ed"); - stderr_redirect_stop(); + std::fclose(file); } int log_exceptions(const std::function& callback) @@ -349,7 +110,6 @@ int log_exceptions(const std::function& callback) { logger.fatal("Unhandled non-standard exception"); } - return EXIT_FAILURE; } diff --git a/src/log.h b/src/log.h index 7b7fdb7..1d717e7 100644 --- a/src/log.h +++ b/src/log.h @@ -1,12 +1,11 @@ #pragma once -#include +#include #include #include #include #include #include -#include #if defined(INFO) #undef INFO @@ -42,34 +41,23 @@ constexpr std::string_view LEVEL_STRINGS[] = { }; #undef LEVELS +// Writes to stdout and, once a session is open, to its own file in the preferences' logs folder. +// The last SESSION_LIMIT sessions' files are kept. class Logger { std::filesystem::path logPath; - std::uintmax_t logSize = 0; + std::FILE* file = nullptr; std::mutex mutex; - std::thread stderrThread; - bool isStderrRedirecting = false; - bool isLogLimitReached = false; - int stderrPipeReadFd = -1; - int stderrPipeWriteFd = -1; - int stderrOriginalFd = -1; - - void stderr_redirect_start(); - void stderr_redirect_stop(); - void stderr_pump(); public: - std::filesystem::path path() const; + std::filesystem::path path(); void session_open(const std::filesystem::path&); - void write_raw(const std::string&); - void write(const Level, const std::string&); + void write(Level, const std::string&); void info(const std::string&); void warning(const std::string&); void error(const std::string&); void fatal(const std::string&); void command(const std::string&); - void open(const std::filesystem::path&); - Logger(); ~Logger(); }; diff --git a/src/render.cpp b/src/render.cpp index e50ce51..95cfccd 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -31,8 +31,8 @@ #include "ui/toast.h" bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path, - const std::vector& framePaths, const std::vector& audio, RenderType type, - int fps) + const std::vector& framePaths, const std::vector& audio, + RenderType type, int fps) { if (framePaths.empty() || ffmpegPath.empty() || path.empty()) return false; @@ -40,14 +40,6 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy auto pathString = path_to_utf8(path); auto ffmpegPathString = path_to_utf8(ffmpegPath); - auto loggerPath = logger.path(); - auto loggerPathString = path_to_utf8(loggerPath); -#if _WIN32 - auto ffmpegTempPath = loggerPath.parent_path() / "ffmpeg_log.temp.txt"; - auto ffmpegTempPathString = path_to_utf8(ffmpegTempPath); - std::error_code ffmpegTempError; - std::filesystem::remove(ffmpegTempPath, ffmpegTempError); -#endif std::filesystem::path audioPath; std::string audioInputArguments; @@ -75,14 +67,14 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy auto byteCount = audio.size() * sizeof(float); if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) { - auto audioDurationFilter = std::string{}; + auto audioDurationFilter = std::string{}; auto frameCount = (double)std::max((int)framePaths.size(), 1); auto expectedDurationSeconds = frameCount / (double)fps; if (expectedDurationSeconds > 0.0) audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds); - audioInputArguments = - std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", AUDIO_FREQUENCY, AUDIO_CHANNELS, path_to_utf8(audioPath)); + audioInputArguments = std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", AUDIO_FREQUENCY, AUDIO_CHANNELS, + path_to_utf8(audioPath)); switch (type) { @@ -111,8 +103,8 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy auto framePattern = temporaryDirectory / path_from_utf8("frame_%06d.png"); auto framePatternString = path_to_utf8(framePattern); - command = - std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps, framePatternString); + command = std::format("\"{0}\" -y -hide_banner -loglevel warning -framerate {1} -start_number 0 -i \"{2}\"", + ffmpegPathString, fps, framePatternString); if (!audioInputArguments.empty()) command += " " + audioInputArguments; @@ -152,6 +144,9 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy } } + // FFmpeg's warnings and errors go to the end of the log. + if (auto logPath = logger.path(); !logPath.empty()) + command += std::format(" 2>> \"{}\"", path_to_utf8(logPath)); #if _WIN32 command = "\"" + command + "\""; #endif @@ -382,9 +377,9 @@ void Recorder::finish() } else { - auto audio = options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector(); - auto isRendered = - animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps); + auto audio = + options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector(); + auto isRendered = animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps); toast_log(isRendered ? Level::INFO : Level::ERROR, isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); }