Coverage for seedboxsync/core/logger.py: 100%
15 statements
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-26 17:46 +0000
« prev ^ index » next coverage.py v7.15.2, created at 2026-07-26 17:46 +0000
1#
2# Copyright (C) 2015-2026 Guillaume Kulakowski <guillaume@kulakowski.fr>
3#
4# For the full copyright and license information, please view the LICENSE
5# file that was distributed with this source code.
6"""Setup logger for Flask."""
8import logging
9from typing import ClassVar
10import click
13class ColorFormatter(logging.Formatter):
14 """Format log records with colors based on their level."""
16 COLORS: ClassVar[dict[int, str]] = {
17 logging.DEBUG: "bright_black",
18 logging.INFO: "blue",
19 logging.WARNING: "yellow",
20 logging.ERROR: "red",
21 logging.CRITICAL: "bright_red",
22 }
24 def format(self, record: logging.LogRecord) -> str:
25 """
26 Format a log record and apply a color based on its log level.
28 Args:
29 record: The log record to format.
31 Returns:
32 str: The formatted and colorized log message.
33 """
34 message = super().format(record)
35 color = self.COLORS.get(record.levelno)
37 if color is None:
38 return message
40 return click.style(message, fg=color)
43def configure_logger(logger: logging.Logger) -> None:
44 """
45 Configure the logger by applying the custom formatter to all existing handlers.
47 Args:
48 logger: The logger to configure.
49 """
50 formatter = ColorFormatter(
51 fmt="%(asctime)s [%(levelname)-8s] [%(module)s] %(message)s",
52 datefmt="%H:%M:%S",
53 )
55 for handler in logger.handlers:
56 handler.setFormatter(formatter)