Skip to content

Logging Configuration

Configure the logger with custom settings using Python's standard logging module.

Parameters:

Name Type Description Default
format_string Optional[str]

The format string for log messages. If None, a default format will be used.

None
level str

The minimum logging level. Default: "INFO"

'INFO'
sink Union[PathLike[str], TextIO, BinaryIO]

Where to send the log. Default: sys.stderr Can be a file path, TextIO, or BinaryIO.

stderr
include_correlation_id bool

Whether to include correlation ID in log messages. Default: True

True
use_colors bool

Whether to use colored output for console logging. Automatically disabled for file output. Default: True

True

Returns:

Type Description
Logger

logging.Logger: The configured logger object

Example
from airia import configure_logging

# Basic configuration with colors
logger = configure_logging()

# Disable colors
logger = configure_logging(use_colors=False)

# File-based logging (colors automatically disabled)
file_logger = configure_logging(
    level="DEBUG",
    sink="app.log",
    include_correlation_id=True
)

# Console output
console_logger = configure_logging(
    level="INFO",
    sink=sys.stdout
)
Source code in airia/logs.py
def configure_logging(
    format_string: Optional[str] = None,
    level: str = "INFO",
    sink: Union[os.PathLike[str], TextIO, BinaryIO] = sys.stderr,
    include_correlation_id: bool = True,
    use_colors: bool = True,
) -> logging.Logger:
    """
    Configure the logger with custom settings using Python's standard logging module.

    Args:
        format_string (Optional[str]): The format string for log messages.
                                      If None, a default format will be used.
        level (str): The minimum logging level. Default: "INFO"
        sink: Where to send the log. Default: sys.stderr
              Can be a file path, TextIO, or BinaryIO.
        include_correlation_id (bool): Whether to include correlation ID in log messages.
                                      Default: True
        use_colors (bool): Whether to use colored output for console logging.
                          Automatically disabled for file output. Default: True

    Returns:
        logging.Logger: The configured logger object

    Example:
        ```python
        from airia import configure_logging

        # Basic configuration with colors
        logger = configure_logging()

        # Disable colors
        logger = configure_logging(use_colors=False)

        # File-based logging (colors automatically disabled)
        file_logger = configure_logging(
            level="DEBUG",
            sink="app.log",
            include_correlation_id=True
        )

        # Console output
        console_logger = configure_logging(
            level="INFO",
            sink=sys.stdout
        )
        ```
    """
    logger = logging.getLogger("airia")
    logger.handlers.clear()
    logger.setLevel(getattr(logging, level.upper(), logging.INFO))

    # Determine if this is file or console output
    is_file_output = isinstance(sink, (str, os.PathLike))

    # Create handler based on sink type
    if is_file_output:
        handler = logging.FileHandler(str(sink))
        # Disable colors for file output
        use_colors = False
    elif hasattr(sink, "write"):
        handler = logging.StreamHandler(sink)  # type: ignore
    else:
        handler = logging.StreamHandler(sys.stderr)

    # Create formatter
    if format_string is None:
        if include_correlation_id:
            format_string = "[%(correlation_id)s] %(asctime)s | %(levelname)-8s | %(name)s:%(funcName)s:%(lineno)d - %(message)s"
        else:
            format_string = "%(asctime)s | %(levelname)-8s | %(name)s:%(funcName)s:%(lineno)d - %(message)s"

    # Use ColoredFormatter for console, regular Formatter for files
    if use_colors and not is_file_output:
        formatter = ColoredFormatter(format_string, use_colors=True)
    else:
        formatter = logging.Formatter(format_string)

    handler.setFormatter(formatter)

    # Add correlation ID filter if enabled
    if include_correlation_id:
        handler.addFilter(CorrelationIdFilter())

    logger.addHandler(handler)

    return logger