Qt实现写日志功能 (代码)
默认情况下,调试信息仅记录在debug版本下
release版本下要使用调试信息,需在.pro文件中添加如下配置
DEFINES += QT_MESSAGELOGCONTEXT
需要在main()函数中添加启动日志的功能 ,如下
//qInstallMessageHandler(outputLog); //启动日志功能
实现代码如下:
void outputLog(QtMsgType msgType, const QMessageLogContext& logContent, const QString& msg)
{
static QMutex s_mutex;
s_mutex.lock();
QString text;
// 判断感兴趣的消息
switch (msgType)
{
case QtDebugMsg:
text = QString("DEBUG:");
break;
case QtWarningMsg:
text = QString("WARNING:");
break;
case QtCriticalMsg:
text = QString("CRITICAL:");
break;
case QtFatalMsg:
text = QString("FATAL:");
break;
}
QString context_info = QString("File:(%1) Line(%2)").arg(QString(logContent.file)).arg(QString(logContent.line));
QString curr_dateTime = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
QString curr_date = QString("%1").arg(curr_dateTime);
QString message = QString("%1 \r\n%2 %3 \r\n%4").arg(curr_date).arg(text).arg(context_info).arg(msg);
// 判断文件是否存在,不存在则创建
QString aFile = QDir::currentPath() + "/LogFile";
qDebug() << aFile;
QDir dir(aFile);
if(!dir.exists())
{
dir.mkdir(aFile);
}
QString curr_time = QDateTime::currentDateTime().toString("yyyyMMdd");
QFile filename(aFile+"/log"+curr_time+".log");
filename.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream textStream(&filename);
textStream << message << "\r\n\r\n";
filename.flush();
filename.close();
s_mutex.unlock();
}