Logging with Qt

Logging messages is an important part of our app and sometimes we can’t find the right way to do so. It depends on how we want to work with that but of course that Qt provide us with some nice options.

Redirect QDebug to a file

Some times we prefer to analyse the our application debug messages in a separated file. It is useful when we want to work with Qt-Creator in full code window and we have two monitors (one for coding and another for application execution and debug file). To redirect the output we have to type in Qt:

Then, in main function we have to add the following line:

qInstallMessageHandler(customMessageHandler);

Redirect QDebug in our custom class

If we want to redirect the output of our custom class to QDebug, it is necessary to declare the operator << of QDebug type as a friend method:

friend QDebug operator << (QDebug d, const Protocol &p);

Have you own logger

Time ago I created a simple logger, nothing fancy, but easy to integrate. It’s a single class that manages several files depending the module and the log level. It makes easier to integrate in your code since there is no dependencies, linking or anything else you need to take into account.

Initially it’s planned to be organized by modules, so for each “part” of your code that you want to log it can only be a file. It gives you the possibility to structure your code in different layers and log them. For now, all log messages of a moduleĀ are printed in the same file, whatever their log level is.

The way to work with this logger is really easy:

The next task I have is to make possible to create files by log level instead of by module. For me it looks a bit messy since you may lose the code traceability, but it’s easier to show errors or warnings.