c++ - Custom and Default Message Handler in Qt -
i want use default qt message handler while logging messages log file except qdebug. here solution, have suggestion or possible problems implementation?
header:
#ifndef qlogger_h #define qlogger_h #include <qtcore/qobject> #include <qtcore/qfile> #include <qtcore/qdatetime> class qlogger : public qobject { q_object public: qlogger(); ~qlogger(); static void start(); static void finish(); static qstring filename; private: static void myloggerfunction(qtmsgtype type, const char *msg); }; #endif // qlogger_h
source:
#include <qtextstream> #include <qdatetime> #include <qdir> #include <iostream> #include "qlogger.h" using namespace std; qstring qlogger::filename=qstring("log.txt"); qlogger::qlogger() { } qlogger::~qlogger() { } void qlogger::start() { qinstallmsghandler(myloggerfunction); } void qlogger::finish() { qinstallmsghandler(0); } void qlogger::myloggerfunction(qtmsgtype type, const char *msg) { qdir dir; dir.cd("log"); qfile logfile(filename); if (logfile.open(qiodevice::append | qiodevice::text)) { qtextstream streamer(&logfile); switch (type){ case qtdebugmsg: finish(); qdebug(msg); break; case qtwarningmsg: streamer << qdatetime::currentdatetime().tostring() <<" warning: " << msg << "\n"; finish(); qwarning(msg); break; case qtcriticalmsg: streamer << qdatetime::currentdatetime().tostring() <<" critical: " << msg << "\n"; finish(); qcritical(msg); break; case qtfatalmsg: streamer << qdatetime::currentdatetime().tostring() <<" fatal: " << msg << "\n"; finish(); qfatal(msg); break; } logfile.close(); } start(); }
afaik not going work, implementing message handler function member function object signature of function qinstallmessagehandler
takes void mymsghandler(qtmsgtype, const char *);
you can either implement function plain freestanding function or use singleton static accessor e.g.
void msghandler(qtmsgtype type, const char * msg) { logger::instance()->handlemessage(type,msg); } class logger { static logger* instance() {... } void handlemessage(qtmsgtype type, const char* msg) { ... } }
this gives function use qinstallmsghandler
, object wrap logging
Comments
Post a Comment