Qt重定向qDebug,实现日志系统(QtDebugMsg、QtInfoMsg、QtWarningMsg、QtCriticalMsg、QtFatalMsg)

原理:

重定向qDebug、qInfo、qWarning、qCritical、qFatal等宏,输出到txt文件。如果需要输出到Qt控件上,则需要使用Qt提供的反射机制。

效果图:

在这里插入图片描述

目录结构如下:

在这里插入图片描述

重点关注:

qInstallMessageHandler()
QMetaObject::invokeMethod()

源码:

MsgHandlerWapper.h:

#ifndef MSGHANDLERWAPPER_H
#define MSGHANDLERWAPPER_H

#include <QObject>

class MsgHandlerWapper : public QObject
{
    Q_OBJECT
public:
    static MsgHandlerWapper * instance();

signals:
    void message(QtMsgType type, const QMessageLogContext &context,const QString &msg);

private:
    MsgHandlerWapper();
    static MsgHandlerWapper * m_instance;
};

#endif // MSGHANDLERWAPPER_H

MsgHandlerWapper.cpp:

#include "msghandlerwapper.h"
#include <QtCore/QMetaType>
#include <QtCore/QMutex>
#include <QtCore/QMutexLocker>
#include <QtCore/QCoreApplication>
#include <QString>

MsgHandlerWapper * MsgHandlerWapper::m_instance = nullptr;

void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QMetaObject::invokeMethod(MsgHandlerWapper::instance(), "message" , Q_ARG(QtMsgType, type) ,Q_ARG(QMessageLogContext , context) ,  Q_ARG(QString, QString(msg)));
}

MsgHandlerWapper * MsgHandlerWapper::instance()
{
    static QMutex mutex;
    if (!m_instance)
    {
        QMutexLocker locker(&mutex);
        if (!m_instance)
            m_instance = new MsgHandlerWapper;
    }

    return m_instance;
}

MsgHandlerWapper::MsgHandlerWapper():QObject(qApp)
{
    qRegisterMetaType<QtMsgType>("QtMsgType");
    qInstallMessageHandler(myMessageOutput);
}

LogTextEdit.h:

#ifndef LOGTEXTEDIT_H
#define LOGTEXTEDIT_H
#include <QPlainTextEdit>
#include <QTextStream>
#include <QDateTime>
#include "msghandlerwapper.h"
#include <QDebug>

class LogTextEdit : public QPlainTextEdit
{
    Q_OBJECT

private:
    QTextStream gOutStream;
    QFile logFile;

public:
    explicit LogTextEdit(QWidget * parent = nullptr) :QPlainTextEdit(parent)
    {
        connect(MsgHandlerWapper::instance(), SIGNAL(message(QtMsgType,QMessageLogContext ,QString)), SLOT(outputMessage(QtMsgType,QMessageLogContext ,QString)));
        openLogFile();
    }

    ~LogTextEdit()
    {
        logFile.flush();
        logFile.close();
        gOutStream.flush();
    }
public slots:
    void outputMessage(QtMsgType type, const QMessageLogContext &context ,const QString &msg)
    {
        QByteArray localMsg = msg.toLocal8Bit();
        QString text;
        QString htmlText;
        switch (type)
        {
        case QtDebugMsg:
            text = QString::fromLocal8Bit("Debug: %1 (%2:%3, %4)\n").arg(QString::fromLocal8Bit(localMsg.constData())).arg(context.file).arg(context.line).arg(context.function);
            htmlText = formatHtml(text , "green");
            break;
        case QtInfoMsg:
            text = QString::fromLocal8Bit("Info: %1 (%2:%3, %4)\n").arg(QString::fromLocal8Bit(localMsg.constData())).arg(context.file).arg(context.line).arg(context.function);
            htmlText = formatHtml(text , "green");
            break;
        case QtWarningMsg:
            text = QString::fromLocal8Bit("Warning: %1 (%2:%3, %4)\n").arg(QString::fromLocal8Bit(localMsg.constData())).arg(context.file).arg(context.line).arg(context.function);
            htmlText = formatHtml(text , "rgb(255, 170, 0)");
            break;
        case QtCriticalMsg:
            text = QString::fromLocal8Bit("Critical: %1 (%2:%3, %4)\n").arg(QString::fromLocal8Bit(localMsg.constData())).arg(context.file).arg(context.line).arg(context.function);
            htmlText = formatHtml(text , "red");
            break;
        case QtFatalMsg:
            text = QString::fromLocal8Bit("Fatal: %1 (%2:%3, %4)\n").arg(QString::fromLocal8Bit(localMsg.constData())).arg(context.file).arg(context.line).arg(context.function);
            htmlText = formatHtml(text , "red");
            break;
        default:
            text = QString::fromLocal8Bit("Default: %1 (%2:%3, %4)\n").arg(QString::fromLocal8Bit(localMsg.constData())).arg(context.file).arg(context.line).arg(context.function);
            htmlText = formatHtml(text , "black");
        }

        gOutStream << QDateTime::currentDateTime().toString("[yyyy-MM-dd hh.mm.ss]\t") + text; //输出到txt文件
        gOutStream .flush(); //刷新缓冲区
        appendHtml(htmlText);
    }

private:
    void openLogFile()
    {
        logFile.setFileName("./Df_Soft_Log.txt");
        if(!logFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append))
        {
            //
        }
        else
        {
            gOutStream.setDevice(&logFile);
        }
    }

    const QString formatHtml(const QString &qText , QString color)
    {
        return QString("<font style='font-size:16px; background-color:white; color:%2;'> %1 </font>").arg(qText).arg(color);
    }
};

#endif // LOGTEXTEDIT_H

源码下载

地址:https://download.csdn.net/download/rl529014/10998010

同类文章链接:https://blog.csdn.net/rl529014/article/details/81462079

已标记关键词 清除标记
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页