此日志是在主线程中实现输出信息,可能对于比较多的线程的项目,不是一个很好的选择。下面记录一下。
首先创建一个头文件log.hpp,也可直接创建成log.h,本人是由于创建前打算在其中定义函数,后又没有定义,也没有再删除后重新创建,就在这个文件中写了。
log.hpp
#ifndef LOG_H
#define LOG_H#include <QCoreApplication>
#include <QDebug>#define OUTPUT_LOG //输出信息输出到输出控制台还是日志,注释掉——release下不能生成日志,在debug版在输出信息栏输出信息,放开——release下生成日志#ifdef OUTPUT_LOG
#define outPut qOut//release版
#else
#define outPut qDebug()//debug版
#endif//日志文件名称
#define LOG_FILE QCoreApplication::applicationDirPath()/*strFilePath*/ + "/logger.txt"
#define qOut qDebug()<<__FUNCTION__<<"["<<__LINE__<<"]"
#define xErrPrint qCritical()<<__FUNCTION__<<"["<<__LINE__<<"]"#endif // LOG_H
上述文件中掺杂着可以实现在debug线能够输出打印信息,release下在日志文件中输出打印信息的代码段。在下一篇博文中将会做讲解。
编写完log.hpp后,在main.cpp中添加如下代码:
#include "maindialog.h"#include <QApplication>
#include <QFile>
#include "log.hpp"
#include <QMutex>
#include <QDateTime>void MessageTypePut(QtMsgType type, const QMessageLogContext &context, const QString &msg);int main(int argc, char *argv[])
{
#ifdef OUTPUT_LOGqInstallMessageHandler(MessageTypePut);
#endifQApplication a(argc, argv);MainDialog w;w.show();return a.exec();
}void MessageTypePut(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:break;}//日志写到文件QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");QString message = QString("%1 %2%3").arg(current_date_time).arg(text).arg(msg);QFile file(LOG_FILE);file.open(QIODevice::WriteOnly | QIODevice::Append);QTextStream text_stream(&file);text_stream << message << "\r\n";file.flush();//将缓冲的数据刷新到文件file.close();mutex.unlock();
}
将main.cpp添加完部分代码后是上面所贴代码的样子。
使用的时候采用如下的方法:
#include "log.hpp" //包含头文件log.hppoutPut<<"创建界面失败!";//输出采用outPut<<
outPut<<"m_info = "<<m_info.rect.x;
和qDebug()的输出相似。其中#define OUTPUT_LOG被注释掉之后只能在debug模式下向应用程序输出栏输出信息,放开#define OUTPUT_LOG的注释,可以在release模式下在可执行文件所在目录生成日志文件,内包含输出信息。