Logging

Logger API

Logging in view.py is a bit more complicated than other libraries. The original logging module that comes with Python wasn't really fun to deal with, so a more abstracted API on top of it was designed.

_Logger is an abstract class to give a nicer, more object oriented approach to logging. To create a new _Logger ready class, simply inherit from it and specify a logging.Logger object:

class MyLogger(_Logger):
    log = logging.getLogger("MyLogger")

MyLogger above could then be used like so:

MyLogger.info("something")

_Logger

Bases: ABC

Wrapper around the built in logger.

Source code in src/view/_logging.py
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
class _Logger(ABC):
    """Wrapper around the built in logger."""

    log: logging.Logger

    @staticmethod
    def _log(
        attr: Callable[..., None],
        *msg: object,
        highlight: bool = True,
        **kwargs,
    ):
        attr(
            _sep(msg),
            extra={
                "markup": True,
                **({} if highlight else {"highlighter": None}),
            },
            **kwargs,
        )

    @classmethod
    def debug(cls, *msg: object, **kwargs):
        """Write debug message."""
        cls._log(cls.log.debug, *msg, **kwargs)

    @classmethod
    def info(cls, *msg: object, **kwargs):
        """Write info message."""
        cls._log(cls.log.info, *msg, **kwargs)

    @classmethod
    def warning(cls, *msg: object, **kwargs):
        """Write warning message."""
        cls._log(cls.log.warning, *msg, **kwargs)

    @classmethod
    def error(cls, *msg: object, **kwargs):
        """Write error message."""
        cls._log(cls.log.error, *msg, **kwargs)

    @classmethod
    def critical(cls, *msg: object, **kwargs):
        """Write critical message."""
        cls._log(cls.log.critical, *msg, **kwargs)

    @classmethod
    def exception(cls, *msg: object, **kwargs):
        """Write exception."""
        cls._log(cls.log.exception, *msg, **kwargs)

critical(*msg, **kwargs) classmethod

Write critical message.

Source code in src/view/_logging.py
290
291
292
293
@classmethod
def critical(cls, *msg: object, **kwargs):
    """Write critical message."""
    cls._log(cls.log.critical, *msg, **kwargs)

debug(*msg, **kwargs) classmethod

Write debug message.

Source code in src/view/_logging.py
270
271
272
273
@classmethod
def debug(cls, *msg: object, **kwargs):
    """Write debug message."""
    cls._log(cls.log.debug, *msg, **kwargs)

error(*msg, **kwargs) classmethod

Write error message.

Source code in src/view/_logging.py
285
286
287
288
@classmethod
def error(cls, *msg: object, **kwargs):
    """Write error message."""
    cls._log(cls.log.error, *msg, **kwargs)

exception(*msg, **kwargs) classmethod

Write exception.

Source code in src/view/_logging.py
295
296
297
298
@classmethod
def exception(cls, *msg: object, **kwargs):
    """Write exception."""
    cls._log(cls.log.exception, *msg, **kwargs)

info(*msg, **kwargs) classmethod

Write info message.

Source code in src/view/_logging.py
275
276
277
278
@classmethod
def info(cls, *msg: object, **kwargs):
    """Write info message."""
    cls._log(cls.log.info, *msg, **kwargs)

warning(*msg, **kwargs) classmethod

Write warning message.

Source code in src/view/_logging.py
280
281
282
283
@classmethod
def warning(cls, *msg: object, **kwargs):
    """Write warning message."""
    cls._log(cls.log.warning, *msg, **kwargs)

view.py has two loggers, Service and Internal. Service is meant for general app information that is sent to the user, whereas Internal is meant for debugging.

Bases: _Logger

Logger to be seen by the user when the app is running.

Source code in src/view/_logging.py
301
302
303
304
class Service(_Logger):
    """Logger to be seen by the user when the app is running."""

    log = svc

Bases: _Logger

Logger to be seen by view.py developers for debugging purposes.

Source code in src/view/_logging.py
307
308
309
310
class Internal(_Logger):
    """Logger to be seen by view.py developers for debugging purposes."""

    log = internal

Warnings

Warnings have been customized for view.py to give a prettier output for the user. The implementation is taken from this issue.

Fancy Mode

Fancy mode is a special output for running an app. It's powered by rich live and has some specially designed components. It wraps things like I/O counts to a graph for more eye candy at runtime. It can be started via enter_server and ended via exit_server.

Once online, special QueueItem objects are sent to _QUEUE, which is handled by the live display and updated on screen.

Dataset

Dataset in a graph.

Source code in src/view/_logging.py
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
class Dataset:
    """Dataset in a graph."""

    def __init__(self, name: str, point_limit: int | None = None) -> None:
        """Args:
        name: Name of the dataset.
        point_limit: Amount of points allowed in the dataset at a time."""
        self.name = name
        self.points: dict[float, float] = {}
        self.point_limit = point_limit
        self.point_order = []

    def add_point(self, x: float, y: float) -> None:
        """Add a point to the dataset.

        Args:
            x: X value.
            y: Y value."""
        Internal.info(f"{self.point_limit} {len(self.point_order)}")
        if self.point_limit and (len(self.point_order) >= self.point_limit):
            to_del = self.point_order.pop(0)
            del self.points[to_del]

        self.point_order.append(x)
        self.points[x] = y

    def add_points(self, *args: tuple[float, float]) -> None:
        """Add multiple points to the dataset."""
        for i in args:
            self.add_point(*i)

__init__(name, point_limit=None)

Args: name: Name of the dataset. point_limit: Amount of points allowed in the dataset at a time.

Source code in src/view/_logging.py
722
723
724
725
726
727
728
729
def __init__(self, name: str, point_limit: int | None = None) -> None:
    """Args:
    name: Name of the dataset.
    point_limit: Amount of points allowed in the dataset at a time."""
    self.name = name
    self.points: dict[float, float] = {}
    self.point_limit = point_limit
    self.point_order = []

add_point(x, y)

Add a point to the dataset.

Parameters:

Name Type Description Default
x float

X value.

required
y float

Y value.

required
Source code in src/view/_logging.py
731
732
733
734
735
736
737
738
739
740
741
742
743
def add_point(self, x: float, y: float) -> None:
    """Add a point to the dataset.

    Args:
        x: X value.
        y: Y value."""
    Internal.info(f"{self.point_limit} {len(self.point_order)}")
    if self.point_limit and (len(self.point_order) >= self.point_limit):
        to_del = self.point_order.pop(0)
        del self.points[to_del]

    self.point_order.append(x)
    self.points[x] = y

add_points(*args)

Add multiple points to the dataset.

Source code in src/view/_logging.py
745
746
747
748
def add_points(self, *args: tuple[float, float]) -> None:
    """Add multiple points to the dataset."""
    for i in args:
        self.add_point(*i)

HeatedProgress

Bases: Progress

Progress that changes color based on how close the bar is to completion.

Source code in src/view/_logging.py
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
class HeatedProgress(Progress):
    """Progress that changes color based on how close the bar is to completion."""

    def make_tasks_table(self, tasks: Iterable[Task]) -> Table:
        result = super().make_tasks_table(tasks)

        for col in result.columns:
            for cell in col._cells:
                if isinstance(cell, ProgressBar):
                    cell.complete_style = _heat_color(cell.completed)
                elif isinstance(cell, Text):
                    text = str(cell)

                    if "%" not in text:
                        continue

                    cell.stylize(_heat_color(float(text[:-1])))
        return result

Internal

Bases: _Logger

Logger to be seen by view.py developers for debugging purposes.

Source code in src/view/_logging.py
307
308
309
310
class Internal(_Logger):
    """Logger to be seen by view.py developers for debugging purposes."""

    log = internal

LogPanel

Bases: Panel

Panel with limit on number of lines relative to the terminal size.

Source code in src/view/_logging.py
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
class LogPanel(Panel):
    """Panel with limit on number of lines relative to the terminal size."""

    def __init__(self, **kwargs):
        self._lines = [""]
        self._line_index = 0
        super().__init__("", **kwargs)

    def _inc(self):
        self._lines.append("")
        self._line_index += 1

    def write(self, text: str) -> None:
        """Write text to the panel."""
        for i in text:
            if i == "\n":
                self._inc()
            else:
                self._lines[self._line_index] += i

    def __rich_console__(
        self,
        console: Console,
        options: ConsoleOptions,
    ) -> RenderResult:
        height = options.max_height
        width = options.max_width

        while height < len(self._lines):
            self._lines.pop(0)
            self._line_index -= 1

        final_lines = []

        for i in self._lines:
            if len(i) < (width - 3):  # - 3 because the ellipsis
                final_lines.append(i)
            else:
                final_lines.append(f"{i[:width - 7]}...")

        self.renderable = "\n".join(final_lines)

        return super().__rich_console__(console, options)

write(text)

Write text to the panel.

Source code in src/view/_logging.py
670
671
672
673
674
675
676
def write(self, text: str) -> None:
    """Write text to the panel."""
    for i in text:
        if i == "\n":
            self._inc()
        else:
            self._lines[self._line_index] += i

LogTable

Bases: Table

Table with limit on number of columns relative to the terminal height.

Source code in src/view/_logging.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
class LogTable(Table):
    """Table with limit on number of columns relative to the terminal height."""

    def __rich_console__(
        self, console: "Console", options: "ConsoleOptions"
    ) -> "RenderResult":
        height = options.max_height
        while len(self.rows) > (height - 4):
            # - 4 because the header and footer lines
            self.rows.pop(0)
            for i in self.columns:
                i._cells.pop(0)

        return super().__rich_console__(console, options)

Plot

Plot renderable for rich.

Source code in src/view/_logging.py
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
class Plot:
    """Plot renderable for rich."""

    def __init__(self, name: str, x: str, y: str) -> None:
        """Args:
        name: Title of the graph.
        x: X label of the graph.
        y: Y label of the graph."""
        plt.xscale("linear")
        plt.yscale("linear")

        self.title = name
        self.x_label = x
        self.y_label = y
        self.datasets: dict[str, Dataset] = {}

    def dataset(self, name: str, *, point_limit: int | None = None) -> Dataset:
        """Generate or create a new dataset.

        Args:
            name: Name of the dataset.
            point_limit: Limit on the number of points to be allowed on the graph at a time. If not set, terminal size divided by 3 is used.
        """
        found = self.datasets.get(name)
        if found:
            return found

        size = os.get_terminal_size().lines // 3

        ds = Dataset(name, point_limit=point_limit or size)
        self.datasets[name] = ds
        return ds

    def _render(self, width: int, height: int) -> None:
        plt.clf()
        plt.plotsize(width, height)

        for ds in self.datasets.values():
            if ds.points:
                plt.plot(
                    [x for x in ds.points.keys()],
                    [y for y in ds.points.values()],
                    label=ds.name,
                )

        plt.title(self.title)
        plt.xlabel(self.x_label)
        plt.ylabel(self.y_label)
        plt.theme("pro")

    def __rich_console__(
        self, console: Console, options: ConsoleOptions
    ) -> RenderResult:
        self._render(options.max_width, options.max_height)
        yield Text.from_ansi(plt.build())

__init__(name, x, y)

Args: name: Title of the graph. x: X label of the graph. y: Y label of the graph.

Source code in src/view/_logging.py
754
755
756
757
758
759
760
761
762
763
764
765
def __init__(self, name: str, x: str, y: str) -> None:
    """Args:
    name: Title of the graph.
    x: X label of the graph.
    y: Y label of the graph."""
    plt.xscale("linear")
    plt.yscale("linear")

    self.title = name
    self.x_label = x
    self.y_label = y
    self.datasets: dict[str, Dataset] = {}

dataset(name, *, point_limit=None)

Generate or create a new dataset.

Parameters:

Name Type Description Default
name str

Name of the dataset.

required
point_limit int | None

Limit on the number of points to be allowed on the graph at a time. If not set, terminal size divided by 3 is used.

None
Source code in src/view/_logging.py
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
def dataset(self, name: str, *, point_limit: int | None = None) -> Dataset:
    """Generate or create a new dataset.

    Args:
        name: Name of the dataset.
        point_limit: Limit on the number of points to be allowed on the graph at a time. If not set, terminal size divided by 3 is used.
    """
    found = self.datasets.get(name)
    if found:
        return found

    size = os.get_terminal_size().lines // 3

    ds = Dataset(name, point_limit=point_limit or size)
    self.datasets[name] = ds
    return ds

Service

Bases: _Logger

Logger to be seen by the user when the app is running.

Source code in src/view/_logging.py
301
302
303
304
class Service(_Logger):
    """Logger to be seen by the user when the app is running."""

    log = svc

enter_server()

Start fancy mode.

Source code in src/view/_logging.py
 997
 998
 999
1000
1001
1002
def enter_server():
    """Start fancy mode."""
    if _CLOSE.is_set():
        _CLOSE.clear()

    Thread(target=_server_logger).start()

exit_server()

End fancy mode.

Source code in src/view/_logging.py
1005
1006
1007
def exit_server():
    """End fancy mode."""
    _CLOSE.set()