UniLogger(
output_dir: str = "logs",
file_suffix: str = "log",
verbose: bool = False,
logger_name: str = None,
write_log: bool = True,
shorten_levels: int = 2,
use_color: bool = True,
)
A logger that:
1) Uses colorlog for console color.
2) Writes an optional log file without color.
3) Shows the caller's class and method.
4) Conditionally includes file paths for specific log levels.
5) Detects if console supports color and allows disabling colors.
Methods:
-
log
–
Log with custom formatting based on log level.
Source code in src/unibox/utils/logger.py
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 | def __init__(
self,
output_dir: str = "logs",
file_suffix: str = "log",
verbose: bool = False,
logger_name: str = None,
write_log: bool = True,
shorten_levels: int = 2, # how many path parts to show for debug logs
use_color: bool = True, # manually enable/disable color
):
self.verbose = verbose
self.write_log = write_log
self.shorten_levels = shorten_levels
# Determine if console supports color
self.supports_color = self._detect_color_support() if use_color else False
self.logger = logging.getLogger(logger_name if logger_name else self.__class__.__name__)
self.logger.setLevel(logging.DEBUG if verbose else logging.INFO)
# Prepare handlers
self.handlers = []
# Optional file handler
if self.write_log:
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
log_file = output_path / f"{file_suffix}_{datetime.now().strftime('%Y%m%d')}.log"
fh = logging.FileHandler(log_file, mode="a", encoding="utf-8")
self.handlers.append(fh)
# Console handler
ch = logging.StreamHandler(sys.stdout)
self.handlers.append(ch)
# Add handlers to logger
if not self.logger.hasHandlers():
for h in self.handlers:
self.logger.addHandler(h)
self._setup_formatters()
|
log
log(level_name: str, message: str)
Log with custom formatting based on log level.
Source code in src/unibox/utils/logger.py
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159 | def log(self, level_name: str, message: str):
"""Log with custom formatting based on log level."""
level = getattr(logging, level_name.upper(), logging.INFO)
# Skip frames to find real caller
caller_frame = inspect.currentframe().f_back.f_back
method_name = caller_frame.f_code.co_name
class_name = None
if "self" in caller_frame.f_locals:
class_name = caller_frame.f_locals["self"].__class__.__name__
if class_name:
full_func_name = f"{class_name}.{method_name}"
else:
full_func_name = method_name
full_path = os.path.abspath(caller_frame.f_code.co_filename)
short_path = self._shorten_path(full_path, self.shorten_levels)
lineno = caller_frame.f_lineno
# Conditionally include the path for debug, warning, error, critical levels
if level in [logging.DEBUG, logging.WARNING, logging.ERROR, logging.CRITICAL]:
extra_path = f" {short_path}:{lineno}"
else:
extra_path = ""
# Provide custom fields in `extra`
extra = {
"my_func": full_func_name,
"my_lineno": lineno,
"extra_path": extra_path,
}
# Log using extra fields
self.logger.log(level, message, extra=extra)
|