I'm using a lot of qDebug() <<
statements for debug output. Is there any cross-platform way I can redirect that debug output to a file, without resorting to shell scripts? I'm guessing that open() and dup2() will do the job in Linux, but will it work compiled with MinGW in Windows?
And maybe there is a Qt way to do it?
Here is a working example of hooking the default message handler.
Thank you @Ross Rogers!
Well, I would say that the moment when you need to redirect your debug output to anything different than stderr is when you could think about some logging tool. If you feel you need one I would recommend using
QxtLogger
("The QxtLogger class is an easy to use, easy to extend logging tool.") fromQxt
library.You've to install a message handler using
qInstallMsgHandler
function, and then, you can useQTextStream
to write the debug message to a file. Here is a sample example:Taken from the doc of
qInstallMsgHandler
(I only added the comments):In the above example, the function
myMessageOutput
usesstderr
which you might want to replace with some other file stream, or completely re-write the function!Once you write and install this function, all your
qDebug
(as well asqWarning
,qCritical
etc) messages would be redirected to the file you're writing to in the handler.Here is a cross-platform solution to log to the console, if the app was ran from the Qt Creator and to the
debug.log
file, when it is compiled and being ran as a standalone app.main.cpp:
Log formatting is handled by
QString("%1 %2: %3 (%4)").arg...
(for the file) andfprintf(stderr, "%s %s: %s (%s:%u, %s)\n"...
(for console).Inspiration: https://gist.github.com/polovik/10714049.
From here all credit goes to spirit.