Replace logging backend for console.debug() console.warn()

829 views Asked by At

Qt Quick uses qDebug to perform logging, where the standard Javascript logging methods are maped to a Qt log type

console.log()   -> qDebug()
console.debug() -> qDebug()
console.info()  -> qDebug()
console.warn()  -> qWarning()
console.error() -> qCritical()

At this point you loose the distinction between debug() and info().

Is there any way to register a custom logger for the Javascript methods directly in the QML engine without going over qDebug and qInstallMessageHandler?

1

There are 1 answers

2
mapsonyllaer On BEST ANSWER

Although the globalObject is read-only in the QQmlEngine, values stored therein are not. So you can modify the console property of the globalObject. You can do that both in C++ and in QML. Here is a trivial running example in QML:

import QtQuick 2.3
import QtQuick.Controls 1.2

ApplicationWindow {
    visible: true
    width: 640
    height: 480
    title: qsTr("Console example")

    Column {
        anchors.centerIn: parent

        Button {
            text: "debug"
            onClicked: {
                console.log = console.debug
            }
        }

        Button {
            text: "exception"
            onClicked: {
                console.log = console.exception
            }
        }

        Button {
            text: "print something"
            onClicked: {
                console.log( "logging something" );
            }
        }
    }
}

The first two buttons change, what the third button does by modifying the console.log method. C++ would look something like this (I cannot copy all of my code here, sorry, but it should get you going and it works nicely):

// in a header file
class HelperObject: public QObject {
    Q_OBJECT
    // ...
    public slots:
        myLog( QString aMessage );
};

// in an implementation file
QQmlEngine   qmlEngine;
HelperObject helperObject;
QJSValue     helperValue = qmlEngine.newQObject( &helperObject );
QJSValue     consoleObject( qmlEngine.globalObject().property( "console" ) );

if (!consoleObject.isUndefined()) {
    QJSValue myLogValue = helperValue.property( "myLog" );

    consoleObject.setProperty( "log", myLogValue );
}