Important: Please read the Qt Code of Conduct -

Problem logging my application (QMessageLogger )

  • I want to create a logging system for my application using QMessageLogger(since it already exists even though I could create my own which could meet my specific needs) but I just can't seem to understand how it works. I went through the doc but the example is minimum and did not clear it up. The best example I could find was this one but even with it I don't understand how I can log my app the way I want.

    I want to log my application in the following way: every time the application is opened a folder named the date and time it was open is created and inside 3 files, each one logging a type of information I need.

    I have already thought out a way to do that implementing my own class but I want to use QMessageLogger.

    Could someone give an idea on how would I do that and in the meantime explain how QMessageLogger works?

    Thank you!!

  • Moderators

    You should not use QMessageLogger. instead, prepare your own logging function and register it with qInstallMessageHandler. And in doc of that function you will find an example, too.

    Or you can take an external logging solution like MLog, QLogger etc.

  • @sierdzio Thanks for the tip, I've decided to prepare myown logging function and register it with qInstallMessageHandler.

    What are are the downsides of writing my own logging system and when, if ever, should I do it?

  • @hbatalha said in Problem logging my application (QMessageLogger ):

    What are are the downsides of writing my own logging system


    when, if ever, should I do it?

    Whenever you like! Just make sure you take the configuration setting from a file (like via QSettings) so you can heighten/lower the level at runtime.

  • @JonB said in Problem logging my application (QMessageLogger ):

    Just make sure you take the configuration setting from a file (like via QSettings) so you can heighten/lower the level at runtime.

    Didn't understand, could you elaborate?

  • @hbatalha
    The signature for the message handler function is void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);. If you are going to write your own logging stuff you are passed the enum QtMsgType. You might want to detect this to distinguish between, say, errors versus info, and log/not log the messages. I always think it is nice to be able to switch that level on/off at runtime, so controlled by say a setting in QSettings.

  • Lifetime Qt Champion


    For fine grained control about logging, QLoggingCategory is a good tool and you can pretty easily build rules to log more or less, specific parts of your application, etc.

  • @JonB I understand now thanks

  • @hbatalha
    Just to say: I realise what i wrote is a bit "advanced". Get your logging working simply, then add in that stuff. You will want to look at @SGaist 's mention of adding your own categories too.

  • @SGaist I couldn't understand how to use QLoggingCategory in my app. And based on myMessageHandler I created my own Logger:


    #ifndef LOGGER_H
    #define LOGGER_H
    #include <QObject>
    class Logger : public QObject
        // SPY is just a silly name since it will be registering every step taken in the app
        enum class Type {ERROR_, WARNING, DEBUG, SPY};
        void log(Type type, const QString& msg);
        void logSettings();
        void starting();
        QString debug_file;
        QString errorAndWarings_file;
        QString flow_file; // register every step taken in the app
    #endif // LOGGER_H


    #include "logger.h"
    #include <QStandardPaths>
    #include <QFile>
    #include <QDir>
    #include <QDateTime>
    #include <QSettings>
        QString logDir = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/Log";
        QDir dir(logDir);
        debug_file = logDir + "/debug.log";
        errorAndWarings_file = logDir + "/errors_and_warnings.log";
        flow_file = logDir + "/flow.log";
        if( ! dir.exists())
            dir.mkdir(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + "/Log");
        if( ! QFile::exists(debug_file))
            QFile file(debug_file);
   | QIODevice::ReadWrite);
        if( ! QFile::exists(errorAndWarings_file))
            QFile file(errorAndWarings_file);
   | QIODevice::ReadWrite);
        if( ! QFile::exists(flow_file))
            QFile file(flow_file);
   | QIODevice::ReadWrite);
    void Logger::starting()
        QFile debugFile(debug_file); | QIODevice::ReadWrite | QIODevice::Append);
        QTextStream log(&debugFile);
        log << "\n[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << "]" << '\n' << '\n';
        QFile flowFile(flow_file); | QIODevice::ReadWrite | QIODevice::Append);
        log << '\n';
    void Logger::log(Type type, const QString &msg)
        QString logFile;
        QString msgType;
        switch (type)
        case Type::SPY:
            logFile = flow_file;
            msgType = "Flow: ";
        case Type::DEBUG:
            logFile = debug_file;
        case Type::ERROR_:
            logFile = errorAndWarings_file;
            msgType = "Error: ";
        case Type::WARNING:
            logFile = errorAndWarings_file;
            msgType = "Warning: ";
        QFile file(logFile); | QIODevice::ReadWrite | QIODevice::Append);
        QTextStream log(&file);
        if(type == Type::DEBUG)
            log << msg << '\n';
            log << "[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << "] ";
            log << msgType << ": " << msg << '\n';
    void Logger::logSettings()
        QFile flowFile(flow_file); | QIODevice::ReadWrite | QIODevice::Append);
        QTextStream log(&flowFile);
        QSettings  qsettings(QSettings::IniFormat, QSettings::UserScope, "HBatalha", "my_app");
        log << "\n[Settings]\n";
        log << "confiron_exit: " <<                         qsettings.value("confiron_exit", "1").toBool()                          << '\n';
        log << "mimimize_to_tray: " <<                      qsettings.value("mimimize_to_tray", "0").toBool()                       << '\n';
        log << "close_to_tray: " <<                         qsettings.value("close_to_tray", "0").toBool()                          << '\n';
        log << "video_format: " <<                          qsettings.value("video_format", 0).toInt();
        log << "language: " <<                              qsettings.value("language", "0").toInt()                                << '\n';
        log << "theme: " <<                                 qsettings.value("theme", "0").toInt()                                   << '\n';
        log << "[----]\n";

  • @hbatalha
    This is all fine, but it's just your own, standalone logging code, no use of qInstallMessageHandler or QLoggingCategory. That's OK, though not as flexible as it could be.

    I notice that you re-open each file at the moment you want to log to it. Could be a bit slow; if you log a lot, you might want to keep open handles into the 3 files around.

  • @JonB

    you might want to keep open handles into the 3 files around

    How would I do that?

  • @hbatalha
    Make your QFiles for sure, and possibly your QTextStreams too, member variables in Logger class. Open the files in the constructor or in starting, and leave them open. Although they will close automatically on program exit, you might add a finishing() method too and call it to explicitly, or from destructor, to close when shutting down.

  • @JonB I have done exactly that and it created another problem.
    I use Logger in different classes aside from MainWindow and in those classes the logging won't work and I am guessing it is because the files will be already open. Is there a way to write to open files.
    The solution I am thinking of is to have Logger object pointer in those classes to point to the one in MainWindow.

Log in to reply