util/file: cleanup log initialization and some file-util functions (#2299)

Fixes both issues mentioned in #2297
This commit is contained in:
Tyler Wilding
2023-03-01 17:52:33 -05:00
committed by GitHub
parent 43da4088e6
commit bc40fc5d2f
9 changed files with 76 additions and 32 deletions
+15 -12
View File
@@ -111,22 +111,25 @@ void log_print(const char* message) {
// 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) {
void set_file(const std::string& filename, const bool should_rotate) {
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);
if (should_rotate) {
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);
}
}
}