Skip to content

ColourizedFormatter

faststream.log.formatter.ColourizedFormatter #

ColourizedFormatter(fmt=None, datefmt=None, style='%', use_colors=None)

Bases: Formatter

A class to format log messages with colorized level names.

METHOD DESCRIPTION
__init__

Initialize the formatter with specified format strings.

formatMessage

Format the log record message with colorized level name.

Initialize the formatter with specified format strings.

Initialize the formatter either with the specified format string, or a default as described above. Allow for specialized date formatting with the optional datefmt argument. If datefmt is omitted, you get an ISO8601-like (or RFC 3339-like) format.

Use a style parameter of '%', '{' or '$' to specify that you want to use one of %-formatting, :meth:str.format ({}) formatting or :class:string.Template formatting in your format string.

Source code in faststream/log/formatter.py
def __init__(
    self,
    fmt: Optional[str] = None,
    datefmt: Optional[str] = None,
    style: Literal["%", "{", "$"] = "%",
    use_colors: Optional[bool] = None,
) -> None:
    """Initialize the formatter with specified format strings.

    Initialize the formatter either with the specified format string, or a
    default as described above. Allow for specialized date formatting with
    the optional datefmt argument. If datefmt is omitted, you get an
    ISO8601-like (or RFC 3339-like) format.

    Use a style parameter of '%', '{' or '$' to specify that you want to
    use one of %-formatting, :meth:`str.format` (``{}``) formatting or
    :class:`string.Template` formatting in your format string.
    """
    if use_colors in (True, False):
        self.use_colors = use_colors
    else:
        self.use_colors = sys.stdout.isatty()
    super().__init__(fmt=fmt, datefmt=datefmt, style=style)

use_colors instance-attribute #

use_colors = use_colors

formatMessage #

formatMessage(record)

Formats the log message.

PARAMETER DESCRIPTION
record

The log record to format.

TYPE: LogRecord

RETURNS DESCRIPTION
str

The formatted log message.

TYPE: str

Source code in faststream/log/formatter.py
def formatMessage(self, record: logging.LogRecord) -> str:  # noqa: N802
    """Formats the log message.

    Args:
        record (logging.LogRecord): The log record to format.

    Returns:
        str: The formatted log message.
    """
    if self.use_colors:
        record.levelname = expand_log_field(
            field=COLORED_LEVELS.get(record.levelno, record.levelname),
            symbols=17,
        )

    return super().formatMessage(record)