QT log日志的使用

log日志是一个很关键的内容,在项目开发中很实用,接下来是基于QT5版本的log日志使用方法。
首先添加头文件,使用到的头文件有:

#include 
#include 
#include 
#include 

添加一个函数:

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:");
    }

    QString context_info = QString("File:(%1) Line:(%2)").arg(QString(context.file)).arg(context.line);
    QString current_date_time = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss ddd");
    QString current_date = QString("(%1)").arg(current_date_time);
    QString message = QString("%1 %2 %3 %4").arg(text).arg(context_info).arg(msg).arg(current_date);

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

在main函数中注册qInstallMessageHandler:

qInstallMessageHandler(outputMessage);

下面打印log日志:

//打印日志到文件中
qDebug("This is a debug message");			//	qDebug:调试信息
qWarning("This is a warning message");		//	qWarning:警告信息
qCritical("This is a critical message");	//	qCritical:严重错误
qFatal("This is a fatal message");			//	qFatal:致命错误(会报错,然后准备退出)

// 或者想平常一样
qDebug() << "****"; 也可以正常使用日志系统

debug模式下可以正常打印文件位置,到了release打印不了,需要在pro文件中添加下面这句话:

DEFINES += QT_MESSAGELOGCONTEXT

你可能感兴趣的:(QT)