Qt 实现 Logger 日志的显示

来源:互联网 发布:apache jmeter 3.2 编辑:程序博客网 时间:2024/06/15 11:20
来源:http://my.oschina.net/gongshang/blog/353590
摘要
日志一般是程序员自己看,即使程序中需要用控件显示,要求一般也不太高。 但需要能够控制显示的总共行数,能够备份至文件。这里记录写网上搜集整理的资料和个人的经验。

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 ofsetMaximumBlockCount() and appendPlainText() turns QPlainTextEdit into an efficient viewer for log text. The scrolling can be reduced with thecenterOnScroll() 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(). WhileQPlainTextEdit 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】)。


参考:

  • StackOverflow
  • Logging In Qt
0 0