Skip to content

vllm.logging_utils

Modules:

Name Description
access_log_filter

Access log filter for uvicorn to exclude specific endpoints from logging.

dump_input
formatter
lazy
log_time

Provides a timeslice logging decorator

__all__ module-attribute

__all__ = [
    "NewLineFormatter",
    "ColoredFormatter",
    "UvicornAccessLogFilter",
    "create_uvicorn_log_config",
    "lazy",
    "logtime",
]

ColoredFormatter

Bases: NewLineFormatter

Adds ANSI color codes to log levels for terminal output.

This formatter adds colors by injecting them into the format string for static elements (timestamp, filename, line number) and modifying the levelname attribute for dynamic color selection.

Source code in vllm/logging_utils/formatter.py
class ColoredFormatter(NewLineFormatter):
    """Adds ANSI color codes to log levels for terminal output.

    This formatter adds colors by injecting them into the format string for
    static elements (timestamp, filename, line number) and modifying the
    levelname attribute for dynamic color selection.
    """

    # ANSI color codes
    COLORS = {
        "DEBUG": "\033[37m",  # White
        "INFO": "\033[32m",  # Green
        "WARNING": "\033[33m",  # Yellow
        "ERROR": "\033[31m",  # Red
        "CRITICAL": "\033[35m",  # Magenta
    }
    GREY = "\033[90m"  # Grey for timestamp and file info
    RESET = "\033[0m"

    def __init__(self, fmt, datefmt=None, style="%"):
        # Inject grey color codes into format string for timestamp and file info
        if fmt:
            # Wrap %(asctime)s with grey
            fmt = fmt.replace("%(asctime)s", f"{self.GREY}%(asctime)s{self.RESET}")
            # Wrap [%(fileinfo)s:%(lineno)d] with grey
            fmt = fmt.replace(
                "[%(fileinfo)s:%(lineno)d]",
                f"{self.GREY}[%(fileinfo)s:%(lineno)d]{self.RESET}",
            )

        # Call parent __init__ with potentially modified format string
        super().__init__(fmt, datefmt, style)

    def format(self, record):
        # Store original levelname to restore later (in case record is reused)
        orig_levelname = record.levelname

        # Only modify levelname - it needs dynamic color based on severity
        if (color_code := self.COLORS.get(record.levelname)) is not None:
            record.levelname = f"{color_code}{record.levelname}{self.RESET}"

        # Call parent format which will handle everything else
        msg = super().format(record)

        # Restore original levelname
        record.levelname = orig_levelname

        return msg

COLORS class-attribute instance-attribute

COLORS = {
    "DEBUG": "\x1b[37m",
    "INFO": "\x1b[32m",
    "WARNING": "\x1b[33m",
    "ERROR": "\x1b[31m",
    "CRITICAL": "\x1b[35m",
}

GREY class-attribute instance-attribute

GREY = '\x1b[90m'

RESET class-attribute instance-attribute

RESET = '\x1b[0m'

__init__

__init__(fmt, datefmt=None, style='%')
Source code in vllm/logging_utils/formatter.py
def __init__(self, fmt, datefmt=None, style="%"):
    # Inject grey color codes into format string for timestamp and file info
    if fmt:
        # Wrap %(asctime)s with grey
        fmt = fmt.replace("%(asctime)s", f"{self.GREY}%(asctime)s{self.RESET}")
        # Wrap [%(fileinfo)s:%(lineno)d] with grey
        fmt = fmt.replace(
            "[%(fileinfo)s:%(lineno)d]",
            f"{self.GREY}[%(fileinfo)s:%(lineno)d]{self.RESET}",
        )

    # Call parent __init__ with potentially modified format string
    super().__init__(fmt, datefmt, style)

format

format(record)
Source code in vllm/logging_utils/formatter.py
def format(self, record):
    # Store original levelname to restore later (in case record is reused)
    orig_levelname = record.levelname

    # Only modify levelname - it needs dynamic color based on severity
    if (color_code := self.COLORS.get(record.levelname)) is not None:
        record.levelname = f"{color_code}{record.levelname}{self.RESET}"

    # Call parent format which will handle everything else
    msg = super().format(record)

    # Restore original levelname
    record.levelname = orig_levelname

    return msg

NewLineFormatter

Bases: Formatter

Adds logging prefix to newlines to align multi-line messages.

Source code in vllm/logging_utils/formatter.py
class NewLineFormatter(logging.Formatter):
    """Adds logging prefix to newlines to align multi-line messages."""

    def __init__(self, fmt, datefmt=None, style="%"):
        super().__init__(fmt, datefmt, style)

        self.use_relpath = envs.VLLM_LOGGING_LEVEL == "DEBUG"
        if self.use_relpath:
            self.root_dir = Path(__file__).resolve().parent.parent.parent

    def format(self, record):
        def shrink_path(relpath: Path) -> str:
            """
            Shortens a file path for logging display:
            - Removes leading 'vllm' folder if present.
            - If path starts with 'v1',
            keeps the first two and last two levels,
            collapsing the middle as '...'.
            - Otherwise, keeps the first and last two levels,
            collapsing the middle as '...'.
            - If the path is short, returns it as-is.
            - Examples:
            vllm/model_executor/layers/quantization/utils/fp8_utils.py ->
            model_executor/.../quantization/utils/fp8_utils.py
            vllm/model_executor/layers/quantization/awq.py ->
            model_executor/layers/quantization/awq.py

            Args:
                relpath (Path): The relative path to be shortened.
            Returns:
                str: The shortened path string for display.
            """
            parts = list(relpath.parts)
            new_parts = []
            if parts and parts[0] == "vllm":
                parts = parts[1:]
            if parts and parts[0] == "v1":
                new_parts += parts[:2]
                parts = parts[2:]
            elif parts:
                new_parts += parts[:1]
                parts = parts[1:]
            if len(parts) > 2:
                new_parts += ["..."] + parts[-2:]
            else:
                new_parts += parts
            return "/".join(new_parts)

        if self.use_relpath:
            abs_path = getattr(record, "pathname", None)
            if abs_path:
                try:
                    relpath = Path(abs_path).resolve().relative_to(self.root_dir)
                except Exception:
                    relpath = Path(record.filename)
            else:
                relpath = Path(record.filename)
            record.fileinfo = shrink_path(relpath)
        else:
            record.fileinfo = record.filename

        msg = super().format(record)
        if record.message != "":
            parts = msg.split(record.message)
            msg = msg.replace("\n", "\r\n" + parts[0])
        return msg

root_dir instance-attribute

root_dir = parent

use_relpath instance-attribute

use_relpath = VLLM_LOGGING_LEVEL == 'DEBUG'

__init__

__init__(fmt, datefmt=None, style='%')
Source code in vllm/logging_utils/formatter.py
def __init__(self, fmt, datefmt=None, style="%"):
    super().__init__(fmt, datefmt, style)

    self.use_relpath = envs.VLLM_LOGGING_LEVEL == "DEBUG"
    if self.use_relpath:
        self.root_dir = Path(__file__).resolve().parent.parent.parent

format

format(record)
Source code in vllm/logging_utils/formatter.py
def format(self, record):
    def shrink_path(relpath: Path) -> str:
        """
        Shortens a file path for logging display:
        - Removes leading 'vllm' folder if present.
        - If path starts with 'v1',
        keeps the first two and last two levels,
        collapsing the middle as '...'.
        - Otherwise, keeps the first and last two levels,
        collapsing the middle as '...'.
        - If the path is short, returns it as-is.
        - Examples:
        vllm/model_executor/layers/quantization/utils/fp8_utils.py ->
        model_executor/.../quantization/utils/fp8_utils.py
        vllm/model_executor/layers/quantization/awq.py ->
        model_executor/layers/quantization/awq.py

        Args:
            relpath (Path): The relative path to be shortened.
        Returns:
            str: The shortened path string for display.
        """
        parts = list(relpath.parts)
        new_parts = []
        if parts and parts[0] == "vllm":
            parts = parts[1:]
        if parts and parts[0] == "v1":
            new_parts += parts[:2]
            parts = parts[2:]
        elif parts:
            new_parts += parts[:1]
            parts = parts[1:]
        if len(parts) > 2:
            new_parts += ["..."] + parts[-2:]
        else:
            new_parts += parts
        return "/".join(new_parts)

    if self.use_relpath:
        abs_path = getattr(record, "pathname", None)
        if abs_path:
            try:
                relpath = Path(abs_path).resolve().relative_to(self.root_dir)
            except Exception:
                relpath = Path(record.filename)
        else:
            relpath = Path(record.filename)
        record.fileinfo = shrink_path(relpath)
    else:
        record.fileinfo = record.filename

    msg = super().format(record)
    if record.message != "":
        parts = msg.split(record.message)
        msg = msg.replace("\n", "\r\n" + parts[0])
    return msg

UvicornAccessLogFilter

Bases: Filter

A logging filter that excludes access logs for specified endpoint paths.

This filter is designed to work with uvicorn's access logger. It checks the log record's arguments for the request path and filters out records matching the excluded paths.

Uvicorn access log format

'%s - "%s %s HTTP/%s" %d' (client_addr, method, path, http_version, status_code)

Example

127.0.0.1:12345 - "GET /health HTTP/1.1" 200

Parameters:

Name Type Description Default
excluded_paths list[str] | None

A list of URL paths to exclude from logging. Paths are matched exactly. Example: ["/health", "/metrics"]

None
Source code in vllm/logging_utils/access_log_filter.py
class UvicornAccessLogFilter(logging.Filter):
    """
    A logging filter that excludes access logs for specified endpoint paths.

    This filter is designed to work with uvicorn's access logger. It checks
    the log record's arguments for the request path and filters out records
    matching the excluded paths.

    Uvicorn access log format:
        '%s - "%s %s HTTP/%s" %d'
        (client_addr, method, path, http_version, status_code)

    Example:
        127.0.0.1:12345 - "GET /health HTTP/1.1" 200

    Args:
        excluded_paths: A list of URL paths to exclude from logging.
                       Paths are matched exactly.
                       Example: ["/health", "/metrics"]
    """

    def __init__(self, excluded_paths: list[str] | None = None):
        super().__init__()
        self.excluded_paths = set(excluded_paths or [])

    def filter(self, record: logging.LogRecord) -> bool:
        """
        Determine if the log record should be logged.

        Args:
            record: The log record to evaluate.

        Returns:
            True if the record should be logged, False otherwise.
        """
        if not self.excluded_paths:
            return True

        # This filter is specific to uvicorn's access logs.
        if record.name != "uvicorn.access":
            return True

        # The path is the 3rd argument in the log record's args tuple.
        # See uvicorn's access logging implementation for details.
        log_args = record.args
        if isinstance(log_args, tuple) and len(log_args) >= 3:
            path_with_query = log_args[2]
            # Get path component without query string.
            if isinstance(path_with_query, str):
                path = urlparse(path_with_query).path
                if path in self.excluded_paths:
                    return False

        return True

excluded_paths instance-attribute

excluded_paths = set(excluded_paths or [])

__init__

__init__(excluded_paths: list[str] | None = None)
Source code in vllm/logging_utils/access_log_filter.py
def __init__(self, excluded_paths: list[str] | None = None):
    super().__init__()
    self.excluded_paths = set(excluded_paths or [])

filter

filter(record: LogRecord) -> bool

Determine if the log record should be logged.

Parameters:

Name Type Description Default
record LogRecord

The log record to evaluate.

required

Returns:

Type Description
bool

True if the record should be logged, False otherwise.

Source code in vllm/logging_utils/access_log_filter.py
def filter(self, record: logging.LogRecord) -> bool:
    """
    Determine if the log record should be logged.

    Args:
        record: The log record to evaluate.

    Returns:
        True if the record should be logged, False otherwise.
    """
    if not self.excluded_paths:
        return True

    # This filter is specific to uvicorn's access logs.
    if record.name != "uvicorn.access":
        return True

    # The path is the 3rd argument in the log record's args tuple.
    # See uvicorn's access logging implementation for details.
    log_args = record.args
    if isinstance(log_args, tuple) and len(log_args) >= 3:
        path_with_query = log_args[2]
        # Get path component without query string.
        if isinstance(path_with_query, str):
            path = urlparse(path_with_query).path
            if path in self.excluded_paths:
                return False

    return True

create_uvicorn_log_config

create_uvicorn_log_config(
    excluded_paths: list[str] | None = None,
    log_level: str = "info",
) -> dict

Create a uvicorn logging configuration with access log filtering.

This function generates a logging configuration dictionary that can be passed to uvicorn's log_config parameter. It sets up the access log filter to exclude specified paths.

Parameters:

Name Type Description Default
excluded_paths list[str] | None

List of URL paths to exclude from access logs.

None
log_level str

The log level for uvicorn loggers.

'info'

Returns:

Type Description
dict

A dictionary containing the logging configuration.

Example

config = create_uvicorn_log_config(["/health", "/metrics"]) uvicorn.run(app, log_config=config)

Source code in vllm/logging_utils/access_log_filter.py
def create_uvicorn_log_config(
    excluded_paths: list[str] | None = None,
    log_level: str = "info",
) -> dict:
    """
    Create a uvicorn logging configuration with access log filtering.

    This function generates a logging configuration dictionary that can be
    passed to uvicorn's `log_config` parameter. It sets up the access log
    filter to exclude specified paths.

    Args:
        excluded_paths: List of URL paths to exclude from access logs.
        log_level: The log level for uvicorn loggers.

    Returns:
        A dictionary containing the logging configuration.

    Example:
        >>> config = create_uvicorn_log_config(["/health", "/metrics"])
        >>> uvicorn.run(app, log_config=config)
    """
    config = {
        "version": 1,
        "disable_existing_loggers": False,
        "filters": {
            "access_log_filter": {
                "()": UvicornAccessLogFilter,
                "excluded_paths": excluded_paths or [],
            },
        },
        "formatters": {
            "default": {
                "()": "uvicorn.logging.DefaultFormatter",
                "fmt": "%(levelprefix)s %(message)s",
                "use_colors": None,
            },
            "access": {
                "()": "uvicorn.logging.AccessFormatter",
                "fmt": '%(levelprefix)s %(client_addr)s - "%(request_line)s" %(status_code)s',  # noqa: E501
            },
        },
        "handlers": {
            "default": {
                "formatter": "default",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stderr",
            },
            "access": {
                "formatter": "access",
                "class": "logging.StreamHandler",
                "stream": "ext://sys.stdout",
                "filters": ["access_log_filter"],
            },
        },
        "loggers": {
            "uvicorn": {
                "handlers": ["default"],
                "level": log_level.upper(),
                "propagate": False,
            },
            "uvicorn.error": {
                "level": log_level.upper(),
                "handlers": ["default"],
                "propagate": False,
            },
            "uvicorn.access": {
                "handlers": ["access"],
                "level": log_level.upper(),
                "propagate": False,
            },
        },
    }
    return config

logtime

logtime(logger, msg=None)

Logs the execution time of the decorated function. Always place it beneath other decorators.

Source code in vllm/logging_utils/log_time.py
def logtime(logger, msg=None):
    """
    Logs the execution time of the decorated function.
    Always place it beneath other decorators.
    """

    def _inner(func):
        @functools.wraps(func)
        def _wrapper(*args, **kwargs):
            start = time.perf_counter()
            result = func(*args, **kwargs)
            elapsed = time.perf_counter() - start

            prefix = (
                f"Function '{func.__module__}.{func.__qualname__}'"
                if msg is None
                else msg
            )
            logger.debug("%s: Elapsed time %.7f secs", prefix, elapsed)
            return result

        return _wrapper

    return _inner