forked from Sollumz/Sollumz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlogger.py
85 lines (56 loc) · 2.01 KB
/
logger.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
"""
Logging module to easily log messages from operators that are extended into many functions.
"""
from bpy.types import Operator
from abc import ABC, abstractmethod
from typing import Sequence, Iterator
from collections import defaultdict
from contextlib import contextmanager
class LoggerBase(ABC):
@abstractmethod
def do_log(self, msg: str, level: str):
...
class ConsoleLogger(LoggerBase):
def do_log(self, msg: str, level: str):
print(f"{level}: {msg}")
class OperatorLogger(LoggerBase):
def __init__(self, operator: Operator):
assert operator is not None
self._operator = operator
self._num_logs: dict[str, int] = defaultdict(int)
def do_log(self, msg: str, level: str):
self._operator.report({level}, msg)
self._num_logs[level] += 1
@property
def has_warnings_or_errors(self) -> bool:
return self._num_logs["WARNING"] > 0 or self._num_logs["ERROR"] > 0
def clear_log_counts(self):
self._num_logs.clear()
class MultiLogger(LoggerBase):
def __init__(self, loggers: Sequence[LoggerBase]):
self._loggers: list[LoggerBase] = list(loggers)
def do_log(self, msg: str, level: str):
for logger in self._loggers:
logger.do_log(msg, level)
def add_logger(self, logger: LoggerBase):
self._loggers.append(logger)
def remove_logger(self, logger: LoggerBase):
self._loggers.remove(logger)
_root_logger: MultiLogger = MultiLogger([ConsoleLogger()])
def _log(msg: str, level: str):
_root_logger.do_log(msg, level)
@contextmanager
def use_logger(logger: LoggerBase) -> Iterator[LoggerBase]:
_root_logger.add_logger(logger)
try:
yield logger
finally:
_root_logger.remove_logger(logger)
def use_operator_logger(operator: Operator) -> Iterator[OperatorLogger]:
return use_logger(OperatorLogger(operator))
def info(msg: str):
_log(msg, "INFO")
def warning(msg: str):
_log(msg, "WARNING")
def error(msg: str):
_log(msg, "ERROR")