Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can __FILE__ and __LINE__ be made linkable when printed to Qt Creator's debug console?

Header:

#define TRACE_ERROR(s)                      \
{
  ...
  char TraceBuffer[512];
  sprintf(TraceBuffer, "%s\t(%s:%d)", s, __FILE__, __LINE__);
  DebugErrTrace(TraceBuffer);
  ...
}

Implementation:

void DebugErrTrace(char *String, ...) {
  ...
  qDebug() << String;
}

The above spits out a line of debug trace, which might look something like

ERROR File Missing! (..\trunk\Common\FileManager.cpp:102)

in Qt Creator's debug console.

I've noticed that Qt's own error messages e.g.

Object::connect: No such slot cClass::Method(QString) in ..\trunk\Components\Class.cpp:301

create what looks like a hyperlink around the __FILE__:__LINE__ part of the debug line, linking to the line which caused the problem. Is there any way I can I do this with my own debug output?

Cheers, Sam

like image 999
sam-w Avatar asked Oct 27 '11 13:10

sam-w


2 Answers

According to Qt Creator source code (there), the hyperlinks are only created for lines matching these regular expressions:

"^(?:\\[Qt Message\\] )?(file:///.+:\\d+(?::\\d+)?):"
"Object::.*in (.*:\\d+)"
"ASSERT: .* in file (.+, line \\d+)"
"^   Loc: \\[(.*)\\]"

So the simplest lines you could construct look like this:

qWarning("file:///%s:%i: %s", __FILE__, __LINE__, "your message");
qWarning("   Loc: [%s:%i] %s", __FILE__, __LINE__, "your message");

Qt Creator doesn't seem to care if the path after "file:///" is absolute or not.

like image 143
alexisdm Avatar answered Oct 29 '22 10:10

alexisdm


In addition to alexisdm's answer (which helped me very much, big thanks!):

Instead of defining a custom macro, I would suggest to do the following in newer versions of Qt and use qDebug itself:

qSetMessagePattern("%{if-category}%{category}: %{endif}%{message}\n   Loc: [%{file}:%{line}]");

The part before \n is Qt's default message pattern, and splitting with \n has the benefit that the log messages also can contain characters like [ or ] without messing up the links.

The message pattern can easily be extended with other log details like timestamps, thread id and so on, see the documentation. When adding other details, keep the link in a seperate line to avoid issues with Qt Creator's parsing.

like image 40
FourtyTwo Avatar answered Oct 29 '22 09:10

FourtyTwo