新增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