debug控制台打印信息;release文本查看信息
main函数外:
void MessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
// 加锁
static QMutex mutex;
mutex.lock();
QByteArray localMsg = msg.toLocal8Bit();
QString strMsg;
switch((int)type)
{
case QtDebugMsg:
strMsg = QString("Debug:");
break;
case QtWarningMsg:
strMsg = QString("Warning:");
break;
case QtCriticalMsg:
strMsg = QString("Critical:");
break;
case QtFatalMsg:
strMsg = QString("Fatal:");
break;
}
// 设置输出信息格式
QString strDateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString strMessage = QString(strMsg+"%1 File:%2 Line:%3 Function:%4 DateTime:%5")
.arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function).arg(strDateTime);
// 输出信息至文件中(读写、追加形式)
QDateTime current_date_time = QDateTime::currentDateTime();
QString current_date = current_date_time.toString("yyyy-MM-dd");
QString filename = QCoreApplication::applicationDirPath() + "/log/" + current_date + ".txt";
QFile file(filename);
file.open(QIODevice::ReadWrite | QIODevice::Append);
QTextStream stream(&file);
stream << strMessage << "\r\n";
file.flush();
file.close();
// 解锁
mutex.unlock();
}
main函数里面:
//建立log文件夹
QDir *temp = new QDir;
QString s = "/log/";
QString filedir = QCoreApplication::applicationDirPath() + s;
bool exist = temp->exists(filedir);
if(!exist)
{
temp->mkpath(filedir);
}
delete temp;
#ifdef QT_NO_DEBUG
qInstallMessageHandler(MessageOutput);
#else
qSetMessagePattern("[%{time yyyyMMdd h:mm:ss t} %{if-debug}D%{endif}%{if-info}I%{endif}%{if-warning}W%{endif}%{if-critical}C%{endif}%{if-fatal}F%{endif}] %{file}:%{line} - %{message}");
#endif
注意:1、要取消控制台需要:去掉终端 注释CONFIG += console
2、解决release打印信息为空的BUG