Skip to content

Commit

Permalink
some logging adaptions
Browse files Browse the repository at this point in the history
  • Loading branch information
JoschD committed Nov 14, 2023
1 parent 96d442f commit c1ab766
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 18 deletions.
2 changes: 1 addition & 1 deletion omc3_gui/segment_by_segment.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@
import logging

if __name__ == "__main__":
init_logging(level=logging.DEBUG)
init_logging()
SbSController.run_application()
81 changes: 69 additions & 12 deletions omc3_gui/utils/base_classes.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import logging
import re
import sys
from typing import List, Union
import typing
from qtpy.QtCore import QObject
from qtpy.QtWidgets import QApplication, QFileDialog, QMenuBar, QDesktopWidget, QWidgetAction
from qtpy import QtGui
from omc3_gui import __version__
from omc3_gui.utils.log_handler import get_console_formatter

try:
from accwidgets.app_frame import ApplicationFrame
Expand All @@ -11,6 +16,11 @@
from qtpy.QtWidgets import QMainWindow as ApplicationFrame
exec_app_interruptable = lambda app: app.exec()

try:
from accwidgets.log_console import LogConsoleFormatter as AccPyLogConsoleFormatter
except ImportError:
AccPyLogConsoleFormatter = object



class Controller(QObject):
Expand Down Expand Up @@ -44,17 +54,8 @@ def __init__(self, *args, **kwargs):
del kwargs["use_log_console"]
super().__init__(*args, **kwargs) # QT Main window

if getattr(self, "log_console"):
self.log_console.console.expanded = False
self.log_console.setFeatures(
self.log_console.DockWidgetClosable | self.log_console.DockWidgetMovable
)

# Sizing ---
screen_shape = QDesktopWidget().screenGeometry()
self.resize(2 * screen_shape.width() / 3,
2 * screen_shape.height() / 3)

self._adapt_logger()
self._adapt_to_screensize()
self.build_menu_bar()

def build_menu_bar(self):
Expand All @@ -78,6 +79,26 @@ def build_menu_bar(self):
# Set menu bar ---
self.setMenuBar(self._menu_bar)

def _adapt_to_screensize(self):
""" Sets the window size to 2/3 of the screen size. """
screen_shape = QDesktopWidget().screenGeometry()
self.resize(2 * screen_shape.width() / 3,
2 * screen_shape.height() / 3)

def _adapt_logger(self):
""" Changes the appearance of the log console. """
if getattr(self, "log_console") is None:
return
self.log_console.console.expanded = False
self.log_console.setFeatures(
self.log_console.DockWidgetClosable | self.log_console.DockWidgetMovable
)
self.log_console.console.formatter = LogConsoleFormatter(show_date=False) # see below
self.log_console.console._set_color_to_scheme(color=QtGui.QColor("#b6b6b6b"), level=logging.DEBUG) # default: black
# self.log_console.console._set_color_to_scheme(color=QtGui.QColor("#000000"), level=logging.INFO) # default: green
self.log_console.console.model.buffer_size = 10_000 # default: 1000
if sys.flags.debug:
self.log_console.console.model.visible_levels |= {logging.DEBUG}

def setWindowTitle(self, title: str):
super().setWindowTitle(f"{title} v{self.__app_version__}")
Expand All @@ -86,4 +107,40 @@ def toggleFullScreen(self):
if self.isFullScreen():
self.showNormal()
else:
self.showFullScreen()
self.showFullScreen()


class LogConsoleFormatter(AccPyLogConsoleFormatter):

def __init__(self, show_date: bool = True, show_time: bool = True, show_logger_name: bool = True) -> None:
"""
Reimplementation of the AccPy LogConsoleFormatter, to allow for a different logging format.
Args:
show_date: Add date to the log message prefix.
show_time: Add time to the log message prefix.
show_logger_name: Add logger name to the log message prefix.
"""
super().__init__()

self.show_date = show_date
self.show_time = show_time
self.show_logger_name = show_logger_name

fmt_str = get_console_formatter()._fmt
date_format = []

if show_date:
date_format.append("%Y-%m-%d")
if show_time:
date_format.append("%H:%M:%S")

if not show_date and not show_time:
fmt_str = re.sub(r"\%\(asctime\)\d+s\s+", "", fmt_str)

if not show_logger_name:
fmt_str = re.sub(r"\%\(name\)\d+s\s+", "", fmt_str)

fmt_str = fmt_str[fmt_str.index("%"):]

self._fmt = logging.Formatter(fmt=fmt_str, datefmt=" ".join(date_format), style="%")
22 changes: 17 additions & 5 deletions omc3_gui/utils/log_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,36 @@ def add_file_handler(log_dir):
log_file = os.path.join(log_dir, "log.txt")
file_handler = FileHandler(log_file, mode="w")
file_handler.setLevel(logging.DEBUG)
file_handler.setFormatter(_get_formatter())
file_handler.setFormatter(get_file_formatter())
logger.addHandler(file_handler)
logger.info("Set up debug log file in: " +
os.path.abspath(log_file))


def _get_formatter():
def get_file_formatter():
formatter = logging.Formatter(
"%(name)s %(asctime)s %(levelname)s %(message)s"
)
formatter.datefmt = '%d/%m/%Y %H:%M:%S'
formatter.datefmt = '%Y-%m-%d %H:%M:%S'
return formatter


def init_logging(level=logging.INFO):
def get_console_formatter():
formatter = logging.Formatter(
"%(asctime)s %(name)20s | %(levelname)s - %(message)s"
)
formatter.datefmt = '%H:%M:%S'
return formatter


def init_logging(level: int = None):
""" Set up a basic logger. """
if level is None:
level = logging.DEBUG if sys.flags.debug else logging.INFO

logging.basicConfig(
stream=sys.stdout,
level=level,
format="%(levelname)7s | %(message)s | %(name)s"
format=get_console_formatter()._fmt,
datefmt=get_console_formatter().datefmt,
)

0 comments on commit c1ab766

Please sign in to comment.