Qt打印Log日志到文件

简介

写软件时有时候需要记录日志到文件,方便查看软件运行信息和排查问题,Qt有自己的日志打印功能,实现Qt日志功能需要用到下面的函数,其中Qt4和Qt5的函数有区别;

  • QtMessageHandler qInstallMsgHandler(QtMessageHandler handler) //Qt4函数
  • QtMessageHandler qInstallMessageHandler(QtMessageHandler handler) //Qt5函数

上面的函数是用来打印调试信息,警报信息,危险信息和致命信息的。当Qt有内部错误产生时,Qt调试库会打印几百种警报信息(通常是异常的函数参数),Qt以发布模式编译也会包含这些警报信息,除非在编译的时候设置了QT_NO_WARNING_OUTPUT 和QT_NO_DEBUG_OUTPUT 。消息打印在X11 下默认输出在标准输出,在Windows模式输出在调试器。如果是输出的致命错误消息,程序会立刻退出。
z在一个程序中只能定义一个消息管理者,如果要恢复消息管理, 调用qInstallMessageHandler(0)。

在 main函数中加入下面的调用函数:

#if QT_VERSION < 0x050000
        qInstallMsgHandler(logMessageOutputQt4); //Qt4
#else
        qInstallMessageHandler(logMessageOutputQt5); //Qt5        
#endif

Qt4打印,需要自己加入文件名,函数名和行号:

qDebug("[%s] [%s] [%d] This is a debug message", __FILE__, __FUNCTION__, __LINE__);
    qDebug("[%s] [%s] [%d] This is a warning message", __FILE__, __FUNCTION__, __LINE__);
    qDebug("[%s] [%s] [%d] This is a critical message", __FILE__, __FUNCTION__, __LINE__);
    qDebug("[%s] [%s] [%d] This is a fatal message", __FILE__, __FUNCTION__, __LINE__);

Qt5打印,打印的文件名、函数名和行号在下面的消息处理函数中获得:

qDebug("This is a debug message");
qWarning("This is a warning message");
qCritical("This is a critical message");
qFatal("This is a fatal message");

Qt4消息处理函数定义

void logMessageOutputQt4(QtMsgType type, const char *msg)
{
    static qint64 max = 10485760; //10 * 1024 * 1024;
    if (QString("%1").arg(msg).contains("QWSLock")) {
        return;
    }
    static QMutex mutex;
    mutex.lock();
    QString text;
    switch (type) {
    case QtDebugMsg:
        text = QString("Debug:");
        break;
    case QtWarningMsg:
        text = QString("Warning:");
        break;
    case QtCriticalMsg:
        text = QString("Critical:");
        break;
    case QtFatalMsg:
        text = QString("Fatal:");
        abort();
    default:
        break;
    }
    QString message = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss")).arg(text).arg(msg);

    QFile file("/home/sun/rootnfs/myqttest/log4.txt");
    if (file.size() > max) { //超过指定大小时截取文件
        file.rename("/home/sun/rootnfs/myqttest/tmp.txt");
        QFile logfile("/home/sun/rootnfs/myqttest/log4.txt");

        file.open(QIODevice::ReadWrite);
        logfile.open(QIODevice::ReadWrite);
        qint64 nresult = 4194304; //4 * 1024 * 1024;
        file.seek(file.size() - nresult);
        char lbuffer[256];
        int count;
        while ((count = file.read(lbuffer, 256)) == 256) {
            logfile.write(lbuffer, count);
        }
        logfile.write(message.toLatin1(), message.count());
        file.close();
        file.remove();
        logfile.close();
    } else {
        QTextStream text_stream(&file);
        file.open(QIODevice::ReadWrite | QIODevice::Append);
        text_stream << message << endl;
        file.flush();
        file.close();
    }
    mutex.unlock();
}

打印效果

[2017-05-11 16:15:46] Debug: [qttest/main.cpp] [main] [13] This is a debug message
[2017-05-11 16:15:46] Warning: [qttest/main.cpp] [main] [14] This is a warning message
[2017-05-11 16:15:46] Critical: [qttest/main.cpp] [main] [15] This is a critical message

Qt5消息处理函数定义

void logMessageOutputQt5(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static qint64 max = 10485760;//10 * 1024 * 1024;
    static QMutex mutex;
    mutex.lock();
    QString text;
    switch (type) {
    case QtDebugMsg:
        text = QString("Debug:");
        break;
    case QtWarningMsg:
        text = QString("Warning:");
        break;
    case QtCriticalMsg:
        text = QString("Critical:");
        break;
    case QtFatalMsg:
        text = QString("Fatal:");
        abort();
    default:
        break;
    }
    QString message = QString("[%1] %2 [%3] [%4] [%5] %6").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss"))
            .arg(text).arg(context.file).arg(context.function).arg(context.line).arg(msg);

    QFile file("/home/sun/rootnfs/myqttest/log5.txt");
    if (file.size() > max) { //超过指定大小时截取文件
        file.rename("/home/sun/rootnfs/myqttest/tmp.txt");
        QFile logfile("/home/sun/rootnfs/myqttest/log5.txt");

        file.open(QIODevice::ReadWrite);
        logfile.open(QIODevice::ReadWrite);
        qint64 nresult = 4194304; //4 * 1024 * 1024;
        file.seek(file.size() - nresult);
        char lbuffer[256];
        int count;
        while ((count = file.read(lbuffer, 256)) == 256) {
            logfile.write(lbuffer, count);
        }
        logfile.write(message.toLatin1(), message.count());
        file.close();
        file.remove();
        logfile.close();
    } else {
        QTextStream text_stream(&file);
        file.open(QIODevice::ReadWrite | QIODevice::Append);
        text_stream << message << endl;
        file.flush();
        file.close();
    }
    mutex.unlock();
}

打印效果

[2017-05-11 16:15:46] Debug: [../qttest/main.cpp] [int main(int, char**)] [13] This is a debug message
[2017-05-11 16:15:46] Warning: [../qttest/main.cpp] [int main(int, char**)] [14] This is a warning message
[2017-05-11 16:15:46] Critical: [../qttest/main.cpp] [int main(int, char**)] [15] This is a critical message
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值