Search code examples
c++qtqdebug

QT QDebug with QIODevice not working


I wanted my QT application to store certain logs in different files. I had been using qDebug() << "LOG Messages" to output information. The problem in this method is that all output will come on the same screen even if you are threading. The QDebug class documents that I can make a QDebug(QIODevice * dev) to give any QIODEvice as the device to store data. So I wrote the following code but it doesnt work :

QString logfilePath = "/var/log/1.log";
QFile * logfile = new QFile(logfilePath);
if(!logfile->open(QIODevice::WriteOnly|QIODevice::Append)){
    // There is an error
}else{
    QDebug * logger = new QDebug(logfile);
    *logger << "msg";
}

The file is created but no information is stored in the file. I even checked the QDebug code and it looks like it creates a TEXT Stream on the QIODevice. So why is no output being stored in the file ?

Also I know the qMessageInstaller function. But it wont work for me because it is a universal handler and I would like different threads to store log messages in different files.


Solution

  • Use this

    *logger << "Hello!" << endl;
    

    Or this

    *logger << "Hello!" << flush;
    

    Remember to delete logger, which will flush the stream too.

    delete logger;
    

    Make sure you are writing to different files in different threads too.