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.
This commit is contained in:
shweet committed 2026-11-22 17:42:54 -05:00
1 parent d2c0e32ff5
commit 2f1e75da37
3 files changed
+59 -316

No files matched your search

+40 -280
View File
@@ -1,169 +1,66 @@
#include "log.h" #include "log.h"
#include <algorithm> #include <algorithm>
#include <array>
#include <exception>
#include <filesystem>
#include <format> #include <format>
#include <print> #include <print>
#include <vector> #include <vector>
#include "file.h"
#include "path.h"
#include "localization.h" #include "localization.h"
#include "path.h"
#include "timestamp.h" #include "timestamp.h"
#if _WIN32 #ifdef _WIN32
#include <fcntl.h>
#include <io.h>
#include <process.h> #include <process.h>
#define getpid _getpid
#else #else
#include <unistd.h> #include <unistd.h>
#endif #endif
constexpr auto SESSION_LIMIT = 10; constexpr std::size_t SESSION_LIMIT = 10;
constexpr std::uintmax_t DIRECTORY_SIZE_LIMIT = 100ull * 1024ull * 1024ull;
constexpr std::uintmax_t SESSION_SIZE_LIMIT = 25ull * 1024ull * 1024ull;
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::vector<std::filesystem::path> paths;
std::filesystem::file_time_type time; std::error_code ec;
std::uintmax_t size = 0; 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 logPath;
return (std::uint32_t)_getpid(); }
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 #else
return (std::uint32_t)getpid(); file = std::fopen(logPath.c_str(), "ab");
#endif #endif
info(std::format("Initializing {}", localize.get(LABEL_APPLICATION_NAME, ENGLISH)));
} }
static std::filesystem::path session_path_get(const std::filesystem::path& directory) void Logger::write(Level level, const std::string& message)
{
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<SessionFile> session_files_get(const std::filesystem::path& directory,
const std::filesystem::path& currentPath)
{
std::vector<SessionFile> 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)
{ {
auto line = std::format("{} {} {}", LEVEL_STRINGS[level], timestamp_get("(%d-%B-%Y %I:%M:%S)"), message);
std::lock_guard lock(mutex); std::lock_guard lock(mutex);
try std::println("{}", line);
{ if (!file)
std::println("{}", message); return;
} std::println(file, "{}", line);
catch (...) std::fflush(file);
{}
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);
} }
void Logger::info(const std::string& message) void Logger::info(const std::string& message)
@@ -191,148 +88,12 @@ void Logger::command(const std::string& message)
write(COMMAND, message); write(COMMAND, message);
} }
void Logger::stderr_pump()
{
std::string pending;
std::array<char, 512> 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() Logger::~Logger()
{ {
if (logPath.empty()) if (!file)
return; return;
info("Exiting Anm2Ed"); info("Exiting Anm2Ed");
stderr_redirect_stop(); std::fclose(file);
} }
int log_exceptions(const std::function<int()>& callback) int log_exceptions(const std::function<int()>& callback)
@@ -349,7 +110,6 @@ int log_exceptions(const std::function<int()>& callback)
{ {
logger.fatal("Unhandled non-standard exception"); logger.fatal("Unhandled non-standard exception");
} }
return EXIT_FAILURE; return EXIT_FAILURE;
} }
+6 -18
View File
@@ -1,12 +1,11 @@
#pragma once #pragma once
#include <cstdint> #include <cstdio>
#include <filesystem> #include <filesystem>
#include <functional> #include <functional>
#include <mutex> #include <mutex>
#include <string> #include <string>
#include <string_view> #include <string_view>
#include <thread>
#if defined(INFO) #if defined(INFO)
#undef INFO #undef INFO
@@ -42,34 +41,23 @@ constexpr std::string_view LEVEL_STRINGS[] = {
}; };
#undef LEVELS #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 class Logger
{ {
std::filesystem::path logPath; std::filesystem::path logPath;
std::uintmax_t logSize = 0; std::FILE* file = nullptr;
std::mutex mutex; 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: public:
std::filesystem::path path() const; std::filesystem::path path();
void session_open(const std::filesystem::path&); void session_open(const std::filesystem::path&);
void write_raw(const std::string&); void write(Level, const std::string&);
void write(const Level, const std::string&);
void info(const std::string&); void info(const std::string&);
void warning(const std::string&); void warning(const std::string&);
void error(const std::string&); void error(const std::string&);
void fatal(const std::string&); void fatal(const std::string&);
void command(const std::string&); void command(const std::string&);
void open(const std::filesystem::path&);
Logger();
~Logger(); ~Logger();
}; };
+13 -18
View File
@@ -31,8 +31,8 @@
#include "ui/toast.h" #include "ui/toast.h"
bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path, bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path,
const std::vector<std::filesystem::path>& framePaths, const std::vector<float>& audio, RenderType type, const std::vector<std::filesystem::path>& framePaths, const std::vector<float>& audio,
int fps) RenderType type, int fps)
{ {
if (framePaths.empty() || ffmpegPath.empty() || path.empty()) if (framePaths.empty() || ffmpegPath.empty() || path.empty())
return false; return false;
@@ -40,14 +40,6 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy
auto pathString = path_to_utf8(path); auto pathString = path_to_utf8(path);
auto ffmpegPathString = path_to_utf8(ffmpegPath); 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::filesystem::path audioPath;
std::string audioInputArguments; std::string audioInputArguments;
@@ -75,14 +67,14 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy
auto byteCount = audio.size() * sizeof(float); auto byteCount = audio.size() * sizeof(float);
if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) 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 frameCount = (double)std::max((int)framePaths.size(), 1);
auto expectedDurationSeconds = frameCount / (double)fps; auto expectedDurationSeconds = frameCount / (double)fps;
if (expectedDurationSeconds > 0.0) if (expectedDurationSeconds > 0.0)
audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds); audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds);
audioInputArguments = audioInputArguments = std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", AUDIO_FREQUENCY, AUDIO_CHANNELS,
std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", AUDIO_FREQUENCY, AUDIO_CHANNELS, path_to_utf8(audioPath)); path_to_utf8(audioPath));
switch (type) 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 framePattern = temporaryDirectory / path_from_utf8("frame_%06d.png");
auto framePatternString = path_to_utf8(framePattern); auto framePatternString = path_to_utf8(framePattern);
command = command = std::format("\"{0}\" -y -hide_banner -loglevel warning -framerate {1} -start_number 0 -i \"{2}\"",
std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps, framePatternString); ffmpegPathString, fps, framePatternString);
if (!audioInputArguments.empty()) if (!audioInputArguments.empty())
command += " " + audioInputArguments; 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 #if _WIN32
command = "\"" + command + "\""; command = "\"" + command + "\"";
#endif #endif
@@ -382,9 +377,9 @@ void Recorder::finish()
} }
else else
{ {
auto audio = options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector<float>(); auto audio =
auto isRendered = options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector<float>();
animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps); auto isRendered = animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps);
toast_log(isRendered ? Level::INFO : Level::ERROR, toast_log(isRendered ? Level::INFO : Level::ERROR,
isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
} }