Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Problem logging my application (QMessageLogger )
Forum Updated to NodeBB v4.3 + New Features

Problem logging my application (QMessageLogger )

Scheduled Pinned Locked Moved Solved General and Desktop
14 Posts 4 Posters 1.2k Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • JonBJ JonB

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

    What are are the downsides of writing my own logging system

    None.

    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.

    H Offline
    H Offline
    hbatalha
    wrote on last edited by
    #5

    @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?

    JonBJ 1 Reply Last reply
    0
    • H hbatalha

      @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?

      JonBJ Offline
      JonBJ Offline
      JonB
      wrote on last edited by
      #6

      @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.

      H 1 Reply Last reply
      0
      • SGaistS Offline
        SGaistS Offline
        SGaist
        Lifetime Qt Champion
        wrote on last edited by
        #7

        Hi,

        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.

        Interested in AI ? www.idiap.ch
        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

        H 1 Reply Last reply
        2
        • JonBJ JonB

          @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.

          H Offline
          H Offline
          hbatalha
          wrote on last edited by
          #8

          @JonB I understand now thanks

          JonBJ 1 Reply Last reply
          0
          • H hbatalha

            @JonB I understand now thanks

            JonBJ Offline
            JonBJ Offline
            JonB
            wrote on last edited by
            #9

            @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.

            1 Reply Last reply
            0
            • SGaistS SGaist

              Hi,

              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.

              H Offline
              H Offline
              hbatalha
              wrote on last edited by hbatalha
              #10

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

              Logger.h

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

              Logger.cpp

              #include "logger.h"
              
              #include <QStandardPaths>
              #include <QFile>
              #include <QDir>
              #include <QDateTime>
              #include <QSettings>
              
              Logger::Logger()
              {
                  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);
                      file.open(QIODevice::Text | QIODevice::ReadWrite);
                  }
                  if( ! QFile::exists(errorAndWarings_file))
                  {
                      QFile file(errorAndWarings_file);
                      file.open(QIODevice::Text | QIODevice::ReadWrite);
                  }
                  if( ! QFile::exists(flow_file))
                  {
                      QFile file(flow_file);
                      file.open(QIODevice::Text | QIODevice::ReadWrite);
                  }
              }
              
              void Logger::starting()
              {
                  QFile debugFile(debug_file);
                  debugFile.open(QIODevice::Text | 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);
                  flowFile.open(QIODevice::Text | QIODevice::ReadWrite | QIODevice::Append);
                  log.setDevice(&flowFile);
              
                  log << '\n';
              }
              
              void Logger::log(Type type, const QString &msg)
              {
                  QString logFile;
                  QString msgType;
              
                  switch (type)
                  {
                  case Type::SPY:
                      logFile = flow_file;
                      msgType = "Flow: ";
                      break;
                  case Type::DEBUG:
                      logFile = debug_file;
                      break;
                  case Type::ERROR_:
                      logFile = errorAndWarings_file;
                      msgType = "Error: ";
                      break;
                  case Type::WARNING:
                      logFile = errorAndWarings_file;
                      msgType = "Warning: ";
                      break;
                  }
              
                  QFile file(logFile);
                  file.open(QIODevice::Text | QIODevice::ReadWrite | QIODevice::Append);
                  QTextStream log(&file);
              
                  if(type == Type::DEBUG)
                      log << msg << '\n';
                  else
                  {
                      log << "[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << "] ";
                      log << msgType << ": " << msg << '\n';
                  }
              
                  log.flush();
              }
              
              void Logger::logSettings()
              {
                  QFile flowFile(flow_file);
                  flowFile.open(QIODevice::Text | 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";
              }
              
              JonBJ 1 Reply Last reply
              0
              • H hbatalha

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

                Logger.h

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

                Logger.cpp

                #include "logger.h"
                
                #include <QStandardPaths>
                #include <QFile>
                #include <QDir>
                #include <QDateTime>
                #include <QSettings>
                
                Logger::Logger()
                {
                    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);
                        file.open(QIODevice::Text | QIODevice::ReadWrite);
                    }
                    if( ! QFile::exists(errorAndWarings_file))
                    {
                        QFile file(errorAndWarings_file);
                        file.open(QIODevice::Text | QIODevice::ReadWrite);
                    }
                    if( ! QFile::exists(flow_file))
                    {
                        QFile file(flow_file);
                        file.open(QIODevice::Text | QIODevice::ReadWrite);
                    }
                }
                
                void Logger::starting()
                {
                    QFile debugFile(debug_file);
                    debugFile.open(QIODevice::Text | 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);
                    flowFile.open(QIODevice::Text | QIODevice::ReadWrite | QIODevice::Append);
                    log.setDevice(&flowFile);
                
                    log << '\n';
                }
                
                void Logger::log(Type type, const QString &msg)
                {
                    QString logFile;
                    QString msgType;
                
                    switch (type)
                    {
                    case Type::SPY:
                        logFile = flow_file;
                        msgType = "Flow: ";
                        break;
                    case Type::DEBUG:
                        logFile = debug_file;
                        break;
                    case Type::ERROR_:
                        logFile = errorAndWarings_file;
                        msgType = "Error: ";
                        break;
                    case Type::WARNING:
                        logFile = errorAndWarings_file;
                        msgType = "Warning: ";
                        break;
                    }
                
                    QFile file(logFile);
                    file.open(QIODevice::Text | QIODevice::ReadWrite | QIODevice::Append);
                    QTextStream log(&file);
                
                    if(type == Type::DEBUG)
                        log << msg << '\n';
                    else
                    {
                        log << "[" << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz") << "] ";
                        log << msgType << ": " << msg << '\n';
                    }
                
                    log.flush();
                }
                
                void Logger::logSettings()
                {
                    QFile flowFile(flow_file);
                    flowFile.open(QIODevice::Text | 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";
                }
                
                JonBJ Offline
                JonBJ Offline
                JonB
                wrote on last edited by JonB
                #11

                @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.

                H 1 Reply Last reply
                0
                • JonBJ JonB

                  @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.

                  H Offline
                  H Offline
                  hbatalha
                  wrote on last edited by
                  #12

                  @JonB

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

                  How would I do that?

                  JonBJ 1 Reply Last reply
                  0
                  • H hbatalha

                    @JonB

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

                    How would I do that?

                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on last edited by
                    #13

                    @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.

                    H 1 Reply Last reply
                    0
                    • JonBJ JonB

                      @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.

                      H Offline
                      H Offline
                      hbatalha
                      wrote on last edited by hbatalha
                      #14

                      @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.

                      1 Reply Last reply
                      0

                      • Login

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • Users
                      • Groups
                      • Search
                      • Get Qt Extensions
                      • Unsolved