Qt - 简单的写日志方法
作者:互联网
Qt写日志
在main.cpp文件中添加以下头文件和代码:
#include "mainwindow.h"
#include <QApplication>
#include <QDateTime>
#include <QMutex>
#include <QFile>
#include <QTextStream>
#include <QDebug>
//#define LOG_FILE qApp->applicationDirPath()+"/logger.txt"
void outputMessage(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:");
default:
break;
}
QString context_info = QString("[%1 %2]:").arg(QString(context.function)).arg(context.line);//文件名,所在行数
QString current_date = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
QString message = QString("%1 %2 %3").arg(current_date).arg(text).arg(msg);//.arg(context_info).arg(msg);
QFile file("log.txt");
file.open(QIODevice::WriteOnly | QIODevice::Append);
QTextStream text_stream(&file);
text_stream << message << "\r\n";
file.flush();
file.close();
mutex.unlock();
}
int main(int argc, char *argv[])
{
qInstallMessageHandler(outputMessage);//安装消息处理器调用回调函数
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
在mainwindow.cpp源文件中添加以下代码
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
#define cout qDebug()<<"["<<__FUNCTION__<<":"<<__LINE__<<"]"
#pragma execution_character_set("utf-8")
MainWindow::MainWindow(QWidget *parent): QMainWindow(parent), ui(new Ui::MainWindow)
{
ui->setupUi(this);
qDebug()<<"这是一个写日志的测试";
cout << "测试";
}
MainWindow::~MainWindow()
{
delete ui;
}
日志文件在项目里能看到:
日志内容:
标签:Qt,text,arg,QString,context,简单,日志,include,mainwindow 来源: https://www.cnblogs.com/zhuchunlin/p/16485102.html