Skip to content

Commit

Permalink
Added comprehensive logging
Browse files Browse the repository at this point in the history
  • Loading branch information
Ahsoka committed Jul 16, 2021
1 parent 96a2aae commit 9f77128
Show file tree
Hide file tree
Showing 8 changed files with 194 additions and 22 deletions.
15 changes: 12 additions & 3 deletions beskar/__init__.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from sentry_sdk.integrations.logging import LoggingIntegration
from PyQt6.QtWidgets import QApplication
from .constants import __version__

import sys
import logging
import platform
import darkdetect
import sentry_sdk
Expand All @@ -14,13 +16,20 @@

sentry_sdk.set_context('os', sys_info)

def before_breadcrumbs(crumb, hint):
if crumb['message'] == 'The following error occured:':
return None
return crumb

sentry_sdk.init(
# NOTE: This URL is the testing URL, don't forget to change to production URL
'https://[email protected]/5867522',
traces_sample_rate=1.0,
environment='production' if getattr(sys, 'frozen', False) else 'development',
release=__version__,
default_integrations=False
integrations=(LoggingIntegration(logging.DEBUG, None),),
before_breadcrumb=before_breadcrumbs,
default_integrations=False,
traces_sample_rate=1.0,
release=__version__
)

from .gui import BeskarWindow
Expand Down
25 changes: 22 additions & 3 deletions beskar/__main__.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,48 @@
from sentry_sdk.utils import event_from_exception
from .settings import logging_dir
from .popups import ErrorPopup
from .logs import setUpLogger
from sentry_sdk import Hub
from . import app, window

import sys
import logging
import inspect
import traceback

def handle_exception(exc_type, exc_value, trace):
error_message = ''.join(traceback.format_exception(exc_type, exc_value, trace))
exc_tuple = (exc_type, exc_value, trace)
error_message = ''.join(traceback.format_exception(*exc_tuple))

popup = ErrorPopup(window, error_message)
popup.exec()

# Get logger for the file that is responsible for error
logger = logging.getLogger(inspect.getmodule(inspect.stack()[1].frame).__name__)
logger.critical('The following error occured:', exc_info=exc_tuple)

if popup.sending:
hub = Hub.current
if hub.client is not None:
hub.capture_event(*event_from_exception((exc_type, exc_value, trace)))
hub.capture_event(*event_from_exception(exc_tuple))
hub.flush()

sys.exit(error_message)
sys.exit(1)

def main():
window.show()
sys.exit(app.exec())

if __name__ == '__main__':
for logger_name in map(
lambda name: f'beskar.{name}',
('gui', 'pages', 'popups', 'settings', 'utils')
):
setUpLogger(
logger_name,
'%(levelname)s | %(name)s: [%(funcName)s()] %(message)s',
logging_dir
)

sys.excepthook = handle_exception
main()
32 changes: 19 additions & 13 deletions beskar/gui.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@
from .settings import Settings
from . import __version__

import logging

logger = logging.getLogger(__name__)


class BeskarWindow(QtWidgets.QMainWindow):
def __init__(self):
Expand Down Expand Up @@ -54,13 +58,16 @@ def __init__(self):
if num_of_devices > 1:
popup = MultipleSEALKitsPopup(self)
popup.open()
logger.info('Opened MultipleSEALKitPopup from BeskarWindow.')
elif num_of_devices == 0:
popup = NoSEALKitPopup(self)
popup.open()
logger.info('Opened NoSEALKitPopup from BeskarWindow.')
elif num_of_devices == 1:
self.device_name = system.devices.device_names[0]
apply_voltage(self.device_name)
self.enter_volts_popup.open()
logger.info('Opened EnterVoltsPopup from BeskarWindow.')

QtCore.QMetaObject.connectSlotsByName(self)

Expand Down Expand Up @@ -126,13 +133,10 @@ def on_dark_current_menu_button_clicked(self):

self.dark_current_widget.update_data()

if max(self.dark_current_widget.samples) > 1:
QtWidgets.QMessageBox.warning(
self,
'Unusually High Dark Current',
'These dark current values are unusually high values.'
' There might be something wrong with the SEAL kit you are using.'
)
self.high_dark_current(
'These dark current values are unusually high values. '
'There might be something wrong with the SEAL kit you are using.'
)

@QtCore.pyqtSlot()
def on_scan_menu_button_clicked(self):
Expand All @@ -144,10 +148,12 @@ def on_scan_menu_button_clicked(self):

self.stacked_widget.setCurrentIndex(2)

self.high_dark_current(
'Scanning may not be accurate due to unusually high dark current values. '
'There might be something wrong with the SEAL kit you are using.'
)

def high_dark_current(self, msg: str, title: str = 'Unusually High Dark Current'):
if max(self.dark_current_widget.samples) > 1:
QtWidgets.QMessageBox.warning(
self,
'Unusually High Dark Current',
'Scanning may not be accurate due to unusually high dark current values. '
'There might be something wrong with the SEAL kit your using.'
)
logger.warning('Unusually high dark current detected.')
QtWidgets.QMessageBox.warning(self, title, msg)
75 changes: 75 additions & 0 deletions beskar/logs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import logging, logging.handlers
import datetime
import pathlib

# NOTE: Adapted from: https://github.com/Ahsoka/bdaybot/blob/master/bdaybot/logs.py

class PrettyFormatter(logging.Formatter):
def __init__(self, *args, style='%', **kwargs):
if style != '%':
raise ValueError(f"__init__() does not currently accept {style} as valid style, please use %")
super().__init__(*args, style=style, **kwargs)

def levelname_in_front(self):
loc = self._fmt.find('%(levelname)s')
if loc == -1:
return False
return ')s' not in self._fmt[:loc]

def format(self, record):
unparsed = super().format(record)
if not self.levelname_in_front():
return unparsed
levels = ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
max_length = max(map(len, levels))
for index, level in enumerate(levels):
if level in unparsed:
break
end_loc = unparsed.find(level) + len(level)
end = unparsed[end_loc]
while end != ' ':
end_loc += 1
end = unparsed[end_loc]
spaces = max_length - len(level)
returning = (" " * spaces) + unparsed[:end_loc] + unparsed[end_loc:]
# print(f"returning == unparsed = {unparsed == returning}")
return returning

def file_renamer(filename: str):
split = filename.split('.')
return ".".join(split[:-3] + [split[-1], split[-2]])

def setUpLogger(name, fmt, logs_dir: pathlib.Path, files=True):
# Init the logger
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)

# Init the PrettyFormatter
pretty = PrettyFormatter(fmt=fmt)

# Create a handler that records all activity
everything = logging.handlers.TimedRotatingFileHandler(
logs_dir / f'{format(datetime.datetime.today(), "%Y-%m-%d")}.log',
when='midnight',
encoding='UTF-8'
)
# Do not use loggging.NOTSET, does not work for some reason
# use logging.DEBUG if you want the lowest level
everything.setLevel(logging.DEBUG)
everything.setFormatter(pretty)

# Rename files so .log is the file extension
everything.namer = file_renamer

# Add handlers to the logger
logger.addHandler(everything)

# Create a handler so we can see the output on the console
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
console.setFormatter(pretty)

# Add handler to the logger
logger.addHandler(console)

return logger
21 changes: 19 additions & 2 deletions beskar/pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@

import statistics as stats
import darkdetect
import pathlib
import logging
import nidaqmx
import random
import pathlib
import numpy
import random
import time
import csv

logger = logging.getLogger(__name__)


class BasePage(BaseInteractable, QtWidgets.QWidget):
def super_(self):
Expand Down Expand Up @@ -127,6 +130,10 @@ def on_apply_button_clicked(self):
# This is the implementation in the legacy software
self.current_voltage_applied = self.voltage_to_be_applied
self.apply_button.setEnabled(False)

if self.warning_label.isVisible():
logger.warning('Abnormally high voltage is about to be applied.')

if not self.main_window.mocked:
apply_voltage(
self.main_window.device_name,
Expand All @@ -139,6 +146,9 @@ def set_min_and_max(self):
self.min_voltage = -round(5 - offset - self.main_window.voltage_offset, 3)
self.max_voltage = -round(-offset - self.main_window.voltage_offset, 3)

logger.info(f'self.min_voltage set to {self.min_voltage}.')
logger.info(f'self.max_voltage set to {self.max_voltage}.')

self.horizontal_slider.setValue(abs(int(self.min_voltage * 1000)))
self.double_spin_box.setRange(self.min_voltage, self.max_voltage)

Expand Down Expand Up @@ -234,6 +244,8 @@ def update_data(self):
for num, sample in enumerate(self.samples):
self.scatter.append(num + 1, sample)

logger.info('Updated dark current readings.')

@QtCore.pyqtSlot()
def on_refresh_button_clicked(self):
self.update_data()
Expand Down Expand Up @@ -461,6 +473,8 @@ def on_ok_button_clicked(self):

scan_offset = len(self.bar_charts_tab)

logger.info(f'{self.scans} have been initiated.')

for scan_number in range(self.scans):
scan_number += scan_offset

Expand Down Expand Up @@ -506,6 +520,7 @@ def on_ok_button_clicked(self):

if self.bar_charts_tab.currentIndex() == scan_number:
if self.bar_charts[scan_number][2].last_values_zero():
logger.info('The last four values read from the SEAL kit have been zeros.')
self.notice_for_reading.show()
else:
self.notice_for_reading.hide()
Expand Down Expand Up @@ -591,6 +606,8 @@ def on_file_dialog_accepted(self):
else:
raise RuntimeError(f'This should never be triggered: {file_ext=}')

logger.info(f'{selected} has been created in order to save Scan {current_tab}.')

@QtCore.pyqtSlot()
def on_another_scan_button_clicked(self):
self.main_layout.insertItem(1, self.spacer2)
Expand Down
Loading

0 comments on commit 9f77128

Please sign in to comment.