QT5 写log日志文件及不更改qDebug打印调试信息

 1 #include <QCoreApplication>
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <QFile>
 5 #include <QMutex>
 6 #include <qdebug.h>
 7 #include <QDateTime>
 8 #include <iostream>
 9 using namespace std;
10 
11 void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
12 {
13     static QMutex mutex;
14     mutex.lock();
15     QString text;
16     bool flag = false;
17     switch(type)
18     {
19     case QtDebugMsg://qDebug
20         flag = true;
21         break;
22     case QtInfoMsg://qInfo
23         text = QString(":");
24         break;
25     case QtWarningMsg://qWarning
26         text = QString(":");
27         break;
28     case QtCriticalMsg://qCritical
29         text = QString(":");
30         break;
31     case QtFatalMsg://qFatal
32         text = QString(":");
33         abort();
34     }
35     if (flag)
36     {
37 #ifdef QT_NO_DEBUG
38         cout << msg.toStdString() << endl;
39 #else
40         cout << msg.toStdString() << "," << context.file << "," << context.line << "," << context.function << endl;
41 #endif
42     }
43     else
44     {
45         QString message = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(text).arg(msg);
46         QFile file(QString("log.txt"));
47         file.open(QIODevice::WriteOnly | QIODevice::Append);
48         QTextStream text_stream(&file);
49         text_stream << message << endl;
50         file.flush();
51         file.close();
52     }
53     mutex.unlock();
54 }
55 
56 int main(int argc, char **argv)
57 {
58     qInstallMessageHandler(myMessageOutput);
59     QCoreApplication app(argc, argv);
60     //测试
61     qInfo() << "122";
62     qInfo() << "12342";
63     qInfo() << "1243222";
64     qInfo() << "12322";
65     qDebug() << "aabc";
66     qDebug() << "abadrc";
67     qDebug() << "abzac";
68     qDebug() << "abaqc";
69     qDebug() << "abac";
70     return app.exec();
71 }

 

posted @ 2016-01-05 15:16  LeoVim  阅读(1822)  评论(2编辑  收藏  举报