Qt打印日志

不使用第三方库,直接使用Qt实现日志打印,demo下载

#include "QtLog.h"
#include <QtWidgets/QApplication>
#include <QMutex>
#include <QFile>
#include <QDir>
#include <QDateTime>
#include <QCoreApplication>
#include <QApplication>

#define LOG_MAX_SIZE 5*1024*1024
#define LOG_DIR_NAME "mylog"

QString getLogPath()
{
    return QString("./%1").arg(LOG_DIR_NAME);
}

QString getLogFileName()
{
    return QString("%1/log%2.txt").arg(LOG_DIR_NAME).arg(QDateTime::currentDateTime().toString("yyyyMMddhhmmss"));
}

void myMessageOutput(QtMsgType type, const QMessageLogContext& context, const QString& msg)
{
    // 加锁
    static QMutex mutex;
    mutex.lock();

    QByteArray localMsg = msg.toUtf8();

    QString strMsg("");
    switch (type)
    {
    case QtDebugMsg:
        strMsg = QString("Debug");
        break;
    case QtWarningMsg:
        strMsg = QString("Warning");
        break;
    case QtCriticalMsg:
        strMsg = QString("Critical");
        break;
    case QtFatalMsg:
        strMsg = QString("Fatal");
        break;
    case QtInfoMsg:
        strMsg = QString("Info");
        break;
    default:
        return;
    }

    // 设置输出信息格式
    QString strDateTime = QDateTime::currentDateTime().toString("yy-MM-dd hh:mm:ss");
    QString strMessage = QString("%1 [%2] [%3:%4]   %5")
        .arg(strDateTime)
        .arg(strMsg)
        .arg(context.file)
        .arg(context.line)
        .arg(localMsg.constData());


    // 输出信息至文件中(读写、追加形式)
    // 使用 static 只需要
    static QFile file(getLogFileName());
    if (!file.isOpen()) {
        file.open(QIODevice::ReadWrite | QIODevice::Append);
    }
    if (file.size() > LOG_MAX_SIZE)
    {
        file.close();
        file.setFileName(getLogFileName());
        file.open(QIODevice::ReadWrite | QIODevice::Append);
    }

    QTextStream stream(&file);
    stream << strMessage << "\r\n";
    file.flush();

    // 取消 close
    //    file.close();

    // 解锁
    mutex.unlock();
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    //日志
    QDir dir;
    if (!dir.exists(getLogPath()))
    {
        dir.mkdir(getLogPath());
    }
    qInstallMessageHandler(myMessageOutput);
    qDebug() << "test debug log";
    qInfo() << "test info log";
    qWarning() << "test warning log";
    qCritical() << "test critical log";
    QtLog w;
    w.show();
    return a.exec();
}

Qt中将QString类型的日志记录到文件有多种方式,以下是几种常见的实现方法: ### 方法一:使用日志处理函数 可以通过注册日志处理函数,将所有Qt日志输出重定向到文件中。以下是示例代码: ```cpp #include <QApplication> #include <QDateTime> #include <QFile> #include <QTextStream> #include <iostream> void outputMessage(QtMsgType type, const QMessageLogContext &context, const QString &msg) { static QFile file("log.txt"); if (!file.isOpen()) { file.open(QIODevice::WriteOnly | QIODevice::Append); } QTextStream stream(&file); QString str; str += QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"); str += ": "; str += msg; str += "\r\n"; stream << str; } int main(int argc, char *argv[]) { qInstallMessageHandler(outputMessage); QApplication a(argc, argv); qDebug() << "This is a debug message"; return a.exec(); } ``` 在上述代码中,`outputMessage`函数是自定义的日志处理函数,通过`qInstallMessageHandler`注册该函数后,所有的Qt日志输出都会调用该函数进行处理,并将日志信息写入文件中。 ### 方法二:自定义日志记录函数 可以编写一个自定义的日志记录函数,在需要记录日志的地方调用该函数。示例代码如下: ```cpp #include <QFile> #include <QTextStream> #include <QDateTime> void log(const QString &fileName, const QString &message) { QFile file(fileName); file.open(QIODevice::WriteOnly | QIODevice::Append); if (!file.isOpen()) { return; } QTextStream stream(&file); QString str; str += QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"); str += ": "; str += message; str += "\r\n"; stream << str; file.close(); } // 使用示例 void someFunction() { QString logMessage = "This is a log message"; log("log.txt", logMessage); } ``` 在上述代码中,`log`函数接受文件名和日志信息作为参数,将日志信息添加时间戳后写入文件中。 ### 方法三:创建日志文件夹并记录日志 可以先检测日志文件夹是否存在,如果不存在则创建,然后将日志记录到该文件夹下的文件中。示例代码如下: ```cpp #include <QDir> #include <QFile> #include <QTextStream> #include <QDateTime> void logWithFolder(const QString &message) { QString filename = "log.txt"; QDir dir; if (!dir.exists("log")) { dir.mkdir("log"); } dir.cd("log"); QString path = dir.filePath(filename); QFile file(path); if (file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Append)) { QString str; str += QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz"); str += ": "; str += message; str += "\r\n"; file.write(str.toUtf8()); file.close(); } } // 使用示例 void anotherFunction() { QString logMessage = "This is another log message"; logWithFolder(logMessage); } ``` 在上述代码中,`logWithFolder`函数会先检查`log`文件夹是否存在,如果不存在则创建该文件夹,然后将日志信息写入该文件夹下的`log.txt`文件中。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码河漫步

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值