Skip to content

logger

Classes:

UniLogger

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
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
86
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:
        # Use resolved log directory if default output_dir is used
        if output_dir == "logs":
            log_dir = _resolve_log_dir()
        else:
            log_dir = output_dir

        os.makedirs(log_dir, exist_ok=True)
        log_file = os.path.join(log_dir, 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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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)