Trigger signal when file size limit is reached

337 Views Asked by At

I'm writing log files and would like to set a size limit of 10 Mo.

I was thinking of setting a QTimer triggering every X minutes/hours QFileInfo::refresh and checking the size of the file.

Would there be a better way to do this? Using a QTimer sounds painful and resource-costly to me. I wish I could use a SIGNAL when the limit size is reached.

1

There are 1 best solutions below

0
talamaki On

Simple and working solution is to read a file size with QFile::size() right after writing to a log file and react if the size exceeds the limit. Note that the file must be opened when the size is read.

void Logger::log(const QString &rLine)
{
    QFile f(logFileName());
    if (f.open(QIODevice::ReadWrite | QIODevice::Append | QIODevice::Text))
    {
        QTextStream out(&f);
        out << rLine << endl;
        qint64 f_size = f.size();
        f.close();
        checkFileSize(f_size);
    }
    else
    {
        QTextStream out(stdout);
        out << "CAN'T OPEN LOG FILE: " << logFileName();
    }
}

void Logger::checkFileSize(qint64 size)
{
    if (size <= maxFileSize())
    {
        return;
    }

    // Roll the log file or do whatever you wish like send a signal
}