Qt 之日志功能
enum LOG_LEVLE
{
LOG_DEBUG = 0,
LOG_WARNING = 1,
LOG_ERROR = 2,
LOG_FATAL = 3
};
#define LOGLEVEL LOG_DEBUG
void logViewOutPut(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
if (type < LOGLEVEL)
return;
QString strMsg;
switch (type)
{
case QtDebugMsg:
strMsg = QString(" Debug ");
break;
case QtWarningMsg:
strMsg = QString(" Warning ");
break;
case QtCriticalMsg:
strMsg = QString(" Critical ");
break;
case QtFatalMsg:
strMsg = QString(" Fatal ");
abort();
default:
break;
}
QByteArray localMsg = msg.toLocal8Bit();
QString strTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString message = QString("File:(%1) Line:(%2) Func:(%3) MSG:(%4)").arg(QString(context.file)).arg(QString::number(context.line)).arg(QString(context.function)).arg(QString(localMsg.constData()));
QString str = strTime + strMsg + message;
static QMutex mutex;
mutex.lock();
QFile file("log.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream stream(&file);
stream << str << "\r\n";
file.flush();
file.close();
mutex.unlock();
}
int main(int argc, char *argv[])
{
qInstallMessageHandler(logViewOutPut);
QApplication a(argc, argv);
Mainwindow w;
w.show();
return a.exec();
}
qInstallMessageHandle 有点类似与Qt的EventFilter,调试信息先汇总到注册的函数里面,按照代码执行。相当于重定向输出。