2

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.

Grégoire Borel
  • 1,880
  • 3
  • 33
  • 55
  • 6
    Since your code is doing the writing, you can just keep a counter of the number of bytes you have written so far (add the number-of-bytes-just-written to it after each write). After each write, check the counter to see if it just became larger than your threshold, and if it did, emit the signal. – Jeremy Friesner Aug 30 '16 at 15:46
  • This could be a solution. However, the writing part is done by a third-party library. I would llike to leave its code untouched. I only have access to the file. – Grégoire Borel Aug 30 '16 at 16:06
  • However, I could check the size of the file each time I call the log function. – Grégoire Borel Aug 30 '16 at 16:07
  • 1
    @GrégoireBorel _"...each time I call the log function"_ So, why don't you keep track of number of bytes you pass to this "log" function? – frogatto Aug 30 '16 at 19:59

1 Answers1

0

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
}
talamaki
  • 5,324
  • 1
  • 27
  • 40