Coverage for faststream / _internal / logger / formatter.py: 94%
13 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-08 01:48 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-05-08 01:48 +0000
1import logging
2import sys
3from typing import Literal
5COLORED_LEVELS = {
6 logging.DEBUG: "\033[36mDEBUG\033[0m",
7 logging.INFO: "\033[32mINFO\033[0m",
8 logging.WARNING: "\033[33mWARNING\033[0m",
9 logging.ERROR: "\033[31mERROR\033[0m",
10 logging.CRITICAL: "\033[91mCRITICAL\033[0m",
11}
14class ColourizedFormatter(logging.Formatter):
15 """A class to format log messages with colorized level names.
17 Methods:
18 __init__ : Initialize the formatter with specified format strings.
19 formatMessage : Format the log record message with colorized level name.
20 """
22 def __init__(
23 self,
24 fmt: str | None = None,
25 datefmt: str | None = None,
26 style: Literal["%", "{", "$"] = "%",
27 use_colors: bool | None = None,
28 ) -> None:
29 """Initialize the formatter with specified format strings.
31 Initialize the formatter either with the specified format string, or a
32 default as described above. Allow for specialized date formatting with
33 the optional datefmt argument. If datefmt is omitted, you get an
34 ISO8601-like (or RFC 3339-like) format.
36 Use a style parameter of '%', '{' or '$' to specify that you want to
37 use one of %-formatting, :meth:`str.format` (``{}``) formatting or
38 :class:`string.Template` formatting in your format string.
39 """
40 if use_colors in {True, False}:
41 self.use_colors = use_colors
42 else:
43 self.use_colors = sys.stdout.isatty()
44 super().__init__(fmt=fmt, datefmt=datefmt, style=style)
46 def formatMessage(self, record: logging.LogRecord) -> str: # noqa: N802
47 """Formats the log message.
49 Args:
50 record (logging.LogRecord): The log record to format.
52 Returns:
53 str: The formatted log message.
54 """
55 if self.use_colors: 55 ↛ 61line 55 didn't jump to line 61 because the condition on line 55 was always true
56 record.levelname = expand_log_field(
57 field=COLORED_LEVELS.get(record.levelno, record.levelname),
58 symbols=17,
59 )
61 return super().formatMessage(record)
64def expand_log_field(field: str, symbols: int) -> str:
65 """Expands a log field by adding spaces.
67 Args:
68 field: The log field to expand.
69 symbols: The desired length of the expanded field.
71 Returns:
72 The expanded log field.
73 """
74 return field + (" " * (symbols - len(field)))