Qt文件日志

来源:互联网 发布:淘宝在外国怎么样 编辑:程序博客网 时间:2024/04/29 06:22
#include <QString>
class CFileMessageHandler
{
public:
    CFileMessageHandler();
    ~CFileMessageHandler();
protected:
   static void myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);
   static QString getFileName();
private:
   QtMessageHandler m_holdMsgHandler;
};
#include <QDateTime>
#include <QFile>
#include <QTextStream>
#include <QApplication>
#include <QStandardPaths>
#include <QDir>
CFileMessageHandler::CFileMessageHandler()
{
    m_holdMsgHandler = qInstallMessageHandler(CFileMessageHandler::myMessageOutput);
}
CFileMessageHandler::~CFileMessageHandler()
{
    qInstallMessageHandler(0);
}
void CFileMessageHandler::myMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    QString filename = getFileName();
    QFile file(filename);
    if(file.open(QIODevice::Append))
    {
        QTextStream stream(&file);
        stream << msg;
    }
}
QString CFileMessageHandler::getFileName()
{
    QString path = QStandardPaths::writableLocation(QStandardPaths::DataLocation);
    path += "/log";
    QDir dir(path);
    if(!dir.exists())
    {
        dir.mkpath(path);
    }
    QDateTime datetime = QDateTime::currentDateTime();
    QString str = datetime.toString("yyyy_MM_dd");
    QString appName = QApplication::applicationDisplayName();
    path += "/" + appName + str + ".log";
    return path;
}
使用时,只需要在主函数QApplication a(argc, argv);之后定义一个CFileMessageHandler对象即可。
0 0