logger-36 2024.1__py3-none-any.whl → 2024.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. logger_36/__init__.py +2 -7
  2. logger_36/catalog/config/console_rich.py +49 -0
  3. logger_36/catalog/handler/console.py +80 -0
  4. logger_36/{type/console.py → catalog/handler/console_rich.py} +77 -52
  5. logger_36/catalog/handler/file.py +90 -0
  6. logger_36/catalog/handler/generic.py +150 -0
  7. logger_36/catalog/logging/chronos.py +39 -0
  8. logger_36/catalog/{gpu.py → logging/gpu.py} +3 -1
  9. logger_36/catalog/logging/memory.py +105 -0
  10. logger_36/catalog/{system.py → logging/system.py} +5 -27
  11. logger_36/config/issue.py +35 -0
  12. logger_36/config/memory.py +33 -0
  13. logger_36/{config.py → config/message.py} +14 -14
  14. logger_36/config/system.py +49 -0
  15. logger_36/constant/generic.py +37 -0
  16. logger_36/constant/handler.py +35 -0
  17. logger_36/constant/issue.py +35 -0
  18. logger_36/{type/file.py → constant/logger.py} +13 -15
  19. logger_36/constant/memory.py +39 -0
  20. logger_36/{constant.py → constant/message.py} +11 -15
  21. logger_36/constant/record.py +35 -0
  22. logger_36/constant/system.py +39 -0
  23. logger_36/instance.py +5 -5
  24. logger_36/main.py +130 -32
  25. logger_36/{catalog → task/format}/memory.py +34 -33
  26. logger_36/task/format/message.py +112 -0
  27. logger_36/task/format/rule.py +47 -0
  28. logger_36/task/inspection.py +18 -18
  29. logger_36/{measure → task/measure}/chronos.py +4 -2
  30. logger_36/task/storage.py +64 -3
  31. logger_36/type/extension.py +73 -61
  32. logger_36/type/issue.py +57 -0
  33. logger_36/type/logger.py +346 -0
  34. logger_36/version.py +1 -1
  35. {logger_36-2024.1.dist-info → logger_36-2024.3.dist-info}/METADATA +2 -3
  36. logger_36-2024.3.dist-info/RECORD +39 -0
  37. {logger_36-2024.1.dist-info → logger_36-2024.3.dist-info}/WHEEL +1 -1
  38. logger_36/type/generic.py +0 -115
  39. logger_36-2024.1.dist-info/RECORD +0 -21
  40. /logger_36/{measure → task/measure}/memory.py +0 -0
  41. {logger_36-2024.1.dist-info → logger_36-2024.3.dist-info}/top_level.txt +0 -0
logger_36/main.py CHANGED
@@ -29,68 +29,166 @@
29
29
  # The fact that you are presently reading this means that you have had
30
30
  # knowledge of the CeCILL license and that you accept its terms.
31
31
 
32
- """
33
- Alternative implementations: using logging.Filter or logging.LoggerAdapter.
34
- """
35
32
  import logging as lggg
33
+ import sys as sstm
36
34
  from pathlib import Path as path_t
37
- from typing import Callable, Literal
38
35
 
36
+ try:
37
+ from logger_36.catalog.handler.console_rich import console_rich_handler_t
38
+
39
+ _RICH_ERROR = None
40
+ except ModuleNotFoundError:
41
+ from logger_36.catalog.handler.console import (
42
+ console_handler_t as console_rich_handler_t,
43
+ )
44
+
45
+ _RICH_ERROR = (
46
+ "The Rich console handler is not available, "
47
+ "probably because the Rich package "
48
+ "(https://rich.readthedocs.io/en/stable/index.html) "
49
+ "is not installed, or not loadable. "
50
+ "Falling back to the raw console."
51
+ )
52
+ from logger_36.catalog.handler.console import console_handler_t
53
+ from logger_36.catalog.handler.file import file_handler_t
54
+ from logger_36.catalog.handler.generic import generic_handler_t, interface_h
55
+ from logger_36.constant.handler import HANDLER_CODES, handler_codes_h
39
56
  from logger_36.instance import LOGGER
40
- from logger_36.type.console import console_handler_t
41
- from logger_36.type.file import file_handler_t
42
- from logger_36.type.generic import can_show_message_p, generic_handler_t
57
+ from logger_36.task.format.message import FormattedMessage
43
58
 
44
59
 
45
60
  def AddGenericHandler(
46
- interface: can_show_message_p | Callable[[str], None],
61
+ interface: interface_h,
47
62
  /,
48
- *args,
63
+ *,
64
+ name: str | None = None,
49
65
  level: int = lggg.INFO,
66
+ show_where: bool = True,
67
+ show_memory_usage: bool = False,
68
+ formatter: lggg.Formatter | None = None,
50
69
  supports_html: bool = False,
70
+ should_hold_messages: bool = False,
71
+ **kwargs,
72
+ ) -> None:
73
+ """"""
74
+ handler = generic_handler_t(
75
+ name=name,
76
+ level=level,
77
+ show_where=show_where,
78
+ show_memory_usage=show_memory_usage,
79
+ formatter=formatter,
80
+ supports_html=supports_html,
81
+ rich_kwargs=kwargs,
82
+ interface=interface,
83
+ )
84
+ LOGGER.AddHandler(handler, should_hold_messages)
85
+
86
+
87
+ def AddConsoleHandler(
88
+ *,
89
+ name: str | None = None,
90
+ level: int = lggg.INFO,
91
+ show_where: bool = True,
92
+ show_memory_usage: bool = False,
93
+ formatter: lggg.Formatter | None = None,
94
+ should_hold_messages: bool = False,
95
+ ) -> None:
96
+ """"""
97
+ handler = console_handler_t(
98
+ name=name,
99
+ level=level,
100
+ show_where=show_where,
101
+ show_memory_usage=show_memory_usage,
102
+ formatter=formatter,
103
+ )
104
+ LOGGER.AddHandler(handler, should_hold_messages)
105
+
106
+
107
+ def AddRichConsoleHandler(
108
+ *,
109
+ name: str | None = None,
110
+ level: int = lggg.INFO,
111
+ show_where: bool = True,
112
+ show_memory_usage: bool = False,
113
+ formatter: lggg.Formatter | None = None,
114
+ should_hold_messages: bool = False,
51
115
  **kwargs,
52
116
  ) -> None:
53
117
  """"""
54
- handler = generic_handler_t(interface, *args, supports_html=supports_html, **kwargs)
55
- handler.setLevel(level)
56
- LOGGER.addHandler(handler)
118
+ global _RICH_ERROR
119
+ if _RICH_ERROR is not None:
120
+ print(_RICH_ERROR, file=sstm.stderr)
121
+ _RICH_ERROR = None
122
+
123
+ handler = console_rich_handler_t(
124
+ name=name,
125
+ level=level,
126
+ show_where=show_where,
127
+ show_memory_usage=show_memory_usage,
128
+ formatter=formatter,
129
+ rich_kwargs=kwargs,
130
+ )
131
+ LOGGER.AddHandler(handler, should_hold_messages)
57
132
 
58
133
 
59
134
  def AddFileHandler(
60
- path: str | path_t, /, *args, level: int = lggg.INFO, **kwargs
135
+ path: str | path_t,
136
+ /,
137
+ *args,
138
+ name: str | None = None,
139
+ level: int = lggg.INFO,
140
+ show_where: bool = True,
141
+ show_memory_usage: bool = False,
142
+ formatter: lggg.Formatter | None = None,
143
+ should_hold_messages: bool = False,
144
+ **kwargs,
61
145
  ) -> None:
62
146
  """"""
63
147
  if isinstance(path, str):
64
148
  path = path_t(path)
65
149
  if path.exists():
66
- raise ValueError(f"{path}: File already exists")
150
+ raise ValueError(f"File or folder already exists: {path}.")
67
151
 
68
- handler = file_handler_t(path, *args, **kwargs)
69
- handler.setLevel(level)
70
- LOGGER.addHandler(handler)
152
+ handler = file_handler_t(
153
+ name=name,
154
+ level=level,
155
+ show_where=show_where,
156
+ show_memory_usage=show_memory_usage,
157
+ formatter=formatter,
158
+ path=path,
159
+ handler_args=args,
160
+ handler_kwargs=kwargs,
161
+ )
162
+ LOGGER.AddHandler(handler, should_hold_messages)
71
163
 
72
164
 
73
- def SetLOGLevel(level: int, /, *, which: Literal["c", "f", "a"] = "a") -> None:
165
+ def SetLOGLevel(level: int, /, *, which: handler_codes_h | str = "a") -> None:
74
166
  """
75
- which: c=console, f=file, a=all
167
+ which: g=generic, c=console, f=file, a=all, str=name.
76
168
  """
77
- if which not in "cfa":
78
- raise ValueError(
79
- f"{which}: Invalid handler specifier. "
80
- f'Expected="c" for console, "f" for file, or "a" for all'
81
- )
82
-
169
+ which_is_name = which not in HANDLER_CODES
170
+ found = False
83
171
  for handler in LOGGER.handlers:
84
172
  if (
85
173
  (which == "a")
86
- or ((which == "c") and isinstance(handler, console_handler_t))
174
+ or ((which == "g") and isinstance(handler, generic_handler_t))
175
+ or (
176
+ (which == "c")
177
+ and isinstance(handler, (console_handler_t, console_rich_handler_t))
178
+ )
87
179
  or ((which == "f") and isinstance(handler, file_handler_t))
180
+ or (which == handler.name)
88
181
  ):
89
182
  handler.setLevel(level)
183
+ if which_is_name:
184
+ return
185
+ found = True
90
186
 
91
-
92
- def SetExitOnError(exit_on_error: bool, /) -> None:
93
- """"""
94
- for handler in LOGGER.handlers:
95
- if hasattr(handler, "exit_on_error"):
96
- handler.exit_on_error = exit_on_error
187
+ if not found:
188
+ raise ValueError(
189
+ FormattedMessage(
190
+ "Handler not found",
191
+ actual=which,
192
+ expected=f"{str(HANDLER_CODES)[1:-1]}, or a handler name",
193
+ )
194
+ )
@@ -29,65 +29,54 @@
29
29
  # The fact that you are presently reading this means that you have had
30
30
  # knowledge of the CeCILL license and that you accept its terms.
31
31
 
32
- from typing import Literal
32
+ from logger_36.constant.memory import STORAGE_UNITS, storage_units_h
33
+ from logger_36.task.format.message import FormattedMessage
33
34
 
34
- from logger_36.instance import LOGGER
35
- from logger_36.measure.memory import CanCheckMemory
35
+ _KILO_UNIT = 1000.0
36
+ _MEGA_UNIT = _KILO_UNIT * 1000.0
37
+ _GIGA_UNIT = _MEGA_UNIT * 1000.0
36
38
 
37
- _KILO_UNIT = 1024.0
38
- _MEGA_UNIT = _KILO_UNIT * 1024.0
39
- _GIGA_UNIT = _MEGA_UNIT * 1024.0
40
-
41
-
42
- def SetShowMemoryUsage(show_memory_usage: bool, /) -> None:
43
- """"""
44
- if show_memory_usage and not CanCheckMemory():
45
- LOGGER.warning('Cannot show memory usage: Package "psutil" not installed')
46
- return
47
-
48
- for handler in LOGGER.handlers:
49
- if hasattr(handler, "show_memory_usage"):
50
- handler.show_memory_usage = show_memory_usage
39
+ _BLOCKS_PARTIAL = ("", "▏", "▎", "▍", "▌", "▋", "▊")
40
+ _BLOCK_FULL = "▉"
51
41
 
52
42
 
53
43
  def FormattedUsage(
54
44
  usage: int,
55
45
  /,
56
46
  *,
57
- unit: Literal["b", "k", "m", "g", "a"] | None = "a",
47
+ unit: storage_units_h | None = "a",
58
48
  decimals: int = None,
59
49
  ) -> tuple[int | float, str]:
60
50
  """
61
51
  unit: b or None=bytes, k=kilo, m=mega, g=giga, a=auto
62
52
  """
63
53
  if (unit is None) or (unit == "b"):
54
+ value = usage
64
55
  unit = "B"
65
56
  elif unit == "k":
66
- usage = _Rounded(usage / _KILO_UNIT, decimals)
57
+ value = _Rounded(usage / _KILO_UNIT, decimals)
67
58
  unit = "KB"
68
59
  elif unit == "m":
69
- usage = _Rounded(usage / _MEGA_UNIT, decimals)
60
+ value = _Rounded(usage / _MEGA_UNIT, decimals)
70
61
  unit = "MB"
71
62
  elif unit == "g":
72
- usage = _Rounded(usage / _GIGA_UNIT, decimals)
63
+ value = _Rounded(usage / _GIGA_UNIT, decimals)
73
64
  unit = "GB"
74
65
  elif unit == "a":
75
- usage, unit = WithAutoUnit(usage, decimals)
66
+ value, unit = FormattedUsageWithAutoUnit(usage, decimals)
67
+ else:
68
+ raise ValueError(
69
+ FormattedMessage(
70
+ "Invalid unit", actual=unit, expected=str(STORAGE_UNITS)[1:-1]
71
+ )
72
+ )
76
73
 
77
- return usage, unit
74
+ return value, unit
78
75
 
79
76
 
80
- def MaximumUsage(
81
- *, unit: Literal["b", "k", "m", "g", "a"] | None = "a", decimals: int = None
77
+ def FormattedUsageWithAutoUnit(
78
+ usage: int, decimals: int | None, /
82
79
  ) -> tuple[int | float, str]:
83
- """
84
- unit: b or None=bytes, k=kilo, m=mega, g=giga, a=auto
85
- """
86
- usage = max(getattr(_hdr, "max_memory_usage", -1) for _hdr in LOGGER.handlers)
87
- return FormattedUsage(usage, unit=unit, decimals=decimals)
88
-
89
-
90
- def WithAutoUnit(usage: int, decimals: int | None, /) -> tuple[int | float, str]:
91
80
  """"""
92
81
  if usage > _GIGA_UNIT:
93
82
  return _Rounded(usage / _GIGA_UNIT, decimals), "GB"
@@ -101,6 +90,18 @@ def WithAutoUnit(usage: int, decimals: int | None, /) -> tuple[int | float, str]
101
90
  return usage, "B"
102
91
 
103
92
 
93
+ def UsageBar(
94
+ usage: int | float, max_usage: int | float, /, *, length_100: int = 10
95
+ ) -> str:
96
+ """"""
97
+ length = (usage / max_usage) * length_100
98
+ n_full_s = int(length)
99
+ return (
100
+ n_full_s * _BLOCK_FULL
101
+ + _BLOCKS_PARTIAL[int((2.0 / 3.0) * int(10 * (length - n_full_s)))]
102
+ )
103
+
104
+
104
105
  def _Rounded(value: float, decimals: int | None, /) -> int | float:
105
106
  """"""
106
107
  if decimals == 0:
@@ -0,0 +1,112 @@
1
+ # Copyright CNRS/Inria/UCA
2
+ # Contributor(s): Eric Debreuve (since 2023)
3
+ #
4
+ # eric.debreuve@cnrs.fr
5
+ #
6
+ # This software is governed by the CeCILL license under French law and
7
+ # abiding by the rules of distribution of free software. You can use,
8
+ # modify and/ or redistribute the software under the terms of the CeCILL
9
+ # license as circulated by CEA, CNRS and INRIA at the following URL
10
+ # "http://www.cecill.info".
11
+ #
12
+ # As a counterpart to the access to the source code and rights to copy,
13
+ # modify and redistribute granted by the license, users are provided only
14
+ # with a limited warranty and the software's author, the holder of the
15
+ # economic rights, and the successive licensors have only limited
16
+ # liability.
17
+ #
18
+ # In this respect, the user's attention is drawn to the risks associated
19
+ # with loading, using, modifying and/or developing or reproducing the
20
+ # software by the user in light of its specific status of free software,
21
+ # that may mean that it is complicated to manipulate, and that also
22
+ # therefore means that it is reserved for developers and experienced
23
+ # professionals having in-depth computer knowledge. Users are therefore
24
+ # encouraged to load and test the software's suitability as regards their
25
+ # requirements in conditions enabling the security of their systems and/or
26
+ # data to be ensured and, more generally, to use and operate it in the
27
+ # same conditions as regards security.
28
+ #
29
+ # The fact that you are presently reading this means that you have had
30
+ # knowledge of the CeCILL license and that you accept its terms.
31
+
32
+ import typing as h
33
+
34
+ from logger_36.config.message import (
35
+ ELAPSED_TIME_FORMAT,
36
+ LEVEL_CLOSING,
37
+ LEVEL_OPENING,
38
+ MEMORY_FORMAT,
39
+ MESSAGE_MARKER,
40
+ )
41
+ from logger_36.constant.generic import NOT_PASSED
42
+ from logger_36.constant.message import EXPECTED_OP, expected_op_h
43
+
44
+
45
+ def MessageFormat(with_where: bool, with_memory_usage: bool, /) -> str:
46
+ """"""
47
+ output = [
48
+ f"%(asctime)s"
49
+ f"{LEVEL_OPENING}%(level_first_letter)s{LEVEL_CLOSING}\t"
50
+ f"{MESSAGE_MARKER}%(message)s"
51
+ ]
52
+
53
+ if with_where:
54
+ output.append("%(where)s")
55
+ output.append(ELAPSED_TIME_FORMAT)
56
+ if with_memory_usage:
57
+ output.append(MEMORY_FORMAT)
58
+
59
+ return "".join(output)
60
+
61
+
62
+ def FormattedMessage(
63
+ message: str,
64
+ /,
65
+ *,
66
+ actual: h.Any = NOT_PASSED,
67
+ expected: h.Any | None = None,
68
+ expected_op: expected_op_h = "=",
69
+ with_final_dot: bool = True,
70
+ ) -> str:
71
+ """"""
72
+ if expected_op not in EXPECTED_OP:
73
+ raise ValueError(
74
+ FormattedMessage(
75
+ 'Invalid "expected" section operator',
76
+ actual=expected_op,
77
+ expected=f"One of {str(EXPECTED_OP)[1:-1]}",
78
+ )
79
+ )
80
+
81
+ if actual is NOT_PASSED:
82
+ if with_final_dot:
83
+ if message[-1] != ".":
84
+ message += "."
85
+ elif message[-1] == ".":
86
+ message = message[:-1]
87
+
88
+ return message
89
+
90
+ if message[-1] == ".":
91
+ message = message[:-1]
92
+ actual = _FormattedValue(actual)
93
+ expected = _FormattedValue(expected)
94
+
95
+ if with_final_dot:
96
+ dot = "."
97
+ else:
98
+ dot = ""
99
+ return f"{message}: Actual={actual}; Expected{expected_op}{expected}{dot}"
100
+
101
+
102
+ def _FormattedValue(value: h.Any, /, *, should_format_str: bool = True) -> str:
103
+ """"""
104
+ if value is None:
105
+ return "None"
106
+
107
+ if isinstance(value, str):
108
+ if should_format_str:
109
+ return f'"{value}"'
110
+ return value
111
+
112
+ return str(value)
@@ -0,0 +1,47 @@
1
+ # Copyright CNRS/Inria/UCA
2
+ # Contributor(s): Eric Debreuve (since 2023)
3
+ #
4
+ # eric.debreuve@cnrs.fr
5
+ #
6
+ # This software is governed by the CeCILL license under French law and
7
+ # abiding by the rules of distribution of free software. You can use,
8
+ # modify and/ or redistribute the software under the terms of the CeCILL
9
+ # license as circulated by CEA, CNRS and INRIA at the following URL
10
+ # "http://www.cecill.info".
11
+ #
12
+ # As a counterpart to the access to the source code and rights to copy,
13
+ # modify and redistribute granted by the license, users are provided only
14
+ # with a limited warranty and the software's author, the holder of the
15
+ # economic rights, and the successive licensors have only limited
16
+ # liability.
17
+ #
18
+ # In this respect, the user's attention is drawn to the risks associated
19
+ # with loading, using, modifying and/or developing or reproducing the
20
+ # software by the user in light of its specific status of free software,
21
+ # that may mean that it is complicated to manipulate, and that also
22
+ # therefore means that it is reserved for developers and experienced
23
+ # professionals having in-depth computer knowledge. Users are therefore
24
+ # encouraged to load and test the software's suitability as regards their
25
+ # requirements in conditions enabling the security of their systems and/or
26
+ # data to be ensured and, more generally, to use and operate it in the
27
+ # same conditions as regards security.
28
+ #
29
+ # The fact that you are presently reading this means that you have had
30
+ # knowledge of the CeCILL license and that you accept its terms.
31
+
32
+
33
+ def RuleAsText(text: str, /) -> str:
34
+ """"""
35
+ return f"---- ---- ---- ---- {text} ---- ---- ---- ----"
36
+
37
+
38
+ try:
39
+ from rich.rule import Rule as rule_t
40
+ from rich.text import Text as text_t
41
+
42
+ def Rule(text: str, color: str, /) -> rule_t:
43
+ """"""
44
+ return rule_t(title=text_t(text, style=f"bold {color}"), style=color)
45
+
46
+ except ModuleNotFoundError:
47
+ Rule = lambda _txt, _: RuleAsText(_txt)
@@ -36,14 +36,15 @@ from types import FunctionType, MethodType
36
36
 
37
37
 
38
38
  def Modules(
39
- with_version: bool, formatted: bool, /, *, only_loaded: bool = True
39
+ with_version: bool, formatted: bool, /, *, only_loaded: bool = True, indent: int = 0
40
40
  ) -> tuple[str, ...] | str:
41
41
  """"""
42
42
  output = []
43
43
 
44
44
  if only_loaded:
45
45
  modules = sstm.modules
46
- module_names = sorted(modules.keys(), key=str.lower)
46
+ module_names = set(modules.keys()).difference(sstm.stdlib_module_names)
47
+ module_names = sorted(module_names, key=str.lower)
47
48
  else:
48
49
  modules = None
49
50
  module_names = _ModulesUsingPkgUtil()
@@ -53,35 +54,34 @@ def Modules(
53
54
  if name.startswith("_") or ("." in name):
54
55
  continue
55
56
 
56
- if modules is None:
57
- version = "?version?"
58
- else:
59
- module = modules[name]
60
- version = getattr(module, "__version__", None)
61
- if version is None:
62
- continue
63
-
64
- if formatted and (m_idx > 0) and (m_idx % 4 == 0):
65
- output.append("\n")
66
-
67
57
  if with_version:
58
+ if modules is None:
59
+ version = "?"
60
+ else:
61
+ module = modules[name]
62
+ # strip: Some packages have a \n at the end of their version. Just in
63
+ # case, let's strip it left and right.
64
+ version = getattr(module, "__version__", "?").strip()
68
65
  element = f"{name}={version}"
69
66
  else:
70
67
  element = name
68
+
69
+ if formatted and (m_idx > 0) and (m_idx % 4 == 0):
70
+ output.append("\n")
71
71
  output.append(element)
72
72
 
73
73
  if formatted:
74
- max_length = max(max_length, name.__len__() + version.__len__() + 1)
74
+ max_length = max(max_length, element.__len__())
75
75
  m_idx += 1
76
76
 
77
77
  if formatted:
78
78
  max_length += 4
79
- AlignedInColumns = lambda _str: (
80
- f"{_str:{max_length}}" if _str != "\n" else "\n "
81
- )
79
+ AlignedInColumns = lambda _str: f"{_str:{max_length}}" if _str != "\n" else "\n"
82
80
  output = map(AlignedInColumns, output)
81
+ output = "".join(output).rstrip()
83
82
 
84
- return "".join(output)
83
+ spaces = indent * " "
84
+ return spaces + f"\n{spaces}".join(map(str.rstrip, output.splitlines()))
85
85
 
86
86
  return tuple(output)
87
87
 
@@ -32,7 +32,9 @@
32
32
  import time
33
33
  from datetime import datetime as dttm
34
34
 
35
- from logger_36.constant import START_TIME
35
+ # This module is imported early. Therefore, the current date and time should be close
36
+ # enough to the real start time of the main script.
37
+ _START_DATE_AND_TIME = dttm.now()
36
38
 
37
39
 
38
40
  def TimeStamp() -> str:
@@ -47,7 +49,7 @@ def TimeStamp() -> str:
47
49
 
48
50
  def ElapsedTime() -> str:
49
51
  """"""
50
- elapsed_seconds = (dttm.now() - START_TIME).total_seconds()
52
+ elapsed_seconds = (dttm.now() - _START_DATE_AND_TIME).total_seconds()
51
53
  output = time.strftime("%Hh %Mm %Ss", time.gmtime(elapsed_seconds))
52
54
  while output.startswith("00") and (" " in output):
53
55
  output = output.split(maxsplit=1)[-1]
logger_36/task/storage.py CHANGED
@@ -29,21 +29,82 @@
29
29
  # The fact that you are presently reading this means that you have had
30
30
  # knowledge of the CeCILL license and that you accept its terms.
31
31
 
32
+ import dataclasses as dtcl
32
33
  import logging as lggg
34
+ import re as regx
35
+ import typing as h
36
+ from html.parser import HTMLParser as html_parser_t
33
37
  from pathlib import Path as path_t
34
- from typing import TextIO
35
38
 
36
- from rich.console import Console as console_t
39
+ try:
40
+ from rich.console import Console as console_t
41
+ except ModuleNotFoundError:
42
+ console_t = None
37
43
 
38
44
  from logger_36.instance import LOGGER
39
45
 
46
+ _BODY_END_PATTERN = r"</[bB][oO][dD][yY]>(.|\n)*$"
40
47
 
41
- def SaveLOGasHTML(path: str | path_t | TextIO = None) -> None:
48
+
49
+ @dtcl.dataclass(slots=True, repr=False, eq=False)
50
+ class html_reader_t(html_parser_t):
51
+ source: str = ""
52
+ inside_body: bool = dtcl.field(init=False, default=False)
53
+ body_position_start: tuple[int, int] = dtcl.field(init=False, default=(-1, -1))
54
+ body_position_end: tuple[int, int] = dtcl.field(init=False, default=(-1, -1))
55
+ pieces: list[str] = dtcl.field(init=False, default_factory=list)
56
+
57
+ def __post_init__(self) -> None:
58
+ """"""
59
+ html_parser_t.__init__(self)
60
+ self.source = self.source.strip()
61
+ self.feed(self.source)
62
+
63
+ def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]], /) -> None:
64
+ """"""
65
+ if tag == "body":
66
+ self.body_position_start = self.getpos()
67
+ self.inside_body = True
68
+
69
+ def handle_endtag(self, tag: str, /) -> None:
70
+ """"""
71
+ if tag == "body":
72
+ self.body_position_end = self.getpos()
73
+ self.inside_body = False
74
+
75
+ def handle_data(self, data: str, /) -> None:
76
+ """"""
77
+ if self.inside_body:
78
+ self.pieces.append(data)
79
+
80
+ @property
81
+ def body(self) -> str:
82
+ """"""
83
+ output = self.source.splitlines()
84
+ output = "\n".join(
85
+ output[self.body_position_start[0] : (self.body_position_end[0] + 1)]
86
+ )
87
+ output = output[self.body_position_start[1] :]
88
+ output = regx.sub(_BODY_END_PATTERN, "", output, count=1)
89
+
90
+ return output.strip()
91
+
92
+ @property
93
+ def body_as_text(self) -> str:
94
+ """"""
95
+ return "".join(self.pieces).strip()
96
+
97
+
98
+ def SaveLOGasHTML(path: str | path_t | h.TextIO = None) -> None:
42
99
  """
43
100
  From first console handler found.
44
101
  """
45
102
  cannot_save = "Cannot save logging record as HTML"
46
103
 
104
+ if console_t is None:
105
+ LOGGER.warning(f"{cannot_save}: The Rich console cannot be imported.")
106
+ return
107
+
47
108
  if path is None:
48
109
  for handler in LOGGER.handlers:
49
110
  if isinstance(handler, lggg.FileHandler):