跳到内容

llmcompressor.logger

为 LLM Compressor 提供灵活的日志配置。

Logger 使用 loguru 库,支持控制台和文件日志,可通过环境变量或直接函数调用进行配置。

环境变量

  • LLM_COMPRESSOR_LOG_DISABLED: 禁用日志记录。默认为 False
  • LLM_COMPRESSOR_CLEAR_LOGGERS: 清除 loguru 中已有的日志记录器。默认为 True
  • LLM_COMPRESSOR_LOG_LEVEL: 控制台日志记录级别。默认为 None。选项:DEBUG, INFO, WARNING, ERROR, CRITICAL
  • LLM_COMPRESSOR_LOG_FILE: 用于文件日志记录的文件路径。如果设置了日志文件级别,则默认为 llm-compressor.log,否则为 None
  • LLM_COMPRESSOR_LOG_FILE_LEVEL: 文件日志记录级别。如果设置了日志文件,则默认为 INFO,否则为 None

用法

from llmcompressor import logger, configure_logger, LoggerConfig

# Configure metrics with default settings
configure_logger(
    config=LoggerConfig(
        disabled=False,
        clear_loggers=True,
        console_log_level="DEBUG",
        log_file=None,
        log_file_level=None,
    )
)

logger.debug("This is a debug message")
logger.info("This is an info message")

函数

configure_logger

configure_logger(
    config: Optional[LoggerConfig] = None,
) -> None

配置 LLM Compressor 的日志记录器。

此函数根据指定的或默认参数设置控制台和文件日志记录。

注意:环境变量的优先级高于函数参数。

参数

  • config

    (Optional[LoggerConfig], 默认: None ) –

    要使用的日志记录器的配置。

源代码位于 llmcompressor/logger.py
def configure_logger(config: Optional[LoggerConfig] = None) -> None:
    """
    Configure the logger for LLM Compressor.

    This function sets up the console and file logging
    as per the specified or default parameters.

    **Note**: Environment variables take precedence over function parameters.

    :param config: The configuration for the logger to use.
    :type config: LoggerConfig
    """
    logger_config = config or LoggerConfig()

    # env vars get priority
    if (disabled := os.getenv("LLM_COMPRESSOR_LOG_DISABLED")) is not None:
        logger_config.disabled = disabled.lower() == "true"
    if (clear_loggers := os.getenv("LLM_COMPRESSOR_CLEAR_LOGGERS")) is not None:
        logger_config.clear_loggers = clear_loggers.lower() == "true"
    if (console_log_level := os.getenv("LLM_COMPRESSOR_LOG_LEVEL")) is not None:
        logger_config.console_log_level = console_log_level.upper()
    if (log_file := os.getenv("LLM_COMPRESSOR_LOG_FILE")) is not None:
        logger_config.log_file = log_file
    if (log_file_level := os.getenv("LLM_COMPRESSOR_LOG_FILE_LEVEL")) is not None:
        logger_config.log_file_level = log_file_level.upper()

    if logger_config.disabled:
        logger.disable("llmcompressor")
        return

    logger.enable("llmcompressor")

    if logger_config.clear_loggers:
        logger.remove()

    if logger_config.console_log_level:
        # log as a human readable string with the time, function, level, and message
        logger.add(
            sys.stdout,
            level=logger_config.console_log_level.upper(),
            format="{time} | {function} | {level} - {message}",
            filter=support_log_once,
        )

    if logger_config.log_file or logger_config.log_file_level:
        log_file = logger_config.log_file or "llmcompressor.log"
        log_file_level = logger_config.log_file_level or "INFO"
        # log as json to the file for easier parsing
        logger.add(
            log_file,
            level=log_file_level.upper(),
            serialize=True,
            filter=support_log_once,
        )

    if logger_config.metrics_disabled or "METRIC" in logger._core.levels.keys():
        return

    # initialize metric logger on loguru
    logger.level("METRIC", no=38, color="<yellow>", icon="📈")

support_log_once

support_log_once(record: Dict[str, Any]) -> bool

通过 .bind(log_once=True) 支持仅记录一次。

logger.bind(log_once=False).info("This will log multiple times")
logger.bind(log_once=False).info("This will log multiple times")
logger.bind(log_once=True).info("This will only log once")
logger.bind(log_once=True).info("This will only log once")  # skipped
源代码位于 llmcompressor/logger.py
def support_log_once(record: Dict[str, Any]) -> bool:
    """
    Support logging only once using `.bind(log_once=True)`

    ```
    logger.bind(log_once=False).info("This will log multiple times")
    logger.bind(log_once=False).info("This will log multiple times")
    logger.bind(log_once=True).info("This will only log once")
    logger.bind(log_once=True).info("This will only log once")  # skipped
    ```
    """
    log_once = record["extra"].get("log_once", False)
    level = getattr(record["level"], "name", "none")
    message = str(level) + record["message"]

    if log_once and message in _logged_once:
        return False

    if log_once:
        _logged_once.add(message)

    return True