Qt巧用qInstallMessageHandler实现日志输出,简单方便高效。无需引用第三方日志库。

#include "StdAfx.h"
#include <QTextCodec>
#include <QMutex>
#include <QMutexLocker>

void VMSMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg);

int main(int argc, char *argv[])
{
    QtSingleApplication app(QLatin1String("1e260578-2661-a7f5-ab16-1476eba2bf6f"),argc, argv);

    QDir().mkpath("log");
    qInstallMessageHandler(VMSMessageOutput);

    ......;

    return app.exec();
}


void VMSMessageOutput(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    QMutexLocker iLocker(&mutex);

    QString strLogLevel;
    switch (type) {
    case QtDebugMsg:
        strLogLevel = "Debug";
        break;
    case QtWarningMsg:
        strLogLevel = "Warning";
        break;
    case QtCriticalMsg:
        strLogLevel = "Critical";
        break;
    case QtFatalMsg:
        //abort();
        strLogLevel = "Fatal";
        break;
    default:
        break;
    }
    int nLogLevel = QtWarningMsg;
    int nYear = 1;
    int nMonth = 1;
    int nDay = 1;

    QDate iCurrentDate = QDate::currentDate();
    QString strFile = QString("log/%1.log").arg(iCurrentDate.toString("yyyy-MM-dd"));

    QDate iOld = iCurrentDate.addDays(1);
    iOld = iOld.addYears(-nYear);
    iOld = iOld.addMonths(-nMonth);
    iOld = iOld.addDays(-nDay);
    QString strFileOld = QString("log/%1.log").arg(iOld.toString("yyyy-MM-dd"));
    QFile::remove(strFileOld);

    QString strMsg;
    if (type >= nLogLevel)
    {
        QString strL = QString(QTextCodec::codecForLocale()->toUnicode(msg.toLocal8Bit()));

        QFile file(strFile);
        file.open(QIODevice::WriteOnly | QIODevice::Append);
        QTextStream iStream(&file);
        strMsg = QString("%1 %2 File:%3 Function:%4 Line:%5\n%6\n")
            .arg(QDateTime::currentDateTime().toString("hh:mm:ss.zzz"))
            .arg(strLogLevel)
            .arg(context.file)
            .arg(context.function)
            .arg(context.line)
            .arg(QString(msg.toLocal8Bit()))
            ;
        iStream << strMsg.toLocal8Bit() << "\r\n";
        file.flush();
#if defined(Q_OS_ANDROID)
        int fd = file.handle();
        fsync(fd);
#endif
        file.close();
    }

    QByteArray baOut = strMsg.toLocal8Bit();
    //fprintf(stdout, baOut.data());
    OutputDebugStringA(strMsg.toLocal8Bit());
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值