首页 > 代码库 > Qt 日志宏

Qt 日志宏

随便写了一个日志帮助的宏,既可以如同qDebug()一般在调试时输出信息,也可以在输出文本文件

#ifndef LOG_H#define LOG_H#include <QDir>#include <QFile>#include <QString>#include <QDebug>#include <QDate>#include <QTime>#include <QDateTime>#include <QTextStream>#define WRITE_LOG_FILE(type,msg)(\{QString err;    switch(type){        case QtDebugMsg:{err = "调试信息:";}break;        case QtWarningMsg:{err = "警告信息:";}break;        case QtCriticalMsg:{err = "严重错误:";}break;        case QtFatalMsg:{err = "致命错误:";}break;        default:{err = "常规信息:";}break;}    QString text = QString("%1\r\n 所在文件:%2 \r\n 所在位置:%3 \r\n 记录时间:%4 \r\n 记录信息:%5 \r\n").arg (err).arg (__FILE__).arg (__LINE__).arg (QDateTime::currentDateTime ().toString ("yyyy-MM-dd hh:mm:ss ddd")).arg (msg);qDebug() << text;    QDir dir;    QString path = dir.currentPath () + "\\log\\";    QDateTime dt = QDateTime::currentDateTime ();    QTime t = dt.time ();    QDate d = dt.date ();    QString name = QString("%1%2%3%4").arg (QString::number (d.year ())).arg (QString::number (d.month ())).arg (QString::number (d.day ())).arg (QString::number (t.hour ())) + QString(".txt");    QString filePath = path + name;    if(!dir.exists(path))    {        dir.mkpath(path);    }    QFile file(filePath);    if(!file.exists ())    {        file.open (QIODevice::WriteOnly);        file.close ();    }    if(file.open(QIODevice::WriteOnly | QIODevice::Append))    {        QTextStream stream(&file);        stream << text << "\r\n";        file.flush();file.close();    }})#define DEBUG_LOG(msg)(WRITE_LOG_FILE(QtDebugMsg,msg))#define WARNING_LOG(msg)(WRITE_LOG_FILE(QtWarningMsg,msg))#define CRITICAL_LOG(msg)(WRITE_LOG_FILE(QtCriticalMsg,msg))#define FATAL_LOG(msg)(WRITE_LOG_FILE(QtFatalMsg,msg))#define LOG(msg)(WRITE_LOG_FILE(-1,msg))#endif // LOG_H

 

Qt 日志宏