Qt下的log日誌
阿新 • • 發佈:2018-11-08
#include <QApplication> #include <QTextCodec> #include <QDateTime> #include <QFile> #include <QTextStream> #include <QMutex> 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:"); } 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 "); QString current_date = QString("(%1)").arg(current_date_time); //QString message = QString("%1 %2 %3 %4").arg(current_date).arg(text).arg(context_info).arg(msg); QString message = QString("%1 %2 %3").arg(current_date).arg(text).arg(msg); QString timestr=QDateTime::currentDateTime().toString("yyyy-MM-dd"); QString fileName = timestr + ".txt";//假設指定資料夾路徑為D盤根目錄 QFile file(fileName); 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[]) { QApplication a(argc, argv); //註冊MessageHandler qInstallMessageHandler(outputMessage); //列印日誌到檔案中 qDebug("This is a debug message"); qWarning("This is a warning message"); qCritical("This is a critical message"); //qFatal("This is a fatal message"); //Dialog w; //w.show(); return a.exec(); }