Qt中写日志文件

倘若是windows下,路径改为:const static QString log_path =  QCoreApplication::applicationDirPath ();测试可用。

 linux系统下程序如下:

#include <QDir>
#include <QFile>
#include <QMutex>
#include <QtDebug>
#include <QtGlobal>
#include <QDateTime>
void myMessageOutput(QtMsgType type, const char *msg)
{
    const static QString log_path =  QDir::homePath() + "/myProject/log/";
    static QMutex mutex;
    mutex.lock();

    QString text;
    switch(type)
    {
    case QtDebugMsg:
        text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Debug:")).arg(msg);
        fprintf(stderr, "%s\n", msg);
        break;

    case QtWarningMsg:
        text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Warning:")).arg(msg);
        fprintf(stderr, "%s\n", msg);
        break;

    case QtCriticalMsg:
        text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Critical:")).arg(msg);
        fprintf(stderr, "%s\n", msg);
        break;

    case QtFatalMsg:
        text = QString("[%1] %2 %3").arg(QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd")).arg(QString("Fatal:")).arg(msg);
        fprintf(stderr, "%s\n", msg);
        abort();
        break;

    default:
        break;
    }
    if (!text.isEmpty())
    {
        QString message = text;
        QString log_file = QDateTime::currentDateTime().toString("yyyy-MM-dd") + "log.txt";

        QFile file(log_path+ "/" +log_file);
        if (!file.open(QIODevice::WriteOnly | QIODevice::Append))
        {
            fprintf(stderr, "%s\n", file.errorString().toStdString().c_str());
        }
        QTextStream ts(&file);
        ts << message << endl;
        file.flush();
        file.close();
    }
    mutex.unlock();
}
int main(int argc, char *argv[])
{
    //注册MsgHandler
    qInstallMsgHandler(myMessageOutput);
    QCoreApplication a(argc, argv);
    
    //在需要打印出错信息的位置,按照错误信息的严重程度选择以下四种打印方式
    qDebug("This is a debug message"); 
    qWarning("This is a warning message"); 
    qCritical("This is a critical message"); 
    qFatal("This is a fatal message"); //windows下测试,使用这条程序会崩。
}

注意:

1)main中添加了qInstallMsgHandler(myMessageOutput);这条代码后,打印信息都会写到日志文件中了,并不会在终端中输出。因此,在调试的过程中可以先把这条信息屏蔽掉;

2)  windows下测试,使用qFatal("This is a fatal message");时,程序会直接崩掉,所以,日志输出时不要用这条输出信息?

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值