QtMessageHandler / QTextStream causes memory usage to go up?

213 Views Asked by At

I have installed a simple QtMessageHandler in my application:

void handleMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString text = msg;

    QString path = QCoreApplication::applicationDirPath() + "/logging/logs.txt";

    QFile logFile(path);
    logFile.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream textStream(&logFile);
    textStream<< text << endl << flush;
}

int main(int argc, char *argv[])
{
    qInstallMessageHandler(handleMessage);

    // ...

    for (int i = 0; i < 10000000; i++) {
        qDebug() << "Some text";
    }

    // ...
}

Now when I use qDebug to write some logs to the log file (and the application is doing nothing else!), the memory usage is shooting up. When I stop writing logs, it goes back down, but never to it's previous value. For every few thousand messages, the memory goes up a few hundred kilobytes and stays that way.

I think it's the QTextStream that is causing this, because if I comment that part out, then the memory usage just remains low.

I tried moving the myMessageHandler function to a separate class and have the QTextStream as a member variable, instead of creating it every time that myMessageHandler() is called, but then I couldn't get qInstallMessageHandler() to work.

int main(int argc, char *argv[])
{
    MyMessageHandler myMessageHandler;
    qInstallMessageHandler(myMessageHandler.handleMessage);
}

Which gives me:

cannot convert 'MyMessageHandler::handleMessage' from type 'void (MyMessageHandler::)(QtMsgType, const QMessageLogContext&, const QString&)' to type 'QtMessageHandler {aka void (*)(QtMsgType, const QMessageLogContext&, const QString&)}'qInstallMessageHandler(myMessageHandler.handleMessage);

Anyone have an idea on how to solve this?

0

There are 0 best solutions below