3.QT中的debug相关的函数,以及文件锁的使用

简介:  1  新建项目T33Debug main.cpp #include <QDebug> #include <QFile> #include <QMutex>   //文件锁   void MyMessageHandler(QtMsgType typ


1  新建项目T33Debug

main.cpp

#include <QDebug>

#include <QFile>

#include <QMutex>   //文件锁

 

void MyMessageHandler(QtMsgType type,const QMessageLogContext &context,const QString &msg)

{

    //使用一个文件锁,当在写文件的时候,要等写完之后才能继续执行

    static QMutex mutex;

    mutex.lock();

 

    QString strContext;

    //QMessageLogContext中保存的有文件名,文件行号,方法等信息

    strContext.sprintf("%s %d %s:\r\n\t",context.file,context.line,context.function);

 

    QString output = strContext + msg + "\r\n";

 

    if(type == QtDebugMsg)

    {

        QFile file("debug.log");

        file.open(QFile::WriteOnly | QFile::Append);

        file.write(output.toUtf8());

        file.close();

    }

    if(type == QtWarningMsg)

    {

        QFile file("warning.log");

        file.open(QFile::WriteOnly|QFile::Append);

        file.write(output.toUtf8());

        file.close();

    }

    if(type == QtCriticalMsg)

    {

        QFile file("critical.log");

        file.open(QFile::WriteOnly | QFile::Append);

        file.write(output.toUtf8());

        file.close();

    }

    if(type == QtFatalMsg)

    {

        QFile file("fatal.log");

        file.open(QFile::WriteOnly | QFile::Append);

        file.write(output.toUtf8());

        file.close();

    }

 

    printf("%s",output.toUtf8().data());

    mutex.unlock();

}

 

int main()

{

    //To suppress the output at runtime, install your own message

    //handler with qInstallMessageHandler().

    qInstallMessageHandler(MyMessageHandler);

    qDebug() << "output debug";

    qDebug("%s,%d","outputdebug",1);

 

    qWarning() << "warning";

    qCritical() << "cridical";

    //可以放开下面的一句,然后发现目录也有相应的fatal.log文件

    //qFatal("fatal info");

}

运行结果:

输入目录(E:\QT\build-T33Debug-Desktop_Qt_5_3_MinGW_32bit-Debug)的文件如下:

 

目录
相关文章
|
编译器 C++
qt槽函数的四种写法
QT槽函数的四种写法
196 0
qt槽函数的四种写法
|
编译器
Qt问题:Qt槽函数是否支持内联?
Qt问题:Qt槽函数是否支持内联?
112 0
25 QT - event函数
25 QT - event函数
120 0
|
12月前
(7)Qt中的自定义槽(函数)
这篇文章介绍了在Qt中如何定义和使用自定义槽函数,包括类成员函数、静态类成员函数、全局函数和lambda表达式作为槽函数的示例,以及使用lambda表达式时的注意事项。
394 2
(7)Qt中的自定义槽(函数)
|
编译器 API
【Qt】- 信号和槽函数
【Qt】- 信号和槽函数
185 3
|
算法 开发者
【Qt SDL相关问题】Qt 引入SDL导致main函数冲突的解决方案
【Qt SDL相关问题】Qt 引入SDL导致main函数冲突的解决方案
267 2
|
监控
QT按键监控函数
QT按键监控函数
|
存储 JSON C++
Qt cmake 增加qml文件:深度剖析Qt cmake 的qt_add_qml_module函数
Qt cmake 增加qml文件:深度剖析Qt cmake 的qt_add_qml_module函数
556 0