fischeth
fischeth

Reputation: 113

Set a QML category for console.log

I'm new to the Qt/QML topic and I'm trying to install a logging handler in my c++ business logic. The following code snipet installs a handler and sets a special category:

    int main(int argc, char *argv[])
    {
       qInstallMessageHandler(myMessageOutput);
       QLoggingCategory mainEx("main.ex");

       qCDebug(mainEx) << "debug message";
       ...
    }

The result is a call from the Qt backend to the following installed message handler:

void myMessageOutput(QtMsgType type, const QMessageLogContext &context,
                     const QString &msg)
{
   ...
}

In Qt 5 it is also possible to write debug messages directly in in QML with:

console.debug("debug message")

But the 'cateory' in QMessageLogConext is always 'qml'. Is it possible to set another category directly in QML?

Upvotes: 10

Views: 3243

Answers (2)

Nikita Krupenko
Nikita Krupenko

Reputation: 1175

Starting with Qt 5.8, categorized logging available out of the box in QML.

A logging category can be passed to console.log() and friends as the first argument. If supplied to to the logger the LoggingCategory's name will be used as Logging Category otherwise the default logging category will be used.

import QtQuick 2.8

Item {
    LoggingCategory {
        id: category
        name: "com.qt.category"
    }

    Component.onCompleted: {
      console.log(category, "message");
    }
}

Upvotes: 11

KD07
KD07

Reputation: 163

I think there is no out of box solution available to override default category in QML engine. Here is the possible solution with very good explanation and code.

Upvotes: 4

Related Questions