Skip to content

Commit 8d37a30

Browse files
authored
feat: 自动清理log目录 (#8)
1 parent 017e830 commit 8d37a30

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

include/MaaUtils/Logger.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ class MAA_UTILS_API Logger
7575
Logger() = default;
7676

7777
void reinit();
78+
void cleanup();
7879
bool rotate();
7980
void open(bool append = true);
8081
void close();

source/Logger/Logger.cpp

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@
22

33
#include "MaaUtils/Logger.h"
44

5+
#include <thread>
6+
57
#ifdef _WIN32
68
#include "MaaUtils/SafeWindows.hpp"
79

@@ -109,11 +111,47 @@ void Logger::flush()
109111

110112
void Logger::reinit()
111113
{
114+
cleanup();
112115
bool rotated = rotate();
113116
open(!rotated);
114117
log_proc_info();
115118
}
116119

120+
static void remove_old_files(const std::filesystem::path& dir)
121+
{
122+
constexpr auto kMaxAge = std::chrono::hours(24 * 7); // 一周
123+
const auto now = std::filesystem::file_time_type::clock::now();
124+
125+
std::error_code ec;
126+
for (const auto& entry : std::filesystem::recursive_directory_iterator(dir, ec)) {
127+
if (ec) {
128+
break;
129+
}
130+
if (!entry.is_regular_file(ec) || ec) {
131+
continue;
132+
}
133+
134+
auto last_write = entry.last_write_time(ec);
135+
if (ec) {
136+
continue;
137+
}
138+
139+
auto age = now - last_write;
140+
if (age > kMaxAge) {
141+
std::filesystem::remove(entry.path(), ec);
142+
}
143+
}
144+
}
145+
146+
void Logger::cleanup()
147+
{
148+
if (log_dir_.empty() || !std::filesystem::exists(log_dir_)) {
149+
return;
150+
}
151+
152+
std::thread(remove_old_files, log_dir_).detach();
153+
}
154+
117155
bool Logger::rotate()
118156
{
119157
if (log_path_.empty() || !std::filesystem::exists(log_path_)) {

0 commit comments

Comments
 (0)