当前位置: 首页 > news >正文

【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());
            }
        }
    }
}

实现要点说明:

  1. 界面控件
  • 使用QComboBox提供3/7/10天选项
  • 使用QData关联存储实际天数值
  • 通过QSettings持久化配置
  1. 定时检查
  • 使用QTimer每日触发清理检查
  • 首次启动时立即执行一次清理
  1. 安全增强
  • 文件名日期解析需要验证有效性
  • 删除前可添加确认对话框(生产环境慎用)
  • 建议添加日志记录清理操作
  1. 扩展性
  • 可添加最小保留天数限制(如>=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();
    }
}

相关文章:

  • 排序算法详解、应用对比与C语言实现
  • 【AI学习】DeepSeek-R1-Distill的意义和影响
  • 【TI C2000】F28002x的系统延时、GPIO配置及SCI(UART)串口发送、接收
  • Git命令摘录
  • C++ -- stack的模拟实现 介绍适配器模式
  • Zookeeper(45) 如何在Zookeeper中删除节点?
  • CentOS上安装WordPress
  • 在SpringBoot如何调用DeepSeek接口
  • 【Qt】模型/视图(Model/View)框架详解(一):基本概念
  • 【Axure教程】数字滚动效果
  • 深入解析LVS命令参数及DR模式下的ARP抑制原理
  • rustdesk远程桌面自建服务器
  • stl里的deque 中控map 假如用完了,该如何处理
  • C# 调用 C++ 动态库接口
  • 深入指南:在IDEA中启用和使用DeepSeek
  • 花卉图片分类实战 -- 基于预训练的 Vision Transformer 实现
  • Vue3组件通信全攻略:8种传值方式详解
  • JavaScript document.write()介绍(直接将内容写入HTML文档的早期方法,已逐渐被现代DOM操作方法取代)
  • export关键字
  • boolen盲注和时间盲注
  • “当代阿炳”甘柏林逝世,创办了国内第一所残疾人高等学府
  • 浙江推动人工智能终端消费:家居机器人纳入以旧换新补贴范围
  • 上博东馆常设陈列入选全国博物馆“十大精品”
  • 哈马斯与以色列在多哈举行新一轮加沙停火谈判
  • 新疆多地市民拍到不明飞行物:几秒内加速消失,气象部门回应
  • 被围观的“英之园”,谁建了潮汕天价违建?