qDebug | 调试信息提示 |
qWarning | 一般的警告提示 |
qCritical | 严重错误提示 |
qFatal | 致命错误提示 |
void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
static QMutex mutex;
mutex.lock();
QString text;
switch (type)
{
case QtDebugMsg:
text = QString("Debug:");
break;
case QtWarningMsg:
text = QString("Warning:");
break;
case QtCriticalMsg:
text = QString("Critical:");
break;
case QtFatalMsg:
text = QString("Fatal:");
break;
}
QString context_info = QString("File:(%1) Line(%2)").arg(QString(context.file)).arg(context.line);
QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
QString current_date = QString("(%1)").arg(current_date_time);
QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);
QFile file("log.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
mutex.unlock();
}
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qInstallMessageHandler(outputMessage);
qDebug() << "0-------0";
qDebug("This is a debug message");
qWarning("This is a warning message");
qCritical("This is a critical message");
//qFatal 会终止程序 debug模式下运行会直接段错误 qt的机制
//qFatal("This is a fatal message");
qDebug() << "1-------1";
return a.exec();
}