Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

File based logging in Qt for debugging

From Wiki
Jump to: navigation, search
Article Metadata
Created: skumar_rao (29 Mar 2010)
Last edited: hamishwillee (11 Oct 2012)
ID Creation date 28th Mar 2010
Platform S60 5th Edition Tested on devices Nokia N97 Mini
Category Qt Subcategory

Keywords (APIs, classes, methods, functions): qInstallMsgHandler



File Based Logging in Qt For Debugging.

I agree that there are ways to debug application using IDE, but in long run every developers requires a way to print debugging info in to the file. In case of Qt there are standard ways to use file logging as shown below.

  • Using Log4Qt
  • Using QxtLogger

But the above 2 requires developers either to include a heavier static lib or have to convert to a specific data format (like QVariants or QVariantList) before logging .

Here we will see a simple file logging methods which is very easy to use and requires not more then 25 lines. Before you start logging still it provides same level of flexibility to log debug/info/warning etc.

Step 1.

We will create a logging handler.

#include <fstream>
using namespace std;
ofstream logfile;
void SimpleLoggingHandler(QtMsgType type, const char *msg) {
switch (type) {
case QtDebugMsg:
logfile << QTime::currentTime().toString().toAscii().data() << " Debug: " << msg << "\n";
case QtCriticalMsg:
logfile << QTime::currentTime().toString().toAscii().data() << " Critical: " << msg << "\n";
case QtWarningMsg:
logfile << QTime::currentTime().toString().toAscii().data() << " Warning: " << msg << "\n";
case QtFatalMsg:
logfile << QTime::currentTime().toString().toAscii().data() << " Fatal: " << msg << "\n";

Step 2.

Open A file to be where application will be logging for example"c:\\data\\logfile.txt", ios::app);

Step 3.

Install our handler as a qInstallMsgHandler.


That is it now we can use the normal qCritical(), qDebug(), qFatal() and qWarning() to direct messages to file. for example

#include <QTime>
#define PREFIX "[myDebugPrint]" << QTime::currentTime().toString("hh:mm:ss.zzz")
void MyClass::myFunction(int variable)
qDebug() << PREFIX << "MyClass::myFunction() begin";
qDebug("code is not activated");
qDebug() << variable;
qDebug() << PREFIX << "MyClass::myFunction() end";

Reference links

--skumar_rao 16:52, 29 March 2010 (UTC)

This page was last modified on 11 October 2012, at 01:16.
251 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.


Thank you!

We appreciate your feedback.