281
|
1 #!/usr/bin/python
|
|
2
|
|
3 import sys
|
|
4 import os
|
|
5 import logging
|
|
6 import datetime
|
|
7
|
333
|
8 from qtwrapper import QtGui, QtCore, QtWidgets, Qt
|
281
|
9
|
|
10 def formatTime(t):
|
|
11 t2 = datetime.datetime.fromtimestamp(t)
|
|
12 return t2.strftime('%H:%M:%S')
|
|
13
|
333
|
14
|
|
15 class LogModel(QtCore.QAbstractTableModel):
|
281
|
16 def __init__(self):
|
|
17 super().__init__()
|
|
18 self.entries = []
|
|
19 self.headers = ['Time', 'Level', 'Logger', 'Message']
|
|
20 self.txts = []
|
|
21 self.txts.append(lambda e: str(formatTime(e.created)))
|
|
22 self.txts.append(lambda e: str(e.levelname))
|
|
23 self.txts.append(lambda e: str(e.name))
|
|
24 self.txts.append(lambda e: str(e.msg))
|
|
25
|
|
26 def rowCount(self, parent):
|
|
27 return len(self.entries)
|
333
|
28
|
281
|
29 def columnCount(self, parent):
|
|
30 return len(self.headers)
|
|
31
|
|
32 def data(self, index, role):
|
|
33 if not index.isValid():
|
|
34 return
|
|
35 row, col = index.row(), index.column()
|
|
36 if role == Qt.DisplayRole:
|
|
37 le = self.entries[row]
|
|
38 return self.txts[col](le)
|
|
39
|
|
40 def headerData(self, section, orientation, role):
|
|
41 if orientation == Qt.Horizontal and role == Qt.DisplayRole:
|
|
42 return self.headers[section]
|
333
|
43
|
281
|
44 def newLog(self, x):
|
|
45 self.entries.append(x)
|
|
46 self.modelReset.emit()
|
|
47
|
|
48
|
333
|
49 class LogView(QtWidgets.QWidget):
|
281
|
50 """ Log view component """
|
|
51 def __init__(self, parent=None):
|
|
52 super().__init__(parent)
|
333
|
53 l = QtWidgets.QVBoxLayout(self)
|
|
54 self.tv = QtWidgets.QTableView(self)
|
281
|
55 self.tv.horizontalHeader().setStretchLastSection(True)
|
|
56 l.addWidget(self.tv)
|
|
57 self.lm = LogModel()
|
|
58 self.tv.setModel(self.lm)
|
333
|
59
|
281
|
60 class MyHandler(logging.Handler):
|
|
61 def emit(self2, x):
|
|
62 self.lm.newLog(x)
|
|
63 self.tv.scrollToBottom()
|
|
64 for i in range(3):
|
|
65 self.tv.resizeColumnToContents(i)
|
|
66
|
|
67 logging.getLogger().addHandler(MyHandler())
|
|
68
|
|
69
|
|
70 if __name__ == '__main__':
|
|
71 app = QApplication(sys.argv)
|
|
72 lv = LogView()
|
|
73 lv.show()
|
|
74 lv.resize(600, 200)
|
|
75 logging.error('Error!!!')
|
|
76 logging.warn('Warn here!')
|
|
77 app.exec_()
|
|
78
|