qInstallMessageHandler的学习

背景:需要做一个日志系统

把信息重定向到txt文件中。

参考: 

QT 调试信息如何输出到文件(qDebug/qWarning/qCritical/qFatal)-CSDN博客

Qt 之 qInstallMessageHandler(重定向至文件)-CSDN博客 

demo:

#include <QApplication>
#include <QMutex>
#include <QFile>
#include <QTextStream>
#include <QDebug>
static QMutex mutex;
//void myMessageHandler(QtMsgType, const QMessageLogContext &, const QString &);
void customMessageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString txt;
    switch (type) {
    case QtDebugMsg:
        txt="qDebug:";
        break;
    case QtInfoMsg:
        txt="qInfo:";
        break;
    case QtWarningMsg:
        txt="qWarning:";
        break;
    case QtCriticalMsg:
        txt="qCritical:";
        break;
    }
    mutex.lock();
    QFile file("log.txt");
    file.open(QIODevice::WriteOnly|QIODevice::Append);
    QTextStream text_stream(&file);
    text_stream<<txt+msg<<"\r\n";
    text_stream<<QString(context.file)<<"\r\n";
    text_stream<<QString::number(context.line)<<"\r\n";
    text_stream<<QString(context.function)<<"\r\n";
    file.close();
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qInstallMessageHandler(customMessageHandler);
    qDebug()<<"111";
    qInfo()<<"222";
    qWarning()<<"333";
    qCritical()<<"444";
    return a.exec();
}

 关键:

 qInstallMessageHandler(customMessageHandler);

这是一个回调函数

当执行qDebug(),qInfo()......这些的时候,

会调用customMessageHandler()函数

QtMessageHandler qInstallMessageHandler(QtMessageHandler handler); 

为什么要加锁呢?

我的理解:

比如:

qDebug()<<"123"; 
qDebug()<<"456";

这两条语句都会触发customMessageHandler函数,那么可能会出现抢夺log.txt文件使用权的问题,所以要加锁

关于 context.file, context.line, context.function

文件名,文件行数,所在的函数名。 

猜你喜欢

转载自blog.csdn.net/weixin_51883798/article/details/134651440
今日推荐