一、调试信息类型
前面两种输出调试信息,后面三个输出错误信息,严重级别依次增加:
- qDebug():QtDebugMsg(调试信息)
如果项目中定义了QT_NO_WARNING_OUTPUT,则不会执行此函数。 - qInfo():QtInfoMsg(一般信息)
- qWarning():QtWarningMsg(警告信息)
如果项目中定义了QT_NO_WARNING_OUTPUT,则不会执行此函数。 - qCritical():QtCriticalMsg(严重信息)
- qFatal():QtFatalMsg(致命信息)
默认实现将使程序中断。
二、日志消息处理API
- qInstallMessageHandler(“回调函数”)
安装消息处理函数,传入回调函数,输出调试信息的时候就调用此回调函数。 - IsDebuggerPresent()
判断当前是否处于调试环境,如果有调试器附加(如Dbgview工具),就不会将日志信息输出到日志文件中。 - OutputDebugStringA(“日志信息”)
调试信息的Windows API(ANSI版本),用来输出日志信息到日志文件或调试器。
三、日志信息输出接口
1.loginfo.h文件
#ifndef LOGINFO_H
#define LOGINFO_H
#include <QtGlobal>
#include <QFile>
#include <QDir>
#include <QDate>
#include <QTime>
#include <qt_windows.h>
class LogInfo
{
public:
static void RecordLog();
private:
static void outputLog(QtMsgType type,const QMessageLogContext &context,const QString &msg);
};
#endif // LOGINFO_H
2.loginfo.cpp文件
#include "loginfo.h"
void LogInfo::RecordLog()
{
if(IsDebuggerPresent()){
return;
}
qInstallMessageHandler(outputLog); //安装消息处理函数
}
void LogInfo::outputLog(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
QDir projectDir(QDir::currentPath()); //当前工程目录下
const QString logDir = "log";
if(!projectDir.exists(logDir)){
projectDir.mkdir(logDir);
}
projectDir.cd(logDir); //切换到日志目录下
QString logPath = projectDir.filePath(QDate::currentDate().toString("yyyy-MM-dd")+".txt");
QFile logFile(logPath); //创建日志文件
if(!logFile.open(QFile::Append | QFile::WriteOnly)){
qInstallMessageHandler(0); //恢复消息处理程序
qDebug("ERROR OPEN LOG FILE");
return;
}
QString tp = nullptr;
switch (type){
case QtDebugMsg:
tp = "Debug";
break;
case QtInfoMsg:
tp = "Info";
break;
case QtWarningMsg:
tp = "Warning";
break;
case QtCriticalMsg:
tp = "Critical";
break;
case QtFatalMsg:
tp = "Fatal";
break;
default:
break;
}
QString logLine = QString("%1%2 %3:%4:%5:%6 %7%8\r").arg("Time::").arg(QTime::currentTime().toString("hh:mm:ss"))
.arg(tp).arg(context.file).arg(context.line).arg(context.function).arg("Log::").arg(msg);
logFile.write(logLine.toUtf8());
OutputDebugStringA(msg.toLocal8Bit());
}
3.调用方式
提示:在调用该接口之后,工程的调试信息才会输出到日志文件中
在mian函数里直接调用LogInfo::RecordLog()即可,记得加入头文件#include “loginfo.h”。