I have the following code taken from https://doc.qt.io/qt-5/qtglobal.html#qInstallMessageHandler I want to have access to context.file, context.line, context.function inside myMessageOutput()
void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QByteArray localMsg = msg.toLocal8Bit();
const char *file = context.file ? context.file : "";
const char *function = context.function ? context.function : "";
switch (type) {
case QtDebugMsg:
fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtInfoMsg:
fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtWarningMsg:
fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtCriticalMsg:
fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
case QtFatalMsg:
fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), file, context.line, function);
break;
}
}
int main(int argc, char **argv)
{
qInstallMessageHandler(myMessageOutput);
QApplication app(argc, argv);
...
return app.exec();
}
In Debug build (using `qDebug() << "test logging") shows details about context.line/file/number. In Release build that info(s) are nullptr or 0 (line). Reproduced on Windows (QT 5.12)
CodePudding user response:
I have tested your code in Qt 5.15.2 with gcc (in Linux) and it worked both in debug and release mode and I can not reproduce your problem. However it is mentioned in document page QMessageLogContext Class that:
Note: By default, this information is recorded only in debug builds. You can overwrite this explicitly by defining QT_MESSAGELOGCONTEXT or QT_NO_MESSAGELOGCONTEXT.
So adding following line to your project.pro file may fix your problem:
DEFINES = QT_MESSAGELOGCONTEXT
Do not forget to run qmake and rebuild your project to see effects.