Refactor logging setup across multiple modules to use loguru with consistent configuration

- Updated logging initialization in MessageCalendar, admin_edit_prof, elsa_main, graph, iconLine, searchPage, and richtext modules to use loguru.
- Changed log rotation and retention settings for log files to improve log management.
- Replaced logger.debug/info calls with log.debug/info for consistency.
- Fixed a typo in the searchPage UI and updated related references in the UI files.
- Removed unused imports and cleaned up code for better readability.
This commit is contained in:
2025-05-13 15:49:52 +02:00
parent 4a3a95623a
commit f7c499ea6e
32 changed files with 412 additions and 491 deletions

View File

@@ -32,15 +32,15 @@ from src.logic import (
)
from src.ui.dialogs import (
popus_confirm,
medienadder_ui,
MedienAdder,
About,
ApparatExtendDialog,
Mail_Dialog,
Settings,
edit_bookdata_ui,
login_ui,
parsed_titles_ui,
reminder_ui,
BookDataUI,
LoginDialog,
ParsedTitles,
ReminderDialog,
DocumentPrintDialog,
)
from src.ui.widgets import (
@@ -55,28 +55,27 @@ from src.ui.widgets import (
)
from datetime import datetime
from loguru import logger as log
logger = log
logger.remove()
logger.add("logs/application.log", rotation="1 week", enqueue=True)
import loguru
log = loguru.logger
log.remove()
log.add(sys.stdout)
log.add("logs/application.log", rotation="1 MB", retention="10 days")
log.add(
f"logs/{datetime.now().strftime('%Y-%m-%d')}.log",
rotation="1 day",
compression="zip",
retention="1 month",
)
# logger.add(sys.stderr, format="{time} {level} {message}", level="INFO")
logger.add(sys.stdout)
valid_input = (0, 0, 0, 0, 0, 0)
class Ui(Ui_Semesterapparat):
# use the Ui_MainWindow class from mainwindow.py
def __init__(self, MainWindow, username: str) -> None: # type:ignore
logger.info("Starting Semesterapparatsmanagement")
log.info("Starting Semesterapparatsmanagement")
super().__init__()
self.active_user = username
self.setupUi(MainWindow) # type:ignore
@@ -116,7 +115,6 @@ class Ui(Ui_Semesterapparat):
self.tableWidget_apparate.horizontalHeader().setSectionResizeMode( # type:ignore
QtWidgets.QHeaderView.ResizeMode.Stretch
)
self.tableWidget_apparate.setSortingEnabled(True)
self.saveandcreate.hide()
# Actions
@@ -142,7 +140,7 @@ class Ui(Ui_Semesterapparat):
self.prof_tel_nr.setValidator(
QtGui.QRegularExpressionValidator(QtCore.QRegularExpression(r"^\d{3,14}"))
)
# #logger.debug(self.prof_tel_nr.maxLength())
# #log.debug(self.prof_tel_nr.maxLength())
self.app_fach.setValidator( # validator to allow typing in the app_fach field
QtGui.QRegularExpressionValidator(
QtCore.QRegularExpression(r"[a-zA-Z0-9\s\W]+")
@@ -160,7 +158,7 @@ class Ui(Ui_Semesterapparat):
)
self.tableWidget_apparate.doubleClicked.connect(self.load_app_data) # type:ignore
# #logger.debug(f"user:{self.active_user}")
# #log.debug(f"user:{self.active_user}")
userrole = self.db.getRole(self.active_user)
# hide admin interface when non-admin is logged in
if userrole == "admin":
@@ -239,7 +237,7 @@ class Ui(Ui_Semesterapparat):
self.admin_action.setTitle("")
# Create instances to be used by the threads in the application
self.bookGrabber = []
self.bookGrabber: list[QThread] = []
self.availChecker = None
self.mail_thread = None
self.autoGrabber = None
@@ -260,7 +258,7 @@ class Ui(Ui_Semesterapparat):
self.valid_check_semester.clicked.connect(self.display_valid_semester) # type:ignore
def create_doc(self):
logger.debug("Creating document")
log.debug("Creating document")
# open DocumentPrintDialog
dialog = DocumentPrintDialog(self.MainWindow)
dialog.show()
@@ -332,7 +330,7 @@ class Ui(Ui_Semesterapparat):
self.app_fach.addItems([subject[1] for subject in self.db.getSubjects()])
def open_documentation(self):
logger.info("Opening Documentation")
log.info("Opening Documentation")
if not self.docu.isRunning():
self.docu.start()
webbrowser.open("http://localhost:8000")
@@ -357,7 +355,7 @@ class Ui(Ui_Semesterapparat):
statistics.updateCalendar.connect(self.update_calendar)
stats_layout.addWidget(statistics)
# #logger.debug("searchpage")
# #log.debug("searchpage")
if self.tabWidget.currentIndex() == 0: # Apparate
# clear all entries from the table
self.tableWidget_apparate.setRowCount(0)
@@ -375,7 +373,7 @@ class Ui(Ui_Semesterapparat):
widget.deleteLater()
elsa_layout.addWidget(ElsaDialog())
# logger.debug("added")
# log.debug("added")
pass
def generateSemester(self, today=False):
@@ -418,9 +416,9 @@ class Ui(Ui_Semesterapparat):
self.prof_mail.setText(appdata.prof.mail)
self.prof_tel_nr.setText(appdata.prof.telnr)
self.app_name.setText(appdata.apparat.name)
# #logger.debug("changing dropdown app_fach from '' to ", appdata.app_fach)
# #log.debug("changing dropdown app_fach from '' to ", appdata.app_fach)
self.app_fach.setCurrentText(appdata.apparat.subject)
# #logger.debug("changed dropdown app_fach to ", self.app_fach.currentText())
# #log.debug("changed dropdown app_fach to ", self.app_fach.currentText())
self.sem_year.setText(appdata.apparat.get_semester.split(" ")[1])
match appdata.apparat.get_semester.split(" ")[0]:
case "SoSe":
@@ -485,7 +483,7 @@ class Ui(Ui_Semesterapparat):
return popup.result()
def thread_check(self):
# #logger.debug("Thread started")
# #log.debug("Thread started")
self.prof_mail.textChanged.connect(self.validate_prof_mail)
self.drpdwn_prof_name.editTextChanged.connect(self.validate_prof_name)
self.prof_tel_nr.textChanged.connect(self.validate_prof_tel)
@@ -596,7 +594,7 @@ class Ui(Ui_Semesterapparat):
return
selected_prof = self.drpdwn_prof_name.currentText()
data = self.db.getProfData(selected_prof)
# logger.debug(data)
# log.debug(data)
prof_title = data.title
if prof_title == "None":
prof_title = "Kein Titel"
@@ -700,20 +698,20 @@ class Ui(Ui_Semesterapparat):
def update_progress_label(self, curr: int, total: int):
text = f"Medium {curr}/{total}"
logger.info(text)
log.info(text)
self.progress_label.setText(text)
# update tableWidget_apparat_media
self.update_app_media_list()
def hide_progress_label(self):
logger.info("Finished adding media, hiding progress label")
log.info("Finished adding media, hiding progress label")
self.progress_label.hide()
self.progress_label.setText("Bitte warten...")
self.line_2.hide()
self.label_info.hide()
def btn_add_medium(self):
media = medienadder_ui()
media = MedienAdder()
media.exec()
mode = media.mode
data = media.data
@@ -733,7 +731,7 @@ class Ui(Ui_Semesterapparat):
app_id = self.active_apparat
prof_id = self.db.getProfId(self.profdata)
logger.debug(prof_id)
log.debug(prof_id)
# check if app_id is in database
if self.db.checkApparatExistsById(app_id) is False:
# create apparat
@@ -756,7 +754,7 @@ class Ui(Ui_Semesterapparat):
bookGrabber.start()
while bookGrabber.isRunning():
# #logger.debug("waiting for thread to finish")
# #log.debug("waiting for thread to finish")
QtWidgets.QApplication.processEvents()
# self.__clear_fields()
@@ -802,7 +800,7 @@ class Ui(Ui_Semesterapparat):
# thread = QThread()
appnumber = self.active_apparat
# #logger.debug(links)
# #log.debug(links)
self.availChecker = AvailChecker(links, appnumber, books=books)
# availcheck.moveToThread(thread)
# availcheck.finished.connect(thread.quit)
@@ -851,7 +849,7 @@ class Ui(Ui_Semesterapparat):
app_id, prof_id, deleted
)
# # #logger.debug(books)
# # #log.debug(books)
# take the dataclass from the tuple
# booklist:list[BookData]=[book[0] for book in books]
self.tableWidget_apparat_media.setRowCount(0)
@@ -860,7 +858,7 @@ class Ui(Ui_Semesterapparat):
book_data = book["bookdata"]
availability = book["available"]
# bd = BookData().from_string(book)
# # #logger.debug(bd, type(bd))
# # #log.debug(bd, type(bd))
# create a new row below the last one
self.tableWidget_apparat_media.insertRow(
self.tableWidget_apparat_media.rowCount()
@@ -954,11 +952,11 @@ class Ui(Ui_Semesterapparat):
self.drpdwn_prof_name.addItem(prof)
def add_document(self):
# #logger.debug("Add document")
# #log.debug("Add document")
picker = FilePicker()
files = picker.pick_files()
for file in files:
# #logger.debug(file)
# #log.debug(file)
filename = file.split("/")[-1]
filetype = filename.split(".")[-1]
self.document_list.insertRow(0)
@@ -1008,7 +1006,7 @@ class Ui(Ui_Semesterapparat):
def __open_dialog(signatures: list[str]):
dialog = QtWidgets.QDialog()
frame = parsed_titles_ui()
frame = ParsedTitles()
frame.setupUi(dialog)
dialog.show()
frame.signatures = signatures
@@ -1030,7 +1028,7 @@ class Ui(Ui_Semesterapparat):
else:
# if file is selected, check for books in the file
if self.document_list.currentRow() != -1:
# #logger.debug("File selected")
# #log.debug("File selected")
file = self.document_list.item(
self.document_list.currentRow(), 3
).text()
@@ -1084,7 +1082,7 @@ class Ui(Ui_Semesterapparat):
bookdata=book, app_id=app_id, prof_id=prof_id
)
self.update_app_media_list()
# #logger.debug(len(signatures))
# #log.debug(len(signatures))
def extract_document_data(self) -> Union[list[str], SemapDocument]:
file_type = self.document_list.item(self.document_list.currentRow(), 1).text()
@@ -1093,7 +1091,7 @@ class Ui(Ui_Semesterapparat):
).text()
file_name = self.document_list.item(self.document_list.currentRow(), 0).text()
file = file_location
logger.info("File selected: {}, {}", file_name, file_location)
log.info("File selected: {}, {}", file_name, file_location)
if file_location == "Database":
# create warning, then return
self.db.recreateFile(file_name, self.active_apparat, filetype=file_type)
@@ -1107,8 +1105,8 @@ class Ui(Ui_Semesterapparat):
return signatures
if file_type == "docx":
data = word_to_semap(file)
logger.info("Converted data from semap file")
logger.debug("Got the data: {}", data)
log.info("Converted data from semap file")
log.debug("Got the data: {}", data)
return data
@@ -1132,17 +1130,17 @@ class Ui(Ui_Semesterapparat):
for runner in self.bookGrabber:
if not runner.isRunning():
runner.deleteLater()
# #logger.debug("Checking file")
# #log.debug("Checking file")
# get active app_id and prof_id
self.tableWidget_apparate.setEnabled(False)
self.tableWidget_apparate.setToolTip(
"Bitte warten, bis alle Medien hinzugefügt wurden"
)
app_id = self.active_apparat
logger.debug(self.profdata)
log.debug(self.profdata)
prof_id = self.db.getProfId(self.profdata)
logger.debug("Prof id: {}", prof_id)
log.debug("Prof id: {}", prof_id)
# check if apparat in database
if prof_id is None:
prof = Prof(
@@ -1155,28 +1153,28 @@ class Ui(Ui_Semesterapparat):
self.db.createProf(prof)
# if app_id not in database, create apparat
if not self.db.checkApparatExistsById(app_id):
logger.info("Apparat does not exist, creating new apparat")
log.info("Apparat does not exist, creating new apparat")
# create apparat
# #logger.debug("Creating apparat")
# #log.debug("Creating apparat")
if not self.btn_save_apparat(False):
return
if self.document_list.rowCount() == 0:
logger.info("No file selected")
log.info("No file selected")
self.tableWidget_apparate.setEnabled(True)
self.tableWidget_apparate.setToolTip("")
return
else:
# if file is selected, check for books in the file
# #logger.debug("File selected")
# #log.debug("File selected")
if prof_id is None:
prof_id = self.db.getProfId(self.profdata)
# logger.debug("Prof ID is None", prof_id)
# log.debug("Prof ID is None", prof_id)
document = self.extract_document_data()
if document is None:
logger.error("Document is None")
log.error("Document is None")
elif isinstance(document, SemapDocument):
signatures = document.signatures
else:
@@ -1287,7 +1285,7 @@ class Ui(Ui_Semesterapparat):
pid=appd.prof.fullname,
)
if clear_fields:
# #logger.debug("clearing fields")
# #log.debug("clearing fields")
self.__clear_fields()
return True
@@ -1346,10 +1344,10 @@ class Ui(Ui_Semesterapparat):
for apparat in self.apparats:
self.insert_apparat_into_table(apparat)
logger.info("Inserted {} apparats into table".format(len(self.apparats)))
log.info("Inserted {} apparats into table".format(len(self.apparats)))
def insert_apparat_into_table(self, apparat):
# logger.debug(apparat)
# log.debug(apparat)
def __dauer_check(apparat):
return "Ja" if apparat[7] == 1 else "Nein"
@@ -1398,7 +1396,7 @@ class Ui(Ui_Semesterapparat):
return
app_id = self.tableWidget_apparate.item(row, 0).text()
pid = self.db.getProfIDByApparat(app_id)
logger.debug(app_id, pid)
log.debug(app_id, pid)
delete_action.triggered.connect(lambda: self.delete_apparat(pos))
# pass pos to contact_prof
contact_action.triggered.connect(
@@ -1407,14 +1405,14 @@ class Ui(Ui_Semesterapparat):
menu.exec(self.tableWidget_apparate.mapToGlobal(position))
def reminder(self):
logger.info("Opening reminder dialog")
reminder = reminder_ui()
log.info("Opening reminder dialog")
reminder = ReminderDialog()
reminder.exec()
tableposition = self.tableWidget_apparate.currentRow()
appnr = self.tableWidget_apparate.item(tableposition, 0).text()
if reminder.result() == QtWidgets.QDialog.DialogCode.Accepted:
data = reminder.return_message()
# #logger.debug(data)
# #log.debug(data)
self.db.addMessage(
data,
self.active_user,
@@ -1423,18 +1421,18 @@ class Ui(Ui_Semesterapparat):
self.update_calendar(data)
# self.db.update_bookdata(data, book_id)
# self.db.update_bookdata(data)
logger.info("committed message to database")
log.info("committed message to database")
# self.update_app_media_list()
def get_reminders(self):
messages = self.db.getAllMessages()
logger.info(f"Got {len(messages)} messages from database")
log.info(f"Got {len(messages)} messages from database")
self.calendarWidget.setMessages(messages)
self.calendarWidget.updateCells()
def open_reminder(self):
selected_date = self.calendarWidget.selectedDate().toString("yyyy-MM-dd")
# # #logger.debug(selected_date)
# # #log.debug(selected_date)
messages = self.db.getMessages(selected_date)
if messages == []:
return
@@ -1445,13 +1443,13 @@ class Ui(Ui_Semesterapparat):
dialog.repaintSignal.connect(lambda: self.calendarWidget.reload(selected_date))
def open_settings(self):
# logger.debug(settings.dict())
# log.debug(settings.dict())
settingsUI = Settings(self.active_user)
settingsUI.exec()
if settingsUI.result() == QtWidgets.QDialog.DialogCode.Accepted:
settingsUI.save()
# logger.debug(settings.dict())
# log.debug(settings.dict())
# self.reload()
@@ -1470,6 +1468,7 @@ class Ui(Ui_Semesterapparat):
delete_action = QtGui.QAction("Löschen")
edit_action = QtGui.QAction("Bearbeiten")
update_data_action = QtGui.QAction("Daten aktualisieren")
apparat_add_action = QtGui.QAction("Zum Apparat hinzufügen")
apparat_move_action = QtGui.QAction("In Apparat verschieben")
apparat_copy_action = QtGui.QAction("In Apparat kopieren")
@@ -1479,7 +1478,7 @@ class Ui(Ui_Semesterapparat):
apparatmenu.addActions(
[apparat_add_action, apparat_copy_action, apparat_move_action]
)
generalmenu.addActions([edit_action, delete_action])
generalmenu.addActions([edit_action, delete_action, update_data_action])
# disable apparat_add_action
apparat_add_action.setEnabled(False)
delete_action.triggered.connect(self.delete_medium)
@@ -1487,8 +1486,13 @@ class Ui(Ui_Semesterapparat):
apparat_add_action.triggered.connect(self.add_to_apparat)
apparat_copy_action.triggered.connect(self.copy_to_apparat)
apparat_move_action.triggered.connect(self.move_to_apparat)
update_data_action.triggered.connect(self.update_data)
menu.exec(self.tableWidget_apparat_media.mapToGlobal(position))
def update_data(self):
# TODO: use link in table, parse data and if needed, update location / signature
pass
def copy_to_apparat(self):
selected_rows = self.tableWidget_apparat_media.selectionModel().selectedRows()
signatures = []
@@ -1577,7 +1581,7 @@ class Ui(Ui_Semesterapparat):
signature=signature,
prof_id=self.db.getProfId(self.profdata),
)
# logger.debug(medium.adis_idn, medium.signature)
# log.debug(medium.adis_idn, medium.signature)
def edit_medium(self):
book = self.tableWidget_apparat_media.item(
@@ -1595,7 +1599,7 @@ class Ui(Ui_Semesterapparat):
book,
)
widget = QtWidgets.QDialog()
bookedit = edit_bookdata_ui()
bookedit = BookDataUI()
bookedit.setupUi(widget)
widget.setWindowIcon(Icon("settings").icon)
# change title of dialog
@@ -1604,10 +1608,10 @@ class Ui(Ui_Semesterapparat):
widget.exec()
if widget.result() == QtWidgets.QDialog.DialogCode.Accepted:
data = bookedit.get_data()
# #logger.debug(data)
# #log.debug(data)
self.db.updateBookdata(bookdata=data, book_id=book_id)
# self.db.update_bookdata(data)
# #logger.debug("accepted")
# #log.debug("accepted")
self.update_app_media_list()
else:
return
@@ -1631,7 +1635,7 @@ class Ui(Ui_Semesterapparat):
)
message = f'Soll das Medium "{self.tableWidget_apparat_media.item(self.tableWidget_apparat_media.currentRow(), 0).text()}" wirklich gelöscht werden?'
state = self.confirm_popup(message, title="Löschen?")
# #logger.debug(state)
# #log.debug(state)
if state == 1:
self.db.deleteBook(book_id)
self.update_app_media_list()
@@ -1643,7 +1647,7 @@ class Ui(Ui_Semesterapparat):
for r in ranges:
for row in range(r.topRow(), r.bottomRow() + 1):
rows.append(row)
# #logger.debug(rows)
# #log.debug(rows)
message = f"Sollen die {len(rows)} Medien wirklich gelöscht werden?"
state = self.confirm_popup(message, title="Löschen?")
if state == 1:
@@ -1663,12 +1667,12 @@ class Ui(Ui_Semesterapparat):
# return data from dialog if ok is pressed
if framework.result() == QtWidgets.QDialog.DialogCode.Accepted:
data = framework.get_data()
# #logger.debug(data)
# #log.debug(data)
# return data
selected_apparat_id = self.tableWidget_apparate.item(
self.tableWidget_apparate.currentRow(), 0
).text()
# #logger.debug(selected_apparat_id)
# #log.debug(selected_apparat_id)
self.db.setNewSemesterDate(
selected_apparat_id, data["semester"], dauerapp=data["dauerapp"]
@@ -1679,7 +1683,7 @@ class Ui(Ui_Semesterapparat):
return
def __contact_dialog(self, apparat, location: tuple | str, mail=None, pid=""):
logger.debug(
log.debug(
"Got these values apparat: {}, location: {}, mail: {}, pid: {}".format(
apparat, location, mail, pid
)
@@ -1722,8 +1726,8 @@ class Ui(Ui_Semesterapparat):
self.mail_thread.show()
def contact_prof(self, apparat="", location="", mail="", pid=""):
logger.debug(apparat)
logger.debug(location)
log.debug(apparat)
log.debug(location)
if self.active_apparat == "":
if apparat is False:
self.confirm_popup(
@@ -1739,10 +1743,10 @@ class Ui(Ui_Semesterapparat):
).text()
message = f"Soll der Apparat {selected_apparat_id} wirklich gelöscht werden?"
state = self.confirm_popup(message, title="Löschen?")
# #logger.debug(state)
logger.info("Result state: {}", state)
# #log.debug(state)
log.info("Result state: {}", state)
if state == 1:
logger.debug("Deleting apparat {}", selected_apparat_id)
log.debug("Deleting apparat {}", selected_apparat_id)
pid = self.db.getProfIDByApparat(selected_apparat_id)
self.db.deleteApparat(selected_apparat_id, Semester().value)
# delete the corresponding entry from self.apparats
@@ -1751,7 +1755,7 @@ class Ui(Ui_Semesterapparat):
self.apparats.remove(apparat)
break
self.old_apparats = self.apparats
# #logger.debug(self.apparats)
# #log.debug(self.apparats)
# remove the row from the table
self.tableWidget_apparate.removeRow(self.tableWidget_apparate.currentRow())
# send mail to prof
@@ -1759,24 +1763,24 @@ class Ui(Ui_Semesterapparat):
def launch_gui():
# #logger.debug("trying to login")
# #logger.debug("checking if database available")
# #log.debug("trying to login")
# #log.debug("checking if database available")
logger.info("Starting login dialog")
log.info("Starting login dialog")
app = QtWidgets.QApplication(sys.argv)
login_dialog = QtWidgets.QDialog()
ui = login_ui()
ui = LoginDialog()
ui.setupUi(login_dialog)
login_dialog.exec() # This will block until the dialog is closed
if ui.lresult == 1:
# if login is successful, open main window
# show login dialog
# #logger.debug(ui.lusername)
# #log.debug(ui.lusername)
MainWindow = QtWidgets.QMainWindow()
aui = Ui(MainWindow, username=ui.lusername)
# #logger.debug(aui.active_user)
# #log.debug(aui.active_user)
MainWindow.show()
# atexit.register()
atexit.register(tempdelete)
@@ -1793,7 +1797,7 @@ def launch_gui():
if __name__ == "__main__":
# #logger.debug("This is the main window")
# #log.debug("This is the main window")
# app = QtWidgets.QApplication(sys.argv)
# window = MainWindow()
# app.exec()