关闭qdebug,Qt5:如何使用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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值