【Qt】实现定期清理程序日志
在现有Qt程序中实现可配置日志保存天数的代码示例,分为界面修改、配置存储和核心逻辑三部分:
// 1. 在配置文件(如settings.h)中添加保存天数的配置项
class Settings {
public:
int logRetentionDays() const {
return m_settings.value("Log/RetentionDays", 30).toInt(); // 默认30天
}
void setLogRetentionDays(int days) {
m_settings.setValue("Log/RetentionDays", days);
}
private:
QSettings m_settings;
};
// 2. 在界面类头文件中添加控件声明(MainWindow.h)
class MainWindow : public QMainWindow {
Q_OBJECT
public:
// ... 原有声明
private slots:
void onRetentionDaysChanged(int index);
void checkLogCleanup();
private:
QComboBox *m_retentionCombo;
QTimer *m_cleanupTimer;
Settings m_settings;
};
// 3. 界面初始化(MainWindow.cpp)
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
// 初始化下拉框
m_retentionCombo = new QComboBox(this);
m_retentionCombo->addItem("3天", 3);
m_retentionCombo->addItem("7天", 7);
m_retentionCombo->addItem("10天", 10);
// 读取保存的值
int savedDays = m_settings.logRetentionDays();
int index = m_retentionCombo->findData(savedDays);
m_retentionCombo->setCurrentIndex(index != -1 ? index : 0);
connect(m_retentionCombo, QOverload<int>::of(&QComboBox::currentIndexChanged),
this, &MainWindow::onRetentionDaysChanged);
// 初始化定时器(每天检查)
m_cleanupTimer = new QTimer(this);
connect(m_cleanupTimer, &QTimer::timeout, this, &MainWindow::checkLogCleanup);
m_cleanupTimer->start(24 * 60 * 60 * 1000); // 24小时
}
// 4. 处理配置变更
void MainWindow::onRetentionDaysChanged(int index)
{
int days = m_retentionCombo->itemData(index).toInt();
m_settings.setLogRetentionDays(days);
checkLogCleanup(); // 可选:立即执行一次清理
}
// 5. 实现日志清理核心逻辑
void MainWindow::checkLogCleanup()
{
QDir logDir("logs");
QDate currentDate = QDate::currentDate();
int retentionDays = m_settings.logRetentionDays();
foreach (const QFileInfo &fileInfo, logDir.entryInfoList(QDir::Files)) {
// 从文件名解析日期(假设文件名格式为log_yyyy-MM-dd.txt)
QString fileName = fileInfo.fileName();
QDate fileDate = QDate::fromString(fileName.mid(4, 10), "yyyy-MM-dd");
if (fileDate.isValid()) {
int days = fileDate.daysTo(currentDate);
if (days > retentionDays) {
QFile::remove(fileInfo.absoluteFilePath());
}
}
}
}
实现要点说明:
- 界面控件:
- 使用QComboBox提供3/7/10天选项
- 使用QData关联存储实际天数值
- 通过QSettings持久化配置
- 定时检查:
- 使用QTimer每日触发清理检查
- 首次启动时立即执行一次清理
- 安全增强:
- 文件名日期解析需要验证有效性
- 删除前可添加确认对话框(生产环境慎用)
- 建议添加日志记录清理操作
- 扩展性:
- 可添加最小保留天数限制(如>=1)
- 支持自定义天数(需添加QSpinBox)
- 多线程处理大量文件删除
如果需要更完整的实现,可以添加以下优化:
// 增强版文件日期检测(同时检查文件元数据)
QDate getFileDate(const QFileInfo &fileInfo) {
// 优先从文件名解析
QDate date = parseDateFromFileName(fileInfo.fileName());
// 文件名无效时使用修改日期
if (!date.isValid()) {
date = fileInfo.lastModified().date();
}
return date;
}
// 带进度提示的清理
void MainWindow::checkLogCleanup() {
QDir logDir("logs");
int total = logDir.count();
int processed = 0;
foreach (const QFileInfo &fileInfo, logDir.entryInfoList(QDir::Files)) {
// ... 清理逻辑
// 更新进度
emit cleanupProgress(++processed * 100 / total);
QApplication::processEvents();
}
}