Qt中自定義日誌輸出格式,並寫入文件

1.重寫方法

using namespace std;

//日誌代碼互斥鎖

QMutex logMutex;

QString timePoint;

void LogMsgOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)

{

   logMutex.lock();

   QByteArray localMsg = msg.toLocal8Bit();

   QString log;

   //日誌時間戳

   log.append(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss "));

   switch (type) 

   {

       case QtDebugMsg:

       {

           log.append(QString("Debug: %1(FILE: %2:%3, FUNCTION: %4)

").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));

           break;

        }

       case QtInfoMsg:

       {

           log.append(QString("Info: %1(FILE: %2:%3, FUNCTION: %4)

").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));

           break;

        }

        case QtWarningMsg:

        {

            log.append(QString("Warning: %1(FILE: %2:%3, FUNCTION: %4)

").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));

            break;

         }

         case QtCriticalMsg:

         {

             log.append(QString("Critical: %1(FILE: %2:%3, FUNCTION: %4)

").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));

             break;

          }

         case QtFatalMsg:

         {

            log.append(QString("Fatal: %1(FILE: %2:%3, FUNCTION: %4)

").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function));

            break;

          }

      }

   QDir tempDir;

   if (!tempDir.exists("./log"))

   {

       qDebug() << "log dir not exist" << endl;

       tempDir.mkpath("./log");

   }

   QFile file;

   QString path = QString("./log/%1.log").arg(timePoint);

   file.setFileName(path);

   if (!file.open(QIODevice::ReadWrite | QIODevice::Append))

   {

       QString erinfo = file.errorString();

       cout << erinfo.toStdString() << endl;

       return;

    }

    QTextStream out(&file);

    out << log << "\n\r";

    file.flush();

    file.close();

    logMutex.unlock();

}

2.在main函數中安裝自定義的方法

    timePoint = QDateTime::currentDateTime().toString("yyyy-MM-dd_HH_mm_ss");

    qInstallMessageHandler(LogMsgOutput);

 

注意:

1)在編譯release版本的時候日誌文件中部分內容會爲空,比如文件名、函數名和文件行數,因爲Qt默認會去掉相關信息,解決方法是在pro文件中添加宏定義 DEFINES += QT_MESSAGELOGCONTEXT,如果是VS開發環境在配置項的C++預編譯器中添加此宏,release版本的日誌中就會有相關信息

2)在自定義日誌handler中的qDebug不會有日誌寫入文件,因爲一旦允許這樣操作就會陷入無窮遞歸,所以上面代碼中判斷日誌文件夾是否存在時的 qDebug() << "log dir not exist" << endl;不會在日誌文件中出現,可參考Qt源文件qlogging.cpp的實現和說明

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章