반응형

logging과 PyQt5를 사용하여 로그창을 구현한 예제입니다. 텍스트 파일에도 로그창에 보이는 내용이 따로 저장됩니다.
 



2022. 07. 21  최초작성

2022. 10. 30  한글 메시지 저장시 깨지는 현상 해결

2023. 06. 14  최종수정 - QTextEditLogger에 보여지는 로그 지우는 버튼 추가 



Test Me 버튼을 클릭하면 로그가 추가됩니다.

 

Clear 버튼을 클릭하면 QTextEditLogger에 보여지던 로그가 모두 지워집니다.



전체 소스코드입니다.

import sys
from PyQt5 import QtWidgets
import logging

date_strftime_format = "%d-%b-%y %H:%M:%S"
message_format = "%(asctime)s - %(levelname)s : %(message)s"
logging.basicConfig(filename='log.log', level=logging.INFO, format=message_format, datefmt=date_strftime_format, encoding='utf-8')

class QTextEditLogger(logging.Handler):
    def __init__(self, parent):
        super().__init__()
        self.widget = QtWidgets.QPlainTextEdit(parent)
        self.widget.setReadOnly(True)
        self.widget.setFixedHeight(150)
        self.widget.verticalScrollBar().setValue(
        self.widget.verticalScrollBar().maximum())

    def emit(self, record):
        msg = self.format(record)
        self.widget.appendPlainText(msg)
        self.widget.ensureCursorVisible()
        self.widget.viewport().update()
   
    def clear(self):
        self.widget.clear()


class MyDialog(QtWidgets.QDialog, QtWidgets.QPlainTextEdit):
    def __init__(self, parent=None):
        super().__init__(parent)

        self.logTextBox = QTextEditLogger(self)
        self.logTextBox.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        logging.getLogger().addHandler(self.logTextBox)
        logging.getLogger().setLevel(logging.DEBUG)

        self._button1 = QtWidgets.QPushButton(self)
        self._button1.setText('Test Me')

        self._button2 = QtWidgets.QPushButton(self)
        self._button2.setText('Clear')

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.logTextBox.widget)
        layout.addWidget(self._button1)
        layout.addWidget(self._button2)
        self.setLayout(layout)

        self._button1.clicked.connect(self.test)
        self._button2.clicked.connect(self.clear)

    def test(self):
        logging.debug('test 안녕')
   
    def clear(self):
        self.logTextBox.clear()
   

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    dlg = MyDialog()
    dlg.show()
    dlg.raise_()
    sys.exit(app.exec_())



원본 코드 

https://github.com/furkanhtk/Antenna-Measurement/blob/479217fddca529c1e98f2fbb69cc2fab1fccc3db/GUI/gui_log.py



반응형

문제 발생시 지나치지 마시고 댓글 남겨주시면 가능한 빨리 답장드립니다.

도움이 되셨다면 토스아이디로 후원해주세요.
https://toss.me/momo2024


제가 쓴 책도 한번 검토해보세요 ^^

+ Recent posts