Maybe this functionality already exists in the Qt docs and I haven't come across it yet, so I'm open to suggestions.
Basically what I'm trying to do is create a one-line, generic, global error reporting mechanism for my multi-file program. When it's compiled in debug mode, the function outputs to qDebug() and I read it from the application output in Qt Creator. However, if it's compiled in release mode, I want the function to output to a file instead of the command prompt.
Here's my (buggy) implementation:
//myerror.h:
#ifndef MYERROR_H
#define MYERROR_H
#ifdef DEBUGMODE //DEBUGMODE is defined in the .pro file by "Debug:DEFINES += DEBUGMODE"
#include <QDebug>
#else
#include <QFile>
QFile ERRLOG
("c:/temp/my_errors.log");
#endif
{
#ifdef DEBUGMODE
qDebug() << a;
#else
ERRLOG.
write(QString("%1\n").
arg(a
).
toAscii());
#endif
}
#endif // MYERROR_H
//mainwindow.cpp:
MainWindow
::MainWindow(QWidget *parent
) : ui(new Ui::MainWindow)
{
#ifndef DEBUGMODE
#endif
ui->setupUi(this);
//etc
}
MainWindow::~MainWindow()
{
#ifndef DEBUGMODE
ERRLOG.close();
#endif
delete ui;
}
//myerror.h:
#ifndef MYERROR_H
#define MYERROR_H
#ifdef DEBUGMODE //DEBUGMODE is defined in the .pro file by "Debug:DEFINES += DEBUGMODE"
#include <QDebug>
#else
#include <QFile>
QFile ERRLOG("c:/temp/my_errors.log");
#endif
inline void QDEBUG(QString a)
{
#ifdef DEBUGMODE
qDebug() << a;
#else
ERRLOG.write(QString("%1\n").arg(a).toAscii());
#endif
}
#endif // MYERROR_H
//mainwindow.cpp:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
#ifndef DEBUGMODE
ERRLOG.open(QIODevice::WriteOnly);
#endif
ui->setupUi(this);
//etc
}
MainWindow::~MainWindow()
{
#ifndef DEBUGMODE
ERRLOG.close();
#endif
delete ui;
}
To copy to clipboard, switch view to plain text mode
Now, this works while I'm in debug mode, but doesn't work when in release mode. The file "my_errors.log" is being generated, but as far as I can tell it was never opened or written to. I can't just open the QFile in myerror.h because it's a header, so I have to do it in mainwindow.cpp.
Additionally, including this header in more than one cpp file resulted in a linker error complaining about multiple definitions, even though I've guarded myerror.h!
Is there a better way to do this? Can I just re-route qDebug() to a file? I couldn't find anything on that in the documentation.
Thanks!
Bookmarks