Qt 实现 Logger 日志的显示

Qt qDebug or 开源库

基于 Qt qDebug

Qt 提供 qInstallMessageHandler(Qt5)或者qInstallMsgHandler(Qt4),可以对QDebug、QWarning、QError等进行重定向等处理。

可以参考Qt Assistant 的帮助文档,或者参考Qt之日志输出文件进行实现。

  • 缺点: 没有尝试过,但是有人不支持多线程,至少需要自己去考虑多线程安全问题
  • 缺点: 如果想要让消息既存档,又同时在窗口Widget中显示,可能会麻烦点
  • 需要自己实现文件大小的判断,以及历史文件的备份
  • 如果只是将日志重定向至某个文件,不需要显示,这方法挺好。推荐。

开源库

QsLog (个人推荐)

简单的日志框架,可以添加多个日志的destination,可以使用Signal/Slot机制方便的将日志输出到Widget。

项目地址:QsLog的Bitbucket地址

QxtLogger

QxtLib的一部分,如果也是用QxtLib的其他功能,肯定也会用这个。但是我没用过

项目地址:QxtLogger Class Reference

Widget 显示空间的选择

使用QPlainTextEdit (推荐)

If you want to limit the total number of paragraphs in a QPlainTextEdit, as it is for example useful in a log viewer, then you can use the maximumBlockCount property. The combination of setMaximumBlockCount() and appendPlainText() turns QPlainTextEdit into an efficient viewer for log text. The scrolling can be reduced with the centerOnScroll() property, making the log viewer even faster. Text can be formatted in a limited way, either using a syntax highlighter (see below), or by appending html-formatted text with appendHtml(). While QPlainTextEdit does not support complex rich text rendering with tables and floats, it does support limited paragraph-based formatting that you may need in a log viewer.

上一段引用来自Qt的帮助文档。组合 QPlainTextEdit 的 setMaximumBlockCount()appendPlainText() 方法,来实现logger的显示,可以控制总共显示的行数。

  • 优点是更轻量级
  • 可以利用HTML(<p><span>)进行简单的高亮/行背景色。
  • 缺点,进行筛选相对麻烦

使用 QListWidget 或者 QTableWidget

可以设置总行数来控制显示的日志数量。

  • 缺点,相对厚重了些
  • 优点,可以方便的用不同颜色高亮Error,Warning等。
  • 优点,可以方便的进行筛选,快速找到error等。

单例模式

如果基于qDebug自己造轮子,而且日志的显示窗口需要常开,建议使用单例模式(参考CSDN 或更直接的【CSDN】)。


参考:

转载于:https://my.oschina.net/gongshang/blog/353590

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值