bear-utils 0.7.21__py3-none-any.whl → 0.7.22__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.
- bear_utils/__init__.py +24 -1
- bear_utils/ai/__init__.py +5 -5
- bear_utils/ai/ai_helpers/__init__.py +24 -18
- bear_utils/ai/ai_helpers/_parsers.py +27 -21
- bear_utils/ai/ai_helpers/_types.py +2 -7
- bear_utils/cache/__init__.py +35 -23
- bear_utils/cli/__init__.py +13 -0
- bear_utils/cli/commands.py +14 -8
- bear_utils/cli/prompt_helpers.py +40 -34
- bear_utils/cli/shell/__init__.py +1 -0
- bear_utils/cli/shell/_base_command.py +17 -18
- bear_utils/cli/shell/_base_shell.py +37 -34
- bear_utils/config/__init__.py +4 -2
- bear_utils/config/config_manager.py +193 -56
- bear_utils/config/dir_manager.py +8 -3
- bear_utils/config/settings_manager.py +94 -171
- bear_utils/constants/__init__.py +2 -1
- bear_utils/constants/_exceptions.py +6 -1
- bear_utils/constants/date_related.py +2 -0
- bear_utils/constants/logger_protocol.py +28 -0
- bear_utils/constants/time_related.py +2 -0
- bear_utils/database/__init__.py +2 -0
- bear_utils/database/_db_manager.py +10 -11
- bear_utils/events/__init__.py +3 -1
- bear_utils/events/events_class.py +11 -11
- bear_utils/events/events_module.py +17 -8
- bear_utils/extras/__init__.py +8 -6
- bear_utils/extras/_async_helpers.py +2 -3
- bear_utils/extras/_tools.py +54 -52
- bear_utils/extras/platform_utils.py +5 -1
- bear_utils/extras/responses/__init__.py +1 -0
- bear_utils/extras/responses/function_response.py +301 -0
- bear_utils/extras/wrappers/__init__.py +1 -0
- bear_utils/extras/wrappers/add_methods.py +17 -15
- bear_utils/files/__init__.py +3 -1
- bear_utils/files/file_handlers/__init__.py +2 -0
- bear_utils/files/file_handlers/_base_file_handler.py +23 -3
- bear_utils/files/file_handlers/file_handler_factory.py +38 -38
- bear_utils/files/file_handlers/json_file_handler.py +49 -22
- bear_utils/files/file_handlers/log_file_handler.py +19 -12
- bear_utils/files/file_handlers/toml_file_handler.py +13 -5
- bear_utils/files/file_handlers/txt_file_handler.py +56 -14
- bear_utils/files/file_handlers/yaml_file_handler.py +19 -13
- bear_utils/files/ignore_parser.py +52 -57
- bear_utils/graphics/__init__.py +3 -1
- bear_utils/graphics/bear_gradient.py +17 -12
- bear_utils/graphics/image_helpers.py +11 -5
- bear_utils/gui/__init__.py +3 -1
- bear_utils/gui/gui_tools/__init__.py +3 -1
- bear_utils/gui/gui_tools/_settings.py +0 -1
- bear_utils/gui/gui_tools/qt_app.py +16 -11
- bear_utils/gui/gui_tools/qt_color_picker.py +24 -13
- bear_utils/gui/gui_tools/qt_file_handler.py +30 -38
- bear_utils/gui/gui_tools/qt_input_dialog.py +11 -14
- bear_utils/logging/__init__.py +6 -4
- bear_utils/logging/logger_manager/__init__.py +1 -0
- bear_utils/logging/logger_manager/_common.py +0 -1
- bear_utils/logging/logger_manager/_console_junk.py +15 -11
- bear_utils/logging/logger_manager/_styles.py +1 -2
- bear_utils/logging/logger_manager/loggers/__init__.py +1 -0
- bear_utils/logging/logger_manager/loggers/_base_logger.py +33 -33
- bear_utils/logging/logger_manager/loggers/_base_logger.pyi +6 -5
- bear_utils/logging/logger_manager/loggers/_buffer_logger.py +2 -3
- bear_utils/logging/logger_manager/loggers/_console_logger.py +54 -26
- bear_utils/logging/logger_manager/loggers/_console_logger.pyi +7 -21
- bear_utils/logging/logger_manager/loggers/_file_logger.py +20 -13
- bear_utils/logging/logger_manager/loggers/_level_sin.py +15 -15
- bear_utils/logging/logger_manager/loggers/_logger.py +4 -6
- bear_utils/logging/logger_manager/loggers/_sub_logger.py +16 -23
- bear_utils/logging/logger_manager/loggers/_sub_logger.pyi +4 -19
- bear_utils/logging/loggers.py +9 -13
- bear_utils/monitoring/__init__.py +7 -4
- bear_utils/monitoring/_common.py +28 -0
- bear_utils/monitoring/host_monitor.py +44 -48
- bear_utils/time/__init__.py +13 -6
- {bear_utils-0.7.21.dist-info → bear_utils-0.7.22.dist-info}/METADATA +50 -6
- bear_utils-0.7.22.dist-info/RECORD +83 -0
- bear_utils-0.7.21.dist-info/RECORD +0 -79
- {bear_utils-0.7.21.dist-info → bear_utils-0.7.22.dist-info}/WHEEL +0 -0
@@ -1,27 +1,29 @@
|
|
1
1
|
# region Imports
|
2
|
+
from contextlib import suppress
|
2
3
|
from functools import cached_property
|
3
4
|
from logging import DEBUG, Formatter, Handler, Logger
|
4
5
|
from logging.handlers import QueueHandler, QueueListener, RotatingFileHandler
|
5
6
|
from queue import Queue
|
6
|
-
from typing import override
|
7
|
+
from typing import TYPE_CHECKING, override
|
7
8
|
|
8
9
|
from prompt_toolkit import PromptSession
|
9
10
|
from rich.text import Text
|
10
11
|
from rich.theme import Theme
|
11
|
-
from rich.traceback import Traceback
|
12
12
|
|
13
13
|
from bear_utils.constants.date_related import DATE_TIME_FORMAT
|
14
|
+
from bear_utils.logging.logger_manager._common import FIVE_MEGABYTES, VERBOSE_CONSOLE_FORMAT, VERBOSE_FORMAT, ExecValues
|
15
|
+
from bear_utils.logging.logger_manager._console_junk import ConsoleBuffering, ConsoleFormatter, ConsoleHandler
|
14
16
|
|
15
|
-
from .._common import FIVE_MEGABYTES, VERBOSE_CONSOLE_FORMAT, VERBOSE_FORMAT, ExecValues
|
16
|
-
from .._console_junk import ConsoleBuffering, ConsoleFormatter, ConsoleHandler
|
17
17
|
from ._base_logger import BaseLogger
|
18
18
|
|
19
|
+
if TYPE_CHECKING:
|
20
|
+
from rich.traceback import Traceback
|
21
|
+
|
19
22
|
# endregion Imports
|
20
23
|
|
21
24
|
|
22
25
|
class ConsoleLogger(Logger, BaseLogger):
|
23
|
-
"""
|
24
|
-
A comprehensive console logger that combines Python's logging framework with Rich console styling.
|
26
|
+
"""A comprehensive console logger that combines Python's logging framework with Rich console styling.
|
25
27
|
|
26
28
|
This logger provides styled console output with configurable file logging, queue handling,
|
27
29
|
buffering, and interactive input capabilities. It dynamically creates logging methods
|
@@ -53,7 +55,7 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
53
55
|
file: bool = False,
|
54
56
|
queue_handler: bool = False,
|
55
57
|
buffering: bool = False,
|
56
|
-
*
|
58
|
+
*_,
|
57
59
|
**kwargs,
|
58
60
|
) -> None:
|
59
61
|
Logger.__init__(self, name=name, level=level)
|
@@ -82,7 +84,14 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
82
84
|
**kwargs,
|
83
85
|
)
|
84
86
|
|
85
|
-
def _handle_enable_booleans(
|
87
|
+
def _handle_enable_booleans(
|
88
|
+
self,
|
89
|
+
file: bool,
|
90
|
+
console: bool,
|
91
|
+
buffering: bool,
|
92
|
+
queue_handler: bool,
|
93
|
+
**kwargs,
|
94
|
+
) -> None:
|
86
95
|
"""Configure logging handlers based on initialization parameters."""
|
87
96
|
if console or buffering:
|
88
97
|
self.console_handler: ConsoleHandler = ConsoleHandler(self.print, self.output_buffer)
|
@@ -138,16 +147,16 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
138
147
|
if hasattr(self, "queue_handler"):
|
139
148
|
self.queue_handler.setLevel(level)
|
140
149
|
|
141
|
-
def _console_output(self, msg: object, extra, *args, **kwargs) -> None:
|
150
|
+
def _console_output(self, msg: object, extra: dict, *args, **kwargs) -> None:
|
142
151
|
"""Console-specific output handler that integrates with logging module."""
|
143
152
|
if not self.logger_mode:
|
144
153
|
self.print(msg, *args, **kwargs)
|
145
154
|
else:
|
146
155
|
kwargs.pop("style", None)
|
147
156
|
self.log(
|
148
|
-
|
149
|
-
msg
|
150
|
-
extra
|
157
|
+
extra.get("log_level", DEBUG),
|
158
|
+
msg,
|
159
|
+
extra,
|
151
160
|
*args,
|
152
161
|
**kwargs,
|
153
162
|
)
|
@@ -156,7 +165,7 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
156
165
|
|
157
166
|
# region Utility Methods
|
158
167
|
|
159
|
-
async def input(self, msg: str, style="info", **kwargs) -> str:
|
168
|
+
async def input(self, msg: str, style: str = "info", **kwargs) -> str:
|
160
169
|
"""Display a styled prompt and return user input asynchronously."""
|
161
170
|
if not self.session:
|
162
171
|
self.session = PromptSession(**kwargs)
|
@@ -164,7 +173,13 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
164
173
|
return await self.session.prompt_async()
|
165
174
|
|
166
175
|
def output_buffer(
|
167
|
-
self,
|
176
|
+
self,
|
177
|
+
msg: object,
|
178
|
+
end: str = "\n",
|
179
|
+
exc_info: str | None = None,
|
180
|
+
exec_values: ExecValues | None = None,
|
181
|
+
*_,
|
182
|
+
**kwargs,
|
168
183
|
) -> str:
|
169
184
|
"""Capture console output to a string buffer without printing to terminal."""
|
170
185
|
if exc_info and exec_values:
|
@@ -179,20 +194,25 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
179
194
|
|
180
195
|
# region Enhanced Print Methods
|
181
196
|
|
182
|
-
def print(
|
183
|
-
|
184
|
-
|
197
|
+
def print(
|
198
|
+
self,
|
199
|
+
msg: object,
|
200
|
+
end: str = "\n",
|
201
|
+
exc_info: str | None = None,
|
202
|
+
extra: dict | None = None,
|
203
|
+
*args,
|
204
|
+
**kwargs,
|
205
|
+
) -> None | str:
|
206
|
+
"""Print styled messages with enhanced exception handling and JSON support.
|
185
207
|
|
186
208
|
Extends the base print method with proper exception tracebacks and
|
187
209
|
integrated JSON printing for structured data output.
|
188
210
|
"""
|
189
211
|
if exc_info is not None:
|
190
|
-
|
212
|
+
with suppress(ValueError):
|
191
213
|
self._print(self._get_exception(), end=end, width=100, show_locals=True, **kwargs)
|
192
|
-
except ValueError:
|
193
|
-
...
|
194
214
|
|
195
|
-
self._print(msg, end
|
215
|
+
self._print(msg, end, *args, **kwargs)
|
196
216
|
|
197
217
|
if extra:
|
198
218
|
self._print(msg=extra, end=end, json=True, indent=4)
|
@@ -203,9 +223,17 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
203
223
|
return self.stack_tracker.record_end()
|
204
224
|
|
205
225
|
@override
|
206
|
-
def _log(
|
207
|
-
|
208
|
-
|
226
|
+
def _log( # type: ignore[override]
|
227
|
+
self,
|
228
|
+
level: int,
|
229
|
+
msg: object,
|
230
|
+
args: tuple,
|
231
|
+
exc_info: str | None = None,
|
232
|
+
extra: dict | None = None,
|
233
|
+
stack_info: bool = False,
|
234
|
+
stacklevel: int | None = None,
|
235
|
+
) -> None:
|
236
|
+
"""Custom logging implementation with enhanced exception handling.
|
209
237
|
|
210
238
|
Overrides the standard logging._log method to provide better exception
|
211
239
|
value extraction for Rich traceback integration while respecting log levels.
|
@@ -219,8 +247,8 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
219
247
|
final_extra = extra or {}
|
220
248
|
|
221
249
|
if exc_info is not None:
|
222
|
-
exec_values = self._extract_exception_values(exc_info)
|
223
|
-
if exec_values:
|
250
|
+
exec_values: ExecValues | None = self._extract_exception_values(exc_info)
|
251
|
+
if exec_values is not None:
|
224
252
|
final_extra = {**final_extra, "exec_values": exec_values}
|
225
253
|
|
226
254
|
record = self.makeRecord(
|
@@ -1,16 +1,16 @@
|
|
1
|
-
from logging import
|
1
|
+
from logging import Logger
|
2
2
|
from logging.handlers import QueueHandler, RotatingFileHandler
|
3
3
|
from typing import Any
|
4
4
|
|
5
5
|
from rich.text import Text
|
6
6
|
from rich.theme import Theme
|
7
7
|
|
8
|
-
from
|
8
|
+
from bear_utils.logging.logger_manager._console_junk import ConsoleBuffering, ConsoleHandler
|
9
|
+
|
9
10
|
from ._base_logger import BaseLogger
|
10
11
|
from ._sub_logger import SubConsoleLogger
|
11
12
|
|
12
13
|
class ConsoleLogger(Logger, BaseLogger):
|
13
|
-
|
14
14
|
name: str
|
15
15
|
level: int
|
16
16
|
file: bool
|
@@ -18,13 +18,13 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
18
18
|
buffer_handler: ConsoleBuffering
|
19
19
|
console_handler: ConsoleHandler
|
20
20
|
file_handler: RotatingFileHandler
|
21
|
-
sub_logger: dict[str,
|
21
|
+
sub_logger: dict[str, SubConsoleLogger[ConsoleLogger]]
|
22
22
|
|
23
23
|
def __init__(
|
24
24
|
self,
|
25
25
|
theme: Theme | None = None,
|
26
26
|
name: str = "ConsoleLogger",
|
27
|
-
level: int =
|
27
|
+
level: int = ...,
|
28
28
|
disabled: bool = True,
|
29
29
|
queue_handler: bool = False,
|
30
30
|
buffering: bool = False,
|
@@ -34,21 +34,7 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
34
34
|
logger_mode: bool = True,
|
35
35
|
*args,
|
36
36
|
**kwargs,
|
37
|
-
) -> None:
|
38
|
-
"""
|
39
|
-
A general purpose console logger that that by default is a wrapper around both Rich and Python's logging module.
|
40
|
-
|
41
|
-
Args:
|
42
|
-
theme (Theme | None): The theme for the logger.
|
43
|
-
name (str): The name of the logger.
|
44
|
-
level (int): The logging level.
|
45
|
-
disabled (bool): Whether the logger is disabled.
|
46
|
-
queue_handler (bool): Whether to use a queue handler.
|
47
|
-
buffering (bool): Whether to use buffering.
|
48
|
-
file (bool): Whether to log to a file.
|
49
|
-
style_disabled (bool): Whether to disable styling.
|
50
|
-
logger_mode (bool): Whether to enable logger mode.
|
51
|
-
"""
|
37
|
+
) -> None: ...
|
52
38
|
# fmt: off
|
53
39
|
def debug(self, msg: object, *args, **kwargs: Any) -> None: ...
|
54
40
|
def info(self, msg: object, *args, **kwargs: Any) -> None: ...
|
@@ -60,5 +46,5 @@ class ConsoleLogger(Logger, BaseLogger):
|
|
60
46
|
def set_base_level(self, level: int) -> None: ...
|
61
47
|
def input(self, msg: str, style: str = "info") -> str: ...
|
62
48
|
def trigger_buffer_flush(self) -> str | Text: ...
|
63
|
-
def print(self, msg: object, end: str="\n", exc_info=None, extra: dict | None = None, *args, **kwargs) -> None | str: ...
|
49
|
+
def print(self, msg: object, end: str="\n", exc_info:str|None=None, extra: dict | None = None, *args, **kwargs) -> None | str: ...
|
64
50
|
def exit(self) -> None: ...
|
@@ -1,20 +1,20 @@
|
|
1
1
|
from logging import DEBUG
|
2
2
|
from pathlib import Path
|
3
|
-
from typing import Any, override
|
3
|
+
from typing import TYPE_CHECKING, Any, override
|
4
4
|
|
5
5
|
from rich.theme import Theme
|
6
6
|
|
7
|
-
from bear_utils.
|
7
|
+
from bear_utils.logging.logger_manager._common import FIVE_MEGABYTES
|
8
8
|
|
9
|
-
from .._common import FIVE_MEGABYTES
|
10
|
-
from .._styles import LoggerExtraInfo
|
11
9
|
from ._console_logger import ConsoleLogger
|
12
10
|
from ._sub_logger import SubConsoleLogger
|
13
11
|
|
12
|
+
if TYPE_CHECKING:
|
13
|
+
from bear_utils.logging.logger_manager._styles import LoggerExtraInfo
|
14
|
+
|
14
15
|
|
15
16
|
class FileLogger(ConsoleLogger):
|
16
|
-
"""
|
17
|
-
A file-based logger that writes styled log messages to files.
|
17
|
+
"""A file-based logger that writes styled log messages to files.
|
18
18
|
|
19
19
|
Combines Python's logging framework with Rich console styling, but outputs
|
20
20
|
to files instead of console. Supports file rotation, custom formatting,
|
@@ -47,7 +47,7 @@ class FileLogger(ConsoleLogger):
|
|
47
47
|
file_path: str = "app.log",
|
48
48
|
max_bytes: int = FIVE_MEGABYTES,
|
49
49
|
backup_count: int = 5,
|
50
|
-
*
|
50
|
+
*_,
|
51
51
|
**kwargs,
|
52
52
|
) -> None:
|
53
53
|
self.file_path = Path(file_path) # TODO: Add more options for filename patterns (timestamps, process IDs, etc.)
|
@@ -85,16 +85,23 @@ class FileLogger(ConsoleLogger):
|
|
85
85
|
self.stack_tracker.record_start()
|
86
86
|
|
87
87
|
self.log(
|
88
|
-
|
89
|
-
msg
|
90
|
-
extra
|
88
|
+
extra.get("log_level", DEBUG),
|
89
|
+
msg,
|
90
|
+
extra,
|
91
91
|
*args,
|
92
92
|
**kwargs,
|
93
93
|
)
|
94
94
|
|
95
|
-
def print(
|
96
|
-
|
97
|
-
|
95
|
+
def print(
|
96
|
+
self,
|
97
|
+
msg: object,
|
98
|
+
_: str = "\n",
|
99
|
+
exc_info: str | None = None,
|
100
|
+
extra: dict | None = None,
|
101
|
+
*__,
|
102
|
+
**___,
|
103
|
+
) -> None:
|
104
|
+
"""Print a message to the file with proper formatting.
|
98
105
|
|
99
106
|
Maintains the same interface as other loggers but writes to file instead of console.
|
100
107
|
"""
|
@@ -1,5 +1,5 @@
|
|
1
|
-
import threading
|
2
1
|
from logging import addLevelName
|
2
|
+
import threading
|
3
3
|
from typing import Literal
|
4
4
|
|
5
5
|
ERROR: Literal[40] = 40
|
@@ -9,14 +9,14 @@ INFO: Literal[20] = 20
|
|
9
9
|
DEBUG: Literal[10] = 10
|
10
10
|
NOTSET: Literal[0] = 0
|
11
11
|
|
12
|
-
|
12
|
+
level_to_name = {
|
13
13
|
ERROR: "ERROR",
|
14
14
|
WARNING: "WARNING",
|
15
15
|
INFO: "INFO",
|
16
16
|
DEBUG: "DEBUG",
|
17
17
|
NOTSET: "NOTSET",
|
18
18
|
}
|
19
|
-
|
19
|
+
name_to_level = {
|
20
20
|
"ERROR": ERROR,
|
21
21
|
"WARN": WARNING,
|
22
22
|
"WARNING": WARNING,
|
@@ -32,27 +32,27 @@ def lvl_exists(level: int | str) -> bool:
|
|
32
32
|
"""Check if a logging level already exists."""
|
33
33
|
with _lock:
|
34
34
|
level = check_level(level, fail=False)
|
35
|
-
return level in
|
35
|
+
return level in level_to_name
|
36
36
|
|
37
37
|
|
38
38
|
def add_level_name(level: int, name: str) -> None:
|
39
39
|
"""Add a custom logging level name."""
|
40
40
|
with _lock:
|
41
|
-
if level in
|
42
|
-
raise ValueError(f"Level {level} already exists with name {
|
43
|
-
|
44
|
-
|
45
|
-
addLevelName(level, name)
|
41
|
+
if level in level_to_name:
|
42
|
+
raise ValueError(f"Level {level} already exists with name {level_to_name[level]}")
|
43
|
+
level_to_name[level] = name.upper()
|
44
|
+
name_to_level[name.upper()] = level
|
45
|
+
addLevelName(level=level, levelName=name)
|
46
46
|
|
47
47
|
|
48
|
-
def check_level(level: int | str, fail: bool = True) -> int:
|
48
|
+
def check_level(level: int | str | None, fail: bool = True) -> int:
|
49
49
|
"""Validate and normalize logging level to integer."""
|
50
|
-
if isinstance(level, str) and level.upper() in
|
51
|
-
return
|
52
|
-
if isinstance(level, int) and level in
|
50
|
+
if isinstance(level, str) and level.upper() in name_to_level:
|
51
|
+
return name_to_level[level.upper()]
|
52
|
+
if isinstance(level, int) and level in level_to_name:
|
53
53
|
return level
|
54
54
|
if fail:
|
55
|
-
if not isinstance(level, (int
|
55
|
+
if not isinstance(level, (int | str)):
|
56
56
|
raise TypeError(f"Level must be int or str, got {type(level).__name__}: {level!r}")
|
57
|
-
raise ValueError(f"Invalid logging level: {level!r}. Valid levels are: {list(
|
57
|
+
raise ValueError(f"Invalid logging level: {level!r}. Valid levels are: {list(name_to_level.keys())}")
|
58
58
|
return 999 # Return a high value to indicate invalid level
|
@@ -4,15 +4,13 @@ from ._base_logger import BaseLogger
|
|
4
4
|
|
5
5
|
|
6
6
|
class ExtraBaseLogger(Logger, BaseLogger):
|
7
|
-
"""
|
8
|
-
|
7
|
+
"""Base logger class that extends the standard logging.Logger and BaseLogger.
|
8
|
+
|
9
9
|
This class is intended to be used as a base for custom loggers that require
|
10
10
|
additional functionality or attributes.
|
11
11
|
"""
|
12
12
|
|
13
|
-
def __init__(self, name, level=0, **kwargs):
|
14
|
-
"""
|
15
|
-
Initialize the ExtraBaseLogger with a name and level.
|
16
|
-
"""
|
13
|
+
def __init__(self, name: str, level: int = 0, **kwargs):
|
14
|
+
"""Initialize the ExtraBaseLogger with a name and level."""
|
17
15
|
super().__init__(name, level)
|
18
16
|
BaseLogger.__init__(self, **kwargs)
|
@@ -1,5 +1,4 @@
|
|
1
|
-
"""
|
2
|
-
Logger adapter module that provides an alternative to SubLogger using standard library tools.
|
1
|
+
"""Logger adapter module that provides an alternative to SubLogger using standard library tools.
|
3
2
|
|
4
3
|
This implementation shows how to use LoggerAdapter and contextvars to maintain
|
5
4
|
all the functionality of the existing SubLogger while reducing complexity.
|
@@ -10,26 +9,26 @@ from typing import TYPE_CHECKING, Any, Generic, TypeVar
|
|
10
9
|
|
11
10
|
from rich.text import Text
|
12
11
|
|
13
|
-
from
|
12
|
+
from bear_utils.logging.logger_manager._styles import LOGGER_METHODS, LoggerExtraInfo
|
13
|
+
|
14
14
|
from ._level_sin import check_level
|
15
15
|
|
16
16
|
if TYPE_CHECKING:
|
17
17
|
from ._base_logger import BaseLogger
|
18
18
|
|
19
|
-
|
19
|
+
_T = TypeVar("_T", bound="BaseLogger")
|
20
20
|
|
21
21
|
|
22
|
-
class SubConsoleLogger(Generic[
|
23
|
-
def __init__(self, logger:
|
24
|
-
"""
|
25
|
-
Initialize the SubConsoleLogger with a logger and a namespace.
|
22
|
+
class SubConsoleLogger(Generic[_T]): # noqa: UP046
|
23
|
+
def __init__(self, logger: _T, namespace: str, **kwargs) -> None:
|
24
|
+
"""Initialize the SubConsoleLogger with a logger and a namespace.
|
26
25
|
|
27
26
|
Args:
|
28
27
|
logger: The underlying logger to wrap with a namespace.
|
29
28
|
namespace: The namespace to prefix log messages with
|
30
29
|
"""
|
31
|
-
self.logger:
|
32
|
-
self._level: int = kwargs.get("level"
|
30
|
+
self.logger: _T = logger
|
31
|
+
self._level: int = kwargs.get("level") or logger._level
|
33
32
|
self.logger_mode = logger.logger_mode
|
34
33
|
self.namespace: str = namespace
|
35
34
|
self._setup(self.namespace)
|
@@ -40,27 +39,24 @@ class SubConsoleLogger(Generic[T]):
|
|
40
39
|
end: str = "\n",
|
41
40
|
exc_info: Any = None,
|
42
41
|
extra: dict | None = None,
|
43
|
-
*
|
42
|
+
*_,
|
44
43
|
**kwargs,
|
45
44
|
) -> None | str:
|
46
|
-
"""
|
47
|
-
Print a message to the console with the specified formatting.
|
45
|
+
"""Print a message to the console with the specified formatting.
|
48
46
|
|
49
47
|
This method allows for printing messages with additional context and formatting.
|
50
48
|
"""
|
51
49
|
return self.logger.print(msg, end=end, exc_info=exc_info, extra=extra, **kwargs)
|
52
50
|
|
53
51
|
def set_sub_level(self, level: int) -> None:
|
54
|
-
"""
|
55
|
-
Set the logging level for the logger.
|
52
|
+
"""Set the logging level for the logger.
|
56
53
|
|
57
54
|
This method allows changing the logging level dynamically.
|
58
55
|
"""
|
59
56
|
self._level = level
|
60
57
|
|
61
58
|
def filter_by_level(self, level: int | str) -> bool:
|
62
|
-
"""
|
63
|
-
Filter method to determine if a message should be logged based on its level.
|
59
|
+
"""Filter method to determine if a message should be logged based on its level.
|
64
60
|
|
65
61
|
This method checks if the provided level is greater than or equal to the logger's level.
|
66
62
|
|
@@ -71,12 +67,10 @@ class SubConsoleLogger(Generic[T]):
|
|
71
67
|
bool: True if the message should be logged, False otherwise.
|
72
68
|
"""
|
73
69
|
level = check_level(level)
|
74
|
-
|
75
|
-
return bool_check
|
70
|
+
return level >= self._level
|
76
71
|
|
77
72
|
def trigger_buffer_flush(self) -> str | Text:
|
78
|
-
"""
|
79
|
-
Flush buffered messages to console output.
|
73
|
+
"""Flush buffered messages to console output.
|
80
74
|
|
81
75
|
This method is used to ensure that any buffered log messages are printed
|
82
76
|
to the console, similar to the SubLogger's buffer flush functionality.
|
@@ -84,8 +78,7 @@ class SubConsoleLogger(Generic[T]):
|
|
84
78
|
return self.logger.trigger_buffer_flush()
|
85
79
|
|
86
80
|
def _setup(self, name: str) -> None:
|
87
|
-
"""
|
88
|
-
Get an attribute from the logger.
|
81
|
+
"""Get an attribute from the logger.
|
89
82
|
|
90
83
|
This allows for accessing logger methods directly.
|
91
84
|
"""
|
@@ -1,31 +1,17 @@
|
|
1
|
-
"""
|
2
|
-
Logger adapter module that provides an alternative to SubLogger using standard library tools.
|
3
|
-
|
4
|
-
This implementation shows how to use LoggerAdapter and contextvars to maintain
|
5
|
-
all the functionality of the existing SubLogger while reducing complexity.
|
6
|
-
"""
|
7
|
-
|
8
1
|
from typing import Any, Generic, TypeVar
|
9
2
|
|
10
3
|
from ._base_logger import BaseLogger
|
11
4
|
|
12
|
-
|
13
|
-
|
14
|
-
class SubConsoleLogger(Generic[T]):
|
15
|
-
"""
|
16
|
-
Enhanced logger adapter that supports style-based logging and namespace prefixing.
|
17
|
-
|
18
|
-
This class provides an alternative to the SubLogger implementation while
|
19
|
-
maintaining compatibility with the existing ConsoleLogger.
|
20
|
-
"""
|
5
|
+
_T = TypeVar("_T", bound=BaseLogger)
|
21
6
|
|
22
|
-
|
7
|
+
class SubConsoleLogger(Generic[_T]): # noqa: UP046
|
8
|
+
logger: _T
|
23
9
|
_level: int
|
24
10
|
namespace: str
|
25
11
|
extra: dict[str, Any] | None
|
26
12
|
log_level: int
|
27
13
|
# fmt: off
|
28
|
-
def __init__(self, logger:
|
14
|
+
def __init__(self, logger: _T, namespace: str, **kwargs) -> None: ...
|
29
15
|
def set_sub_level(self, level: int) -> None: ...
|
30
16
|
def success(self, msg: object, *args, **kwargs) -> None: ...
|
31
17
|
def failure(self, msg: object, *args, **kwargs) -> None: ...
|
@@ -35,4 +21,3 @@ class SubConsoleLogger(Generic[T]):
|
|
35
21
|
def warning(self, msg: object, *args, **kwargs) -> None: ...
|
36
22
|
def error(self, msg: object, *args, **kwargs) -> None: ...
|
37
23
|
def print(self, msg: object, end: str = "\n", exc_info: Any = None, extra: dict | None = None, *args, **kwargs: Any) -> None | str: ...
|
38
|
-
def __repr__(self) -> str: ...
|
bear_utils/logging/loggers.py
CHANGED
@@ -1,7 +1,5 @@
|
|
1
|
-
|
2
|
-
|
3
|
-
from .logger_manager._console_junk import ConsoleBuffering, ConsoleFormatter, ConsoleHandler
|
4
|
-
from .logger_manager._styles import DEFAULT_THEME, LOGGER_METHODS, VERBOSE, LoggerExtraInfo, get_method
|
1
|
+
"""A module for logging utilities."""
|
2
|
+
|
5
3
|
from .logger_manager.loggers._base_logger import BaseLogger
|
6
4
|
from .logger_manager.loggers._buffer_logger import BufferLogger
|
7
5
|
from .logger_manager.loggers._console_logger import ConsoleLogger
|
@@ -31,22 +29,21 @@ def get_logger(
|
|
31
29
|
style_disabled (bool): Whether to disable styling.
|
32
30
|
logger_mode (bool): Whether the logger is in logger mode.
|
33
31
|
**kwargs: Additional keyword arguments for customization.
|
32
|
+
|
34
33
|
Returns:
|
35
34
|
BaseLogger | ConsoleLogger | BufferLogger| FileLogger: An instance of the appropriate logger.
|
36
35
|
"""
|
37
36
|
if (not console and not file) and buffering:
|
38
37
|
return BufferLogger(queue_handler=queue_handler, **kwargs)
|
39
|
-
|
38
|
+
if (console and file) or (console and buffering):
|
40
39
|
return ConsoleLogger(queue_handler=queue_handler, buffering=buffering, **kwargs)
|
41
|
-
|
40
|
+
if not console and not buffering and file:
|
42
41
|
return FileLogger(queue_handler=queue_handler, **kwargs)
|
43
|
-
|
44
|
-
return BaseLogger(**kwargs)
|
42
|
+
return BaseLogger(**kwargs)
|
45
43
|
|
46
44
|
|
47
45
|
def get_console(namespace: str) -> tuple[BaseLogger, SubConsoleLogger]:
|
48
|
-
"""
|
49
|
-
Get a console logger and a sub-logger for a specific namespace.
|
46
|
+
"""Get a console logger and a sub-logger for a specific namespace.
|
50
47
|
|
51
48
|
Args:
|
52
49
|
namespace (str): The namespace for the sub-logger.
|
@@ -60,8 +57,7 @@ def get_console(namespace: str) -> tuple[BaseLogger, SubConsoleLogger]:
|
|
60
57
|
|
61
58
|
|
62
59
|
def get_sub_logger(logger: BaseLogger | ConsoleLogger, namespace: str) -> SubConsoleLogger[BaseLogger | ConsoleLogger]:
|
63
|
-
"""
|
64
|
-
Get a sub-logger for a specific namespace.
|
60
|
+
"""Get a sub-logger for a specific namespace.
|
65
61
|
|
66
62
|
Args:
|
67
63
|
logger (BaseLogger): The parent logger.
|
@@ -70,7 +66,7 @@ def get_sub_logger(logger: BaseLogger | ConsoleLogger, namespace: str) -> SubCon
|
|
70
66
|
Returns:
|
71
67
|
SubConsoleLogger: A sub-logger instance.
|
72
68
|
"""
|
73
|
-
if not isinstance(logger, (BaseLogger
|
69
|
+
if not isinstance(logger, (BaseLogger | ConsoleLogger)):
|
74
70
|
raise TypeError("Expected logger to be an instance of BaseLogger or ConsoleLogger")
|
75
71
|
|
76
72
|
return SubConsoleLogger(logger=logger, namespace=namespace)
|
@@ -1,10 +1,13 @@
|
|
1
|
-
|
1
|
+
"""A module for monitoring host system metrics."""
|
2
|
+
|
3
|
+
from ._common import CPU, DISK, GPU, MEM, TaskChoice
|
4
|
+
from .host_monitor import HostMonitor
|
2
5
|
|
3
6
|
__all__ = [
|
4
|
-
"TaskChoice",
|
5
|
-
"HostMonitor",
|
6
7
|
"CPU",
|
7
|
-
"MEM",
|
8
8
|
"DISK",
|
9
9
|
"GPU",
|
10
|
+
"MEM",
|
11
|
+
"HostMonitor",
|
12
|
+
"TaskChoice",
|
10
13
|
]
|
@@ -0,0 +1,28 @@
|
|
1
|
+
from __future__ import annotations
|
2
|
+
|
3
|
+
from enum import StrEnum
|
4
|
+
from typing import Literal
|
5
|
+
|
6
|
+
|
7
|
+
class TaskChoice(StrEnum):
|
8
|
+
"""Enum for task choices."""
|
9
|
+
|
10
|
+
CPU = "cpu"
|
11
|
+
MEM = "mem"
|
12
|
+
DISK = "disk"
|
13
|
+
GPU = "gpu"
|
14
|
+
|
15
|
+
|
16
|
+
CPU = TaskChoice.CPU
|
17
|
+
MEM = TaskChoice.MEM
|
18
|
+
DISK = TaskChoice.DISK
|
19
|
+
GPU = TaskChoice.GPU
|
20
|
+
|
21
|
+
CPU_MEM: tuple[Literal[TaskChoice.CPU], Literal[TaskChoice.MEM]] = (CPU, MEM)
|
22
|
+
CPU_MEM_GPU: tuple[Literal[TaskChoice.CPU], Literal[TaskChoice.MEM], Literal[TaskChoice.GPU]] = (CPU, MEM, GPU)
|
23
|
+
ALL_TASKS: tuple[
|
24
|
+
Literal[TaskChoice.CPU],
|
25
|
+
Literal[TaskChoice.MEM],
|
26
|
+
Literal[TaskChoice.DISK],
|
27
|
+
Literal[TaskChoice.GPU],
|
28
|
+
] = (CPU, MEM, DISK, GPU)
|