Qt实现QDebug重定向输出到日志文件(支持多线程安全)

在Qt中,qDebug(),qInfo(),qWarning(),qCritical(),qFatal()常用于打印信息到终端控制台,我们可以将其重定向输出到文件中。

我们创建一个单例类“LogOutput”封装重定向到文件操作:

logoutput.h

#ifndef LOGOUTPUT_H
#define LOGOUTPUT_H
/**
 * @brief QDebug的日志输出重定向到文件
 * @author wjp
 * @date 2024.3.8 modify by wjp
 *
 * */

#include <QObject>
#include <QtMessageHandler>
#include <QDebug>
#include <QFile>
#include <QMutex>
#include <QMutexLocker>

#define LOG_MAXSIZE  5 * 1024 * 1024 //单个log文件最大值

class LogOutput : public QObject
{
    Q_OBJECT
public:
    static LogOutput * getInstance();

    void install(); //安装信息处理函数
    void uninstall(); //卸载信息处理函数
    void deleteLog(); //删除过期日志

protected:
    // 此函数用于注册
    static void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg);

private:
    //将构造函数,拷贝构造,赋值运算符都定义为私有,不允许外部类操作
    explicit LogOutput(QObject *parent = nullptr); //构造函数
    ~LogOutput();  //析构
    LogOutput(const LogOutput &sig) = delete; //拷贝构造函数
    LogOutput& operator=(const LogOutput &sig) = delete ; //赋值运算符重载

private:
    static LogOutput *ins;  //私有静态对象
    static QMutex m_mutex;

    QFile m_curLogFile;
    QString m_curLogFileDate;// 当前日志所属日期,防止在午夜24点刚刚过,需要更换日志输出文件

    //信息处理函数(重写的myMessageHandler)
    /*功能说明:通过调试信息保存到日志文件
     *
     *参数说明:
     * msgType: 调试信息类型或级别(qdebug, qwarning, qfatal 。。。。)
     * context: 调试信息所处文本,可使用context.file和context.line获取文本所处行数及所处文件路径,以及使用co
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值