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

31 篇文章 8 订阅

原理:

重定向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

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值