Qt--日志

Qt提供了qDebug、qWarning、qCritical、qFatal、qInfo等不同类别的日志记录函数

qlogging.h中声明了一个日志处理函数

typedef void (*QtMessageHandler)(QtMsgType, const QMessageLogContext &, const QString &);

通过qInstallMessageHandler可以安装自己的日志处理器

QtMessageHandler qInstallMessageHandler(QtMessageHandler);

默认的日志处理器是将msg输出到stderr标准错误,如果我们想记录到日志文件中,可以参考下面代码示例:

#include <QDateTime>
void myLogHandler(QtMsgType type, const QMessageLogContext & ctx, const QString & msg){
    char szType[16];
    switch (type) {
    case QtDebugMsg:
        strcpy(szType, "Debug");
        break;
    case QtInfoMsg:
        strcpy(szType, "Info");
        break;
    case QtWarningMsg:
        strcpy(szType, "Warning");
        break;
    case QtCriticalMsg:
        strcpy(szType, "Critical");
        break;
    case QtFatalMsg:
        strcpy(szType, "Fatal");
    }

    QString strLog = QString::asprintf("[%s] [%s]:%s [%s:%d - %s]\n",
                                       QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz").toLocal8Bit().data(),
                                       szType,
                                       msg.toUtf8().data(),
                                       ctx.file,ctx.line,ctx.function);

    QString strLogFilePath = QCoreApplication::applicationDirPath() + "/" +
            QCoreApplication::applicationName() + ".log";

    FILE* fp = fopen(strLogFilePath.toLocal8Bit().data(), "a");
    if (fp){
        fseek(fp, 0, SEEK_END);
        if (ftell(fp) > (2 << 20)){
            fclose(fp);
            fp = fopen(strLogFilePath.toLocal8Bit().data(), "w");
        }
    }

    if (fp){
        fputs(strLog.toLocal8Bit().data(), fp);
        fclose(fp);
    }
}

#include <QApplication>
#include <QLabel>
#include <QDebug>
int main(int argc,char* argv[]){
    QApplication app(argc, argv);

    qInstallMessageHandler(myLogHandler);

    qDebug("app start!");

    QLabel label("开启Qt学习之旅");
    QFont font = label.font();
    font.setPixelSize(48);
    label.setFont(font);
    label.setAlignment(Qt::AlignCenter);
    label.setStyleSheet("background-color: black; color: green;");
    label.setGeometry(200,200,400,300);
    label.show();

    qDebug() << label.text();
    qDebug() << label.geometry();

    app.exec();

    qDebug("app end!");
}

appname.log文件中打印如下:

[2017-11-25 17:59:54.245] [Debug]:app start! [..\core01\main.cpp:66 - int main(int, char**)]
[2017-11-25 17:59:54.298] [Debug]:"开启Qt学习之旅" [..\core01\main.cpp:77 - int main(int, char**)]
[2017-11-25 17:59:54.298] [Debug]:QRect(200,200 400x300) [..\core01\main.cpp:78 - int main(int, char**)]
[2017-11-25 17:59:55.788] [Debug]:app end! [..\core01\main.cpp:82 - int main(int, char**)]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ithewei

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

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

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

打赏作者

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

抵扣说明:

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

余额充值