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!!
-
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.
-
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
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. -
@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. -
@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 isvoid 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 inQSettings
. -
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.
-
@hbatalha
The signature for the message handler function isvoid 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 inQSettings
. -
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.
@SGaist I couldn't understand how to use
QLoggingCategory
in my app. And based onmyMessageHandler
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"; }
-
@SGaist I couldn't understand how to use
QLoggingCategory
in my app. And based onmyMessageHandler
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"; }
@hbatalha
This is all fine, but it's just your own, standalone logging code, no use ofqInstallMessageHandler
orQLoggingCategory
. 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.
-
@hbatalha
This is all fine, but it's just your own, standalone logging code, no use ofqInstallMessageHandler
orQLoggingCategory
. 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.
-
@hbatalha
Make yourQFile
s for sure, and possibly yourQTextStream
s too, member variables inLogger
class. Open the files in the constructor or instarting
, and leave them open. Although they will close automatically on program exit, you might add afinishing()
method too and call it to explicitly, or from destructor, to close when shutting down. -
@hbatalha
Make yourQFile
s for sure, and possibly yourQTextStream
s too, member variables inLogger
class. Open the files in the constructor or instarting
, and leave them open. Although they will close automatically on program exit, you might add afinishing()
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.