新增log.h文件,在main函數中包含進來。
log.h代碼如下:
#ifndef LOG_H #define LOG_H #include <QFile> #include <QTextStream> #include <QDateTime> #include <QMutex> //默認調試級別為warning,即小於warning級別的都不會寫入日志文件 //只有release版本的時候,才會輸出到日志,debug版本正常輸出到終端。 namespace QT_LOG {//默認文件名為當前時間命名的log文件 static int m_LogLevel = 1; static QString m_LogFile = QString("%1.log").arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss")); QMutex m_LogMutex; void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg /*char *msg*/) { if (type < m_LogLevel)//設置輸出日志級別,小於該級別,將不會寫入日志文件,默認是warning級別,即debug信息不會寫入日志文件 { return; } QString log_info; switch (type) { case QtDebugMsg: log_info = QString("%1:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg); break; case QtWarningMsg: log_info = QString("%1[Warning]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg); break; case QtCriticalMsg: log_info = QString("%1[Critical]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg); break; case QtFatalMsg: log_info = QString("%1[Fatal]:%2").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"),msg); abort(); } //為了線程安全 m_LogMutex.lock(); QFile outFile(m_LogFile); outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text); QTextStream ts(&outFile); ts << log_info << endl; outFile.close(); m_LogMutex.unlock(); } //默認調試級別為warning及以上才會寫入日志文件,默認log文件名為程序啟動時間命名的log文件 void logInit(QString logFile = "",int logLevel = 0) { //#ifndef _DEBUG //實現debug版本的時候,輸出到終端;release版本的時候輸出到日志文件 if ((logLevel < 0) || (logLevel > 3)) { m_LogLevel = 1; } else { m_LogLevel = logLevel; } if (!logFile.isEmpty()) { m_LogFile = logFile; } qInstallMessageHandler(customMessageHandler); //#endif } }; #endif // LOG_H
在main函數中增加以下代碼:
int main(int argc, char *argv[]) { if (argc > 1) {//設置log文件名為可執行文件名,如果程序啟動時有參數,則認為參數為調試級別,否則,按默認級別 QT_LOG::logInit(QString(argv[0]).split(QDir::separator()).last().remove(".exe") + ".log",QString(argv[1]).toUInt()); } else { QT_LOG::logInit(QString(argv[0]).split(QDir::separator()).last().remove(".exe") + ".log"); } QApplication a(argc, argv); MainWidget w; w.show(); return a.exec(); }
打印效果如下:
2020-04-20 14:03:29:"無法連接到服務器Unknown error" 2020-04-20 14:05:08:"127.0.0.1" 20121 500 2020-04-20 14:05:08:From main thread: 0x2f50 2020-04-20 14:05:08:Controller's thread is : 0x2f50 2020-04-20 14:05:08:m_tcpThread: QThread(0xb6fd94) 2020-04-20 14:05:08:start running: "127.0.0.1" 20121 500 2020-04-20 14:05:08:"127.0.0.1" : 20121 QAbstractSocket::UnconnectedState 2020-04-20 14:05:10:"無法連接到服務器Unknown error" 2020-04-20 14:05:26:"20121:erro:The remote host closed the connection" 2020-04-20 14:05:26:"127.0.0.1" :: 20121