Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QT 5.0 - Built in Logging?

Tags:

c++

logging

qt

I was doing some research on Qt 5.0 Logging and it appears to have built in classes for logging. I'm having trouble finding an example. I have located the classes i believe are relevant here.

QMessageLogger

QMessageLogContext

I can see roughly how to create the QMessageLogger Object from the documentation, but how can I create a log file and append to it?

like image 832
rreeves Avatar asked Jun 25 '13 18:06

rreeves


1 Answers

By default using qDebug(), qWarning(), etc will allow you to log information out to the console.

#include <QtDebug>
qDebug() << "Hello world!";

QMessageLogger is designed to leverage special C++ macros (e.g. function, line, file)

QMessageLogger(__FILE__, __LINE__, 0).debug() << "Hello world!";

In Qt5 the message logger is used behind the scenes since qDebug() is a macro that will eventually instantiate an instance of QMessageLogger. So I'd just go with using the regular qDebug().

The QMessageLogContext contains what I'd consider as "meta-data", i.e. the file, line number, etc that the qDebug() statement it was called from. Normally you'd concern yourself with the log-context if you're defining your own QtMessageHandler (see qInstallMessageHandler()).

The message handler allows for more control of the logging mechanism - like sending logging information to a custom logging server or even to a file.

As provided in the Qt Documentation, creating a custom message handler is simple:

void myMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
  std::cout << msg.toStdString();
}

Check out better examples and explanations here.

like image 118
Huy Avatar answered Oct 27 '22 09:10

Huy