Qt之分模块log

这篇博客介绍了如何创建一个自定义的日志模块,以适应程序运行时动态创建的模块,每个模块可以有独立的日志记录。通过重定向Qt的qInstallMessageHandler,实现了根据不同日志等级分类存储,并提供了宏定义方便使用。同时,代码示例展示了如何将日志信息写入文件,并包含了时间戳和文件信息。
摘要由CSDN通过智能技术生成

对于一般的log,使用 qInstallMessageHandler 重定向到文件即可,甚至可以根据日志等级,分类存储。但是并不是适用所有情况,比如,程序运行时动态创建模块,而每个模块需要创建不用的日志记录。参考Qt的 QDebug 代码,重新编写日志模块。


/********************************************************************************
*
*  Description  log模块,根据传入参数,创建log文件
*  Author    sherlock
*  Creation Time  2019/8/28
*  Modify
*
*******************************************************************************/

#ifndef LOGGER_H
#define LOGGER_H

#include <stdio.h>
#include <stdlib.h>
#include <QFile>
#include <QTextStream>
#include <QDir>
#include <QDateTime>
#include <QMutex>

class Logger
{
public:
    Logger(){}
    static void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
        static QMutex mutex;
        mutex.lock();
        QString log_message;
        QByteArray localMsg = msg.toLocal8Bit();
        switch (type) {
        case QtDebugMsg:
            log_message = QString("Debug\t:");
            fprintf(stderr, "Debug: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
            break;
        case QtInfoMsg:
            log_message = QString("Info\t:");
            fprintf(stderr, "Info: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
            break;
        case QtWarningMsg:
            log_message = QString("Warning\t:");
            fprintf(stderr, "Warning: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
            break;
        case QtCriticalMsg:
            log_message = QString("Critical\t:");
            fprintf(stderr, "Critical: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
            break;
        case QtFatalMsg:
            fprintf(stderr, "Fatal: %s (%s:%u, %s)\n", localMsg.constData(), context.file, context.line, context.function);
            abort();
        }
        fflush(stderr);//立即输出,msvc没有这句也会立即输出,但是mingw不会


#ifndef QT_DEBUG
//        if(QtDebugMsg == type)
//        {
//            mutex.unlock();
//            return;
//        }
        log_message = QString("%1 %2").arg(log_message).arg(msg);
#else  //release下不会有文件以及函数信息
        log_message = QString("%1 %2\t(%3:%4, %5)").arg(log_message).arg(msg).arg(context.file).arg(context.line).arg(context.function);
#endif // else

        QDir dir;
        if(!dir.exists(logPath))
        {
            dir.mkpath(logPath);
        }

        QDateTime current_time = QDateTime::currentDateTime();
        QString log_file_name = QString("%1/%2_%3.log").arg(logPath)
                .arg(context.category)
                .arg(QDate::currentDate().toString("yyyyMMdd"));

        QFile outFile(log_file_name);
        if (outFile.open(QIODevice::WriteOnly | QIODevice::Append | QIODevice::Text))
        {
            QTextStream write_log(&outFile);
            write_log << current_time.toString("yyyy-MM-dd hh:mm:ss") << "-";
            write_log << log_message << endl;
            outFile.close();
        }

        mutex.unlock();
    }

private:
    static QString logPath;
};

//默认当前路径下的log文件夹下
QString Logger::logPath = QString("%1/104_file_log").arg(QDir::currentPath());

#endif

为了保证旧代码不受影响,可以在项目根目录下新增QDebug文件,填入以下内容

QDebug

#include "qdebug.h"

#define qModuleDebug(module) QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, module.toStdString().c_str()).debug()
#define qModuleInfo(module) QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, module.toStdString().c_str()).info()
#define qModuleWarning(module) QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, module.toStdString().c_str()).warning()
#define qModuleCritical(module) QMessageLogger(QT_MESSAGELOG_FILE, QT_MESSAGELOG_LINE, QT_MESSAGELOG_FUNC, module.toStdString().c_str()).critical()

使用时,只需要使用 qModuleDebug 宏替代原先的 qDebug宏即可,且原来的 qDebug 仍然可以使用


QString moduleName = "test";
qModuleDebug(moduleName)<<"This is test log";

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蝈蝈(GuoGuo)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值