---
title: "Qt 定制qDebug() 信息到log文件"
author: "wan_2004"
date: "2011-01-19T17:44:22Z"
tags: []
categories: ["编程语言"]
slug: "qt-qdebug-log"
draft: false
lastmod: "2011-01-19T17:44:22Z"
id: 888963
url: "https://wan-2004.iteye.com/blog/888963"
---

Qt中有**qInstallMsgHandler** 方法可以去定制消息发生后的回调函数，它回调同时还有qDebug的级别信息。这样我们可以方便把错误消息定制到自己的log文件里面

如下：

```
#include <QtDebug>
#include <QFile>
#include <QTextStream>
 //回调函数实现debug信息到文件
void customMessageHandler(QtMsgType type, const char *msg)
{
	QString txt;
	switch (type) {
	case QtDebugMsg:
		txt = QString("Debug: %1").arg(msg);
		break;
 
	case QtWarningMsg:
		txt = QString("Warning: %1").arg(msg);
	break;
	case QtCriticalMsg:
		txt = QString("Critical: %1").arg(msg);
	break;
	case QtFatalMsg:
		txt = QString("Fatal: %1").arg(msg);
		abort();
	}
 
	QFile outFile("debug.log");
	outFile.open(QIODevice::WriteOnly | QIODevice::Append);
	QTextStream ts(&outFile);
	ts << txt << endl;
}
 
int main( int argc, char * argv[] )
{
	QApplication app( argc, argv );
 
	//这个方法注册回调函数       
	qInstallMsgHandler(customMessageHandler);	
	...
	return app.exec();
}
```