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()andappendPlainText()turnsQPlainTextEditinto 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 withappendHtml(). WhileQPlainTextEditdoes 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】)。
参考:
来源:oschina
链接:https://my.oschina.net/u/274521/blog/353590