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