Qt重定向qDebug,实现日志系统(QtDebugMsgQtInfoMsgQtWarningMsgQtCriticalMsgQtFatalMsg)

Posted 好儿郎-志在四方

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Qt重定向qDebug,实现日志系统(QtDebugMsgQtInfoMsgQtWarningMsgQtCriticalMsgQtFatalMsg)相关的知识,希望对你有一定的参考价值。

原理:

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

以上是关于Qt重定向qDebug,实现日志系统(QtDebugMsgQtInfoMsgQtWarningMsgQtCriticalMsgQtFatalMsg)的主要内容,如果未能解决你的问题,请参考以下文章

将 qDebug 重定向到发出的信号

Log4Qt快速入门——Log4Qt日志输出重定向源码解析

Qt高级——Qt日志信息处理

Log4Qt 输出重定向(控制台)

有没有办法将系统日志消息重定向到标准输出?

systemd 应用异常退出自启动 + 日志重定向