Skip to content

API Reference

LogSettings

Bases: BaseModel

Settings for the loggers.

Attributes:

Name Type Description
console_level Optional[int]

The level to use for the console output.

file_level Optional[int]

The level to use for the file output.

file_path Optional[str]

The path where the log file should be created. Can contain the following placeholders:

  • %date%: The current date in the format YYYY-MM-DD.
  • %time%: The current time in the format HH-MM-SS.
  • %Y%: The current year.
  • %M%: The current month.
  • %D%: The current day.
  • %H%: The current hour.
  • %m%: The current minute.
  • %s%: The current second.
  • %ms%: The current microsecond.

If None logging is disabled.

file_override Optional[bool]

Should the file be opened in overwrite mode or append mode?

base Optional[str]

The base logger (used with getLogger()).

others Dict[str, int]

Change the log levels for specific loggers.

Source code in log2me/settings.py
class LogSettings(BaseModel):
    """Settings for the loggers.

    Attributes:
        console_level: The level to use for the console output.
        file_level: The level to use for the file output.
        file_path: The path where the log file should be created.
            Can contain the following placeholders:

            - %date%: The current date in the format YYYY-MM-DD.
            - %time%: The current time in the format HH-MM-SS.
            - %Y%: The current year.
            - %M%: The current month.
            - %D%: The current day.
            - %H%: The current hour.
            - %m%: The current minute.
            - %s%: The current second.
            - %ms%: The current microsecond.

            If `None` logging is disabled.
        file_override: Should the file be opened in overwrite mode or
            append mode?
        base: The base logger (used with `getLogger()`).
        others: Change the log levels for specific loggers.
    """

    console_level: Optional[int] = Field(
        logging.INFO, description="The level to use for the console output."
    )
    file_level: Optional[int] = Field(
        -1, description="The level to use for the file output."
    )
    file_path: Optional[str] = Field(
        None,
        description=(
            "The path where the log file should be created. "
            "Can contain the following placeholders:\n"
            "- %date%: The current date in the format YYYY-MM-DD.\n"
            "- %time%: The current time in the format HH-MM-SS.\n"
            "- %Y%: The current year.\n"
            "- %M%: The current month.\n"
            "- %D%: The current day.\n"
            "- %H%: The current hour.\n"
            "- %m%: The current minute.\n"
            "- %s%: The current second.\n"
            "- %ms%: The current microsecond.\n"
            "If `None` logging is disabled."
        ),
    )
    file_override: Optional[bool] = Field(
        False,
        description=(
            "Should the file be opened in overwrite mode or append mode?"
        ),
    )
    base: Optional[str] = Field(
        "log2me", description="The base logger (used with `getLogger()`)."
    )
    others: Dict[str, int] = Field(
        default_factory=dict,
        description=(
            "Change the log levels for specific loggers. "
            "The key is the name of the logger, the value is "
            "the level. If the value is None, the level will "
            "not be changed."
        ),
    )

setup_logging(stg, debug=False)

Sets up logging for the application.

If a log file is specified in the settings, the log file will be created and used. Otherwise, only the console will be used. The path of the log file can contain the following placeholders:

  • %date%: The current date in the format YYYY-MM-DD.
  • %time%: The current time in the format HH-MM-SS.
  • %Y%: The current year.
  • %M%: The current month.
  • %D%: The current day.
  • %H%: The current hour.
  • %m%: The current minute.
  • %s%: The current second.
  • %ms%: The current microsecond.

Parameters:

Name Type Description Default
stg LogSettings

The settings object.

required

Returns:

Type Description
Logger

The logger object.

Source code in log2me/setup_log.py
def setup_logging(stg: LogSettings, debug: bool = False) -> logging.Logger:
    """
    Sets up logging for the application.

    If a log file is specified in the settings, the log file will be created
    and used. Otherwise, only the console will be used.
    The path of the log file can contain the following placeholders:

    - %date%: The current date in the format YYYY-MM-DD.
    - %time%: The current time in the format HH-MM-SS.
    - %Y%: The current year.
    - %M%: The current month.
    - %D%: The current day.
    - %H%: The current hour.
    - %m%: The current minute.
    - %s%: The current second.
    - %ms%: The current microsecond.

    Args:
        stg: The settings object.

    Returns:
        The logger object.
    """
    # The file handler for the log file.
    if stg.file_path and stg.file_level and stg.file_level > 0:
        fh = logging.FileHandler(
            get_log_file(stg.file_path),
            "w" if stg.file_override else "a",
            "utf-8",
        )
        fh.setLevel(stg.file_level)
        fh.setFormatter(
            logging.Formatter(
                "%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s",
                datefmt="%I:%M:%S %p",
            )
        )
    else:
        fh = None

    if stg.console_level:
        ch = RichHandler()
        ch.setLevel(stg.console_level)
        # ch.setFormatter(logging.Formatter(
        #     '%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s',
        #     datefmt='%I:%M:%S %p'
        # ))
    else:
        ch = None

    # Top level logger.
    logger = logging.getLogger()
    logger.handlers = []
    if fh:
        logger.addHandler(fh)
    if ch:
        logger.addHandler(ch)

    if ch or fh:
        logger.setLevel(
            min(
                stg.file_level if stg.file_level else logging.CRITICAL,
                stg.console_level if stg.console_level else logging.CRITICAL,
            )
        )
    else:
        logger.setLevel(logging.CRITICAL)

    # Change the log levels for specific loggers.
    for logger_name, logger_level in stg.others.items():
        if logger_level is not None:
            logging.getLogger(logger_name).setLevel(logger_level)

    # See all loggers.
    if debug:
        from log2me.print_loggers import print_loggers

        print_loggers()

    return logging.getLogger(stg.base)

Settings

LogSettings

Bases: BaseModel

Settings for the loggers.

Attributes:

Name Type Description
console_level Optional[int]

The level to use for the console output.

file_level Optional[int]

The level to use for the file output.

file_path Optional[str]

The path where the log file should be created. Can contain the following placeholders:

  • %date%: The current date in the format YYYY-MM-DD.
  • %time%: The current time in the format HH-MM-SS.
  • %Y%: The current year.
  • %M%: The current month.
  • %D%: The current day.
  • %H%: The current hour.
  • %m%: The current minute.
  • %s%: The current second.
  • %ms%: The current microsecond.

If None logging is disabled.

file_override Optional[bool]

Should the file be opened in overwrite mode or append mode?

base Optional[str]

The base logger (used with getLogger()).

others Dict[str, int]

Change the log levels for specific loggers.

Source code in log2me/settings.py
class LogSettings(BaseModel):
    """Settings for the loggers.

    Attributes:
        console_level: The level to use for the console output.
        file_level: The level to use for the file output.
        file_path: The path where the log file should be created.
            Can contain the following placeholders:

            - %date%: The current date in the format YYYY-MM-DD.
            - %time%: The current time in the format HH-MM-SS.
            - %Y%: The current year.
            - %M%: The current month.
            - %D%: The current day.
            - %H%: The current hour.
            - %m%: The current minute.
            - %s%: The current second.
            - %ms%: The current microsecond.

            If `None` logging is disabled.
        file_override: Should the file be opened in overwrite mode or
            append mode?
        base: The base logger (used with `getLogger()`).
        others: Change the log levels for specific loggers.
    """

    console_level: Optional[int] = Field(
        logging.INFO, description="The level to use for the console output."
    )
    file_level: Optional[int] = Field(
        -1, description="The level to use for the file output."
    )
    file_path: Optional[str] = Field(
        None,
        description=(
            "The path where the log file should be created. "
            "Can contain the following placeholders:\n"
            "- %date%: The current date in the format YYYY-MM-DD.\n"
            "- %time%: The current time in the format HH-MM-SS.\n"
            "- %Y%: The current year.\n"
            "- %M%: The current month.\n"
            "- %D%: The current day.\n"
            "- %H%: The current hour.\n"
            "- %m%: The current minute.\n"
            "- %s%: The current second.\n"
            "- %ms%: The current microsecond.\n"
            "If `None` logging is disabled."
        ),
    )
    file_override: Optional[bool] = Field(
        False,
        description=(
            "Should the file be opened in overwrite mode or append mode?"
        ),
    )
    base: Optional[str] = Field(
        "log2me", description="The base logger (used with `getLogger()`)."
    )
    others: Dict[str, int] = Field(
        default_factory=dict,
        description=(
            "Change the log levels for specific loggers. "
            "The key is the name of the logger, the value is "
            "the level. If the value is None, the level will "
            "not be changed."
        ),
    )

Setup

Sets up logging for the application.

If a log file is specified in the settings, the log file will be created and used. Otherwise, only the console will be used. The path of the log file can contain the following placeholders:

  • %date%: The current date in the format YYYY-MM-DD.
  • %time%: The current time in the format HH-MM-SS.
  • %Y%: The current year.
  • %M%: The current month.
  • %D%: The current day.
  • %H%: The current hour.
  • %m%: The current minute.
  • %s%: The current second.
  • %ms%: The current microsecond.

Parameters:

Name Type Description Default
stg LogSettings

The settings object.

required

Returns:

Type Description
Logger

The logger object.

Source code in log2me/setup_log.py
def setup_logging(stg: LogSettings, debug: bool = False) -> logging.Logger:
    """
    Sets up logging for the application.

    If a log file is specified in the settings, the log file will be created
    and used. Otherwise, only the console will be used.
    The path of the log file can contain the following placeholders:

    - %date%: The current date in the format YYYY-MM-DD.
    - %time%: The current time in the format HH-MM-SS.
    - %Y%: The current year.
    - %M%: The current month.
    - %D%: The current day.
    - %H%: The current hour.
    - %m%: The current minute.
    - %s%: The current second.
    - %ms%: The current microsecond.

    Args:
        stg: The settings object.

    Returns:
        The logger object.
    """
    # The file handler for the log file.
    if stg.file_path and stg.file_level and stg.file_level > 0:
        fh = logging.FileHandler(
            get_log_file(stg.file_path),
            "w" if stg.file_override else "a",
            "utf-8",
        )
        fh.setLevel(stg.file_level)
        fh.setFormatter(
            logging.Formatter(
                "%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s",
                datefmt="%I:%M:%S %p",
            )
        )
    else:
        fh = None

    if stg.console_level:
        ch = RichHandler()
        ch.setLevel(stg.console_level)
        # ch.setFormatter(logging.Formatter(
        #     '%(asctime)s - %(name)-12s - %(levelname)-8s - %(message)s',
        #     datefmt='%I:%M:%S %p'
        # ))
    else:
        ch = None

    # Top level logger.
    logger = logging.getLogger()
    logger.handlers = []
    if fh:
        logger.addHandler(fh)
    if ch:
        logger.addHandler(ch)

    if ch or fh:
        logger.setLevel(
            min(
                stg.file_level if stg.file_level else logging.CRITICAL,
                stg.console_level if stg.console_level else logging.CRITICAL,
            )
        )
    else:
        logger.setLevel(logging.CRITICAL)

    # Change the log levels for specific loggers.
    for logger_name, logger_level in stg.others.items():
        if logger_level is not None:
            logging.getLogger(logger_name).setLevel(logger_level)

    # See all loggers.
    if debug:
        from log2me.print_loggers import print_loggers

        print_loggers()

    return logging.getLogger(stg.base)

Debug

A script that prints all the loggers and their levels.

print_loggers()

Print the loggers and their levels.

Source code in log2me/print_loggers.py
def print_loggers() -> None:
    """
    Print the loggers and their levels.
    """
    for logger_name in logging.Logger.manager.loggerDict:
        print(logger_name, ": ", end="")
        level = logging.getLogger(logger_name).getEffectiveLevel()

        print(logging.getLevelName(level))