Qt日志输出到文件

Qt日志输出到文件

#include <QApplication>
#include <QLibraryInfo>

#include "mainwindow.h"

#include <QDateTime>
#include <QDebug>
#include <fstream>      // std::ofstream
std::ofstream g_OutputDebug;

void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    // 加锁
    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: ");
        break;
    default:
        text = QString("Debug: ");
    }

    QString context_info = QString("F:(%1) L:(%2)").arg(QString(context.file)).arg(context.line); // F文件信息L行数
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString current_date = QString("(%1)").arg(current_date_time);
    std::string message = qPrintable(QString("%1 %2 \t%3 \t%4").arg(text).arg(context_info).arg(current_date).arg(msg));
    g_OutputDebug << message << "\r\n"; // std::ofstream
    // 解锁
    mutex.unlock();
}

int main(int argc, char *argv[])
{
	QApplication a(argc, argv);
    // Qt的一个宏,消除未使用变量的警告,无实际作用
    // 定义为,#define Q_UNUSED(x) (void)x
    Q_UNUSED( argc );
    Q_UNUSED( argv );

    QString strDir = QCoreApplication::applicationDirPath()+"/Log/";
    QDir dir(strDir);
    if(!dir.exists())
    {
        dir.mkdir(strDir);
    }
    //注册MessageHandler
    qInstallMessageHandler(outputMessage); //注册MessageHandler
    g_OutputDebug.open(qPrintable(strDir+QString(QString(QDateTime::currentDateTime().toString("yyyy-MM-dd-hh-mm-ss").append("-log.txt")))), std::ios::out | std::ios::trunc);

    MainWindow w;
    a.connect(&a,SIGNAL(lastWindowClosed()),&a,SLOT(qiut()));   //这两句解决程序退出时崩溃,好像并没有什么卵用(#^.^#)
    w.setAttribute(Qt::WA_QuitOnClose,true);

    w.setWindowTitle(QString::fromLocal8Bit("中断缺陷检测"));
    w.show();
    return a.exec();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值