qt写日志

*本文内容借鉴大佬 一去二三里

#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();
}


引用

#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;
}


效果
在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页