Qt5:如何使用qDebug()登录文件,多线程应用程序 [英] Qt5: How to use qDebug() to log in a file, multi-thread application

查看:450
本文介绍了Qt5:如何使用qDebug()登录文件,多线程应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天前我开始使用Qt5.我的应用程序需要一个 logger ,因此我决定使用qDebug,但是为了将日志存储在文件中,似乎必须对其进行重定向".

I started using Qt5 few days ago. I needed a logger for my app and I decided to use qDebug, but it seems it has to be "redirected" in order to have the logs in a file.

我使用qInstallMessageHandler来做到这一点,并编写了如下所示的自己的处理程序(灵感来自此处的其他人).

I used qInstallMessageHandler to do that and I wrote my own handler as presented below (inspired from other people here).

似乎可行,但由于我不是专家,所以我不得不问: 可以在多线程应用程序中使用它吗?

It seems it works, but as I am not a guru, I have to ask: Is it ok to use this in a multi-thread application or not?

此外,如果可以在多线程应用程序中使用安全/安全,是否可以通过某种方式对其进行改进?

Also, if it is ok/safe for using in a multi-thread app, can it be improved somehow?

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

    QDateTime dateTime(QDateTime::currentDateTime());

    QString timeStr(dateTime.toString("dd-MM-yyyy HH:mm:ss:zzz"));
    QString contextString(QString("(%1, %2)").arg(context.file).arg(context.line));

    QFile outFile("file.log");
    outFile.open(QIODevice::WriteOnly | QIODevice::Append);

    QTextStream stream(&outFile);
    stream << timeStr << " " << contextString << ": " << msg << endl;

    mutex.unlock();
}

推荐答案

您的方法看起来简单而干净.我会那样保留.

Your approach looks simple and clean. I'd keep it like that.

您可以改进一件事:在应用程序启动时仅打开一次文件,在关闭应用程序时将其关闭.打开文件是一项昂贵的操作.

There is one thing you can improve: Open the file only once at application start and close it when you close the application. Opening a file is an expensive operation.

您可以从多个线程中写入同一打开文件,因为互斥锁可确保只有一个线程在同一时间写入.

You can write into the same open file from multiple threads, since your mutex ensures that only one thread writes at the same time.

这篇关于Qt5:如何使用qDebug()登录文件,多线程应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆