Chinaunix首页 | 论坛 | 博客
  • 博客访问: 30104018
  • 博文数量: 230
  • 博客积分: 2868
  • 博客等级: 少校
  • 技术积分: 2223
  • 用 户 组: 普通用户
  • 注册时间: 2009-10-08 21:48
个人简介

Live & Learn

文章分类

全部博文(230)

文章存档

2022年(2)

2019年(5)

2018年(15)

2017年(42)

2016年(24)

2015年(13)

2014年(1)

2012年(5)

2011年(58)

2010年(56)

2009年(9)

我的朋友

分类: LINUX

2015-08-27 11:49:24

#include <QtDebug>
#include <QFile> 
#include <QTextStream> 
#define _TIME_ qPrintable (QTime::currentTime ().toString ("hh:mm:ss:zzz")) 
void Log(QtMsgType type, const char* msg)
{
    QString qstrText; switch (type)
    { case QtDebugMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg); break; case QtWarningMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg); break; case QtCriticalMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg); break; case QtFatalMsg:
        qstrText = QString("%1: %2").arg(_TIME_, msg);
        exit(0);
    }
    QFile out("log.txt"); out.open(QIODevice::WriteOnly | QIODevice::Append);
    QTextStream ts(&out);
    ts<<qstrText<<endl;
} int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    qInstallMsgHandler(Log);

    qDebug("this is a debug message");
    qWarning("this is a warning message");
    qCritical("this is a critical message");
    qFatal("this is a fatal message"); return a.exec();
}
 
//=========================================================

使用qInstallMsgHandler将日志保存到文件

1  在main函数之前定义回调函数

void myMessageOutput(QtMsgType type, const char *msg) {     QString text;     switch (type)     {     case QtDebugMsg:         text = QString("Debug: %1").arg(msg);         break;     case QtWarningMsg:         text = QString("Warning: %1").arg(msg);         break;     case QtCriticalMsg:         text = QString("Critical: %1").arg(msg);         break;     case QtFatalMsg:         text = QString("Fatal: %1").arg(msg);         abort();     }     QFile file("111.txt");     file.open(QIODevice::WriteOnly | QIODevice::Append);     QTextStream ts(&file);     ts<<text<<endl; }

2  在main函数中注册myMessageOutput

qInstallMsgHandler(myMessageOutput);

3  注册后,在该程序的任何地方使用即可。

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

posted on 2011-03-22 17:25 seahouse 阅读(1056) 评论(0)  编辑 收藏 引用 所属分类: Qt

阅读(3097) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~