Qt输出日志文件

Qt输出日志文件

void log(QtMsgType type, const QMessageLogContext &context, const QString &msg)
{
    static QMutex mutex;
    mutex.lock();

    QString msgStr;
    switch (type) {
    case QtDebugMsg:
        msgStr.append("Debug:").append(msg);
        break;
    case QtWarningMsg:
        msgStr.append("Warning:").append(msg);
        break;
    case QtCriticalMsg:
        msgStr.append("Critical:").append(msg);
        break;
    case QtFatalMsg:
        msgStr.append("Fatal:").append(msg);
        break;
    default:
        break;
    }

    QString s=QTime::currentTime().toString(Qt::ISODate).append(": ").append(msgStr);
    QString logNameStr=QString("log").append(QDate::currentDate().toString(Qt::ISODate)).append(".txt");

    QFile file(logNameStr);
    if(file.open(QIODevice::WriteOnly | QIODevice::Append))
    {
        QTextStream textStream(&file);
        textStream << s << endl;
        file.flush();
        file.close();
    }
    
    mutex.unlock();
}

int main(int argc, char *argv[])
{
     qInstallMessageHandler(log);

    QApplication a(argc, argv);

    for(int i=0;i<10;i++)
    {
        qDebug()<<"log text--"<

输出为


21:35:02: Debug:log text-- "21:35:02"
21:35:02: Debug:log text-- "21:35:02"
21:35:02: Debug:log text-- "21:35:02"
21:35:02: Debug:log text-- "21:35:02"
21:35:02: Debug:log text-- "21:35:02"


在这里 QtMessageHandler qInstallMessageHandler(QtMessageHandler handler) 是一个函数指针。


http://blog.csdn.net/taiyang1987912/article/details/41218435

借鉴了前辈的文章,就像前辈说的,完整的日志功能还需要添加日志清除、日志文件限制大小等功能。




你可能感兴趣的:(Qt)