From fb20bf34df7419f3279bd9170d06048625f2a1bb Mon Sep 17 00:00:00 2001 From: ManDude <7569514+ManDude@users.noreply.github.com> Date: Sun, 26 Feb 2023 22:56:25 +0000 Subject: [PATCH] rotate log files (#2283) Fixes #1228 (wow only took 1 year) --- common/log/log.cpp | 19 +++++++++++++++++++ common/util/FileUtil.cpp | 9 +++++++++ common/util/FileUtil.h | 2 ++ 3 files changed, 30 insertions(+) diff --git a/common/log/log.cpp b/common/log/log.cpp index 3ef0e2ef53..5a4d1bdf47 100644 --- a/common/log/log.cpp +++ b/common/log/log.cpp @@ -108,9 +108,28 @@ void log_print(const char* message) { } } // namespace internal +// how many extra log files for a single program should be kept? +constexpr int LOG_ROTATE_MAX = 5; + void set_file(const std::string& filename) { ASSERT(!gLogger.fp); file_util::create_dir_if_needed_for_file(filename); + + // rotate files. log.txt is the current one, log.1.txt is the previous one, etc. + auto as_path = fs::path(filename); + auto stem = as_path.stem().string(); + auto ext = as_path.extension().string(); + auto dir = as_path.parent_path(); + for (int i = LOG_ROTATE_MAX; i-- > 0;) { + auto src_name = i != 0 ? fmt::format("{}.{}{}", stem, i, ext) : fmt::format("{}{}", stem, ext); + auto src_path = dir / src_name; + if (file_util::file_exists(src_path.string())) { + auto dst_name = fmt::format("{}.{}{}", stem, i + 1, ext); + auto dst_path = dir / dst_name; + file_util::copy_file(src_path, dst_path); + } + } + gLogger.fp = file_util::open_file(filename.c_str(), "w"); ASSERT(gLogger.fp); } diff --git a/common/util/FileUtil.cpp b/common/util/FileUtil.cpp index c4e2074927..490c447650 100644 --- a/common/util/FileUtil.cpp +++ b/common/util/FileUtil.cpp @@ -584,4 +584,13 @@ std::vector find_directories_in_dir(const fs::path& base_dir) { return dirs; } +void copy_file(const fs::path& src, const fs::path& dst) { + if (src == dst) { + lg::error("Failed to copy_file {}, source and destination are the same\n", src.string()); + throw std::runtime_error("Failed to copy_file"); + } + auto data = read_binary_file(src); + write_binary_file(dst, data.data(), data.size()); +} + } // namespace file_util diff --git a/common/util/FileUtil.h b/common/util/FileUtil.h index eca0933e4d..3813ed101d 100644 --- a/common/util/FileUtil.h +++ b/common/util/FileUtil.h @@ -63,4 +63,6 @@ std::vector decompress_dgo(const std::vector& data_in); FILE* open_file(const fs::path& path, const std::string& mode); std::vector find_files_recursively(const fs::path& base_dir, const std::regex& pattern); std::vector find_directories_in_dir(const fs::path& base_dir); +// writes the contents of one file to another +void copy_file(const fs::path& src, const fs::path& dst); } // namespace file_util