fix: 清空日志改为通过 Logger 自身方法,避免句柄不一致导致空行
Logger 持有打开的文件句柄,用外部 QFile 句柄 truncate 会导致 Logger 写入位置异常,产生大量空行。现在通过 Logger::clearLogFile() 在持有锁的情况下 flush → resize(0) → seek(0),保证句柄一致。 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
parent
71fd4f8a86
commit
fd9de6d7fa
@ -411,24 +411,9 @@ void SettingsPage::onResetConfig() {
|
||||
}
|
||||
|
||||
void SettingsPage::onClearLogs() {
|
||||
// 使用与 Logger 相同的路径逻辑
|
||||
QString logDir = configManager_->get("app.log_dir").toString();
|
||||
if (logDir.isEmpty()) {
|
||||
logDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
|
||||
}
|
||||
|
||||
auto result = clearDirectoryFiles(logDir, {"*.log"}, "日志文件", TruncateMode);
|
||||
if (result.deletedCount < 0) {
|
||||
QMessageBox::warning(this, "清除日志", "清除失败,请检查目录权限");
|
||||
return;
|
||||
}
|
||||
if (result.deletedCount == 0) {
|
||||
QMessageBox::information(this, "清除日志", "没有可清除的日志文件");
|
||||
return;
|
||||
}
|
||||
QMessageBox::information(this, "清除日志",
|
||||
QString("已清空 %1 个日志文件的内容,释放 %2 KB 空间")
|
||||
.arg(result.deletedCount).arg(result.freedBytes / 1024));
|
||||
Logger::clearLogFile();
|
||||
LOG_INFO(kTag, "日志文件已通过 Logger 清空");
|
||||
QMessageBox::information(this, "清除日志", "日志文件已清空");
|
||||
statusLabel_->setText("日志文件已清空");
|
||||
}
|
||||
|
||||
|
||||
@ -60,6 +60,15 @@ void Logger::setLogFile(const QString& path) {
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::clearLogFile() {
|
||||
QMutexLocker locker(&mutex_);
|
||||
if (logFile_ && logFile_->isOpen()) {
|
||||
logFile_->flush();
|
||||
logFile_->resize(0);
|
||||
logFile_->seek(0);
|
||||
}
|
||||
}
|
||||
|
||||
void Logger::log(LogLevel level, const QString& tag, const QString& message) {
|
||||
QMutexLocker locker(&mutex_);
|
||||
QString logLine = QString("[%1] [%2] [%3] %4")
|
||||
|
||||
@ -39,6 +39,9 @@ public:
|
||||
/** @brief 设置日志文件路径(运行时切换) */
|
||||
static void setLogFile(const QString& path);
|
||||
|
||||
/** @brief 清空日志文件内容(线程安全) */
|
||||
static void clearLogFile();
|
||||
|
||||
private:
|
||||
static QString levelToString(LogLevel level);
|
||||
static QString getTimestamp();
|
||||
|
||||
Loading…
Reference in New Issue
Block a user