使用Qt实现简单的日志记录功能(qInstallMessageHandler)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/rl529014/article/details/81462079

前言:

相信大家在软件开发的过程中,都有记录软件运行日志的需求,凭借日志信息来分析软件的运行状况,或者是查找、定位软件存在的未知Bug。

基于C++的日志工具有log4cplus、log4cxx,Log4Qt等,但如果只是并非复杂的环境使用,其实我们可以讲Qt的消息输出,重定向到日志文件,就可以实现一个简单的日志记录系统。

Qt包含用于警告和调试文本的全局宏:

 1. qDebug()  :调试消息
 2. qInfo()  : 信息消息
 3. qWarning() :  警告消息和可恢复的错误
 4. qCritical()  :关键错误和系统错误
 5. qFatal() :致命错误

Qt Assistant原文:
Qt includes global macros for writing out warning and debug text. You can use them for the following purposes:
- qDebug() is used for writing custom debug output.
- qInfo() is used for informational messages.
- qWarning() is used to report warnings and recoverable errors in your application.
- qCritical() is used for writing critical error messages and reporting system errors.
- qFatal() is used for writing fatal error messages shortly before exiting.

实践:

下面列出代码:

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QByteArray localMsg = msg.toLocal8Bit();
    QString text;
    switch (type)
    {
    case QtDebugMsg:
        text = QString("Debug: %1 (%2:%3, %4)\n").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);
        break;
    case QtInfoMsg:
        text = QString("Info: %1 (%2:%3, %4)\n").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);      
        break;
    case QtWarningMsg:
        text = QString("Warning: %1 (%2:%3, %4)\n").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);
        break;
    case QtCriticalMsg:
        text = QString("Critical: %1 (%2:%3, %4)\n").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);
        break;
    case QtFatalMsg:
        text = QString("Fatal: %1 (%2:%3, %4)\n").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);
        abort();
    default:
        text = QString("Default: %1 (%2:%3, %4)\n").arg(localMsg.constData()).arg(context.file).arg(context.line).arg(context.function);
    }
    gOutStream << QDateTime::currentDateTime().toString("yyyy-MM-dd hh.mm.ss ") + text; //输出到txt文件
    gOutStream .flush(); //刷新缓冲区
}

在应用程序的main函数中,注册我们的回调函数:

 qInstallMessageHandler(myMessageOutput);

上面的代码片中,gOutStream 是一个全局的输出流,我们可以将其输出到文件,。

 QFile file("log.txt");
      if (!file.open(QIODevice::WriteOnly | QIODevice::Text))
          return;
 QTextStream gOutStream (&file);
 qDebug<< "这是日志输出" ;

在Debug模式下,可以将信息输出定位到某个具体的文件、某个函数、某行代码,可以说是非常强大了。

下面是运行txt日志文件的效果截图:

这里写图片描述

猜你喜欢

转载自blog.csdn.net/rl529014/article/details/81462079