10

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?

demonplus
  • 5,613
  • 12
  • 49
  • 68
fischeth
  • 113
  • 1
  • 5
  • 1
    It would nice to know why you need more categories. What you trying to achieve? You can use other members (`file, function, line`) of `QMessageLogConext` to get more context of the logging statement origin. – KD07 Oct 26 '15 at 21:42
  • I want to use different QML extensions in one application and need a logging system, where I can print messages dependant from its source. For example, if a write "extension1" in categories, and a qDebug() message is set, so this category (including the message) will appear in the customized handler. So I can use the category to find out, which extension the qDebug message produced. – fischeth Oct 27 '15 at 07:41

2 Answers2

11

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");
    }
}
Yasser Sobhy
  • 145
  • 3
  • 14
Nikita Krupenko
  • 1,117
  • 1
  • 13
  • 17
4

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.

KD07
  • 163
  • 1
  • 5
  • 1
    Yep, that's true. There are ways of creating new categories in [Qt & C++](https://blog.qt.io/blog/2014/03/11/qt-weekly-1-categorized-logging/), but not in QML yet. @fischeth [Here](http://stackoverflow.com/questions/18410549/how-to-redirect-qmls-console-log-to-cpp-stdout]) you have another idea. – Tarod Oct 28 '15 at 07:18