Skip to content

logging_tools

log_level_by_name = log_level module-attribute

LogLevel

Bases: Enum

Source code in src/recnexteval/utils/logging_tools.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class LogLevel(Enum):
    CRITICAL = logging.CRITICAL
    ERROR = logging.ERROR
    WARNING = logging.WARNING
    INFO = logging.INFO
    DEBUG = logging.DEBUG
    NOTSET = logging.NOTSET

    @classmethod
    def from_string(cls, level: str) -> "LogLevel":
        """Return a LogLevel member from a case-insensitive string.

        Args:
            level: Name of the log level (case-insensitive).

        Returns:
            The corresponding :class:`LogLevel` enum member.
        """
        return cls[level.upper()]

CRITICAL = logging.CRITICAL class-attribute instance-attribute

ERROR = logging.ERROR class-attribute instance-attribute

WARNING = logging.WARNING class-attribute instance-attribute

INFO = logging.INFO class-attribute instance-attribute

DEBUG = logging.DEBUG class-attribute instance-attribute

NOTSET = logging.NOTSET class-attribute instance-attribute

from_string(level) classmethod

Return a LogLevel member from a case-insensitive string.

Parameters:

Name Type Description Default
level str

Name of the log level (case-insensitive).

required

Returns:

Type Description
LogLevel

The corresponding :class:LogLevel enum member.

Source code in src/recnexteval/utils/logging_tools.py
24
25
26
27
28
29
30
31
32
33
34
@classmethod
def from_string(cls, level: str) -> "LogLevel":
    """Return a LogLevel member from a case-insensitive string.

    Args:
        level: Name of the log level (case-insensitive).

    Returns:
        The corresponding :class:`LogLevel` enum member.
    """
    return cls[level.upper()]

log_level(level)

Change the logging level for the root logger.

Parameters:

Name Type Description Default
level int | str | LogLevel

The logging level to set. May be a :class:LogLevel enum, a level name (str, case-insensitive), or an integer logging level.

required

Returns:

Type Description
None

None

Source code in src/recnexteval/utils/logging_tools.py
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
def log_level(level: int | str | LogLevel) -> None:
    """Change the logging level for the root logger.

    Args:
        level: The logging level to set. May be a :class:`LogLevel` enum,
            a level name (str, case-insensitive), or an integer logging level.

    Returns:
        None
    """
    if isinstance(level, str):
        level = LogLevel.from_string(level)

    numeric_level = level.value if isinstance(level, LogLevel) else level

    logger = logging.getLogger()
    logger.setLevel(numeric_level)
    for handler in logger.handlers:
        handler.setLevel(numeric_level)

suppress_warnings()

Suppress all Python warnings.

This will disable warning output by filtering all warnings and disabling logging's capture of warnings.

Returns:

Type Description
None

None

Source code in src/recnexteval/utils/logging_tools.py
61
62
63
64
65
66
67
68
69
70
71
def suppress_warnings() -> None:
    """Suppress all Python warnings.

    This will disable warning output by filtering all warnings and
    disabling logging's capture of warnings.

    Returns:
        None
    """
    logging.captureWarnings(False)
    warnings.filterwarnings("ignore")

enable_warnings()

Enable Python warnings (reset to default behavior).

This re-enables warning capture and resets any filters previously set.

Returns:

Type Description
None

None

Source code in src/recnexteval/utils/logging_tools.py
74
75
76
77
78
79
80
81
82
83
def enable_warnings() -> None:
    """Enable Python warnings (reset to default behavior).

    This re-enables warning capture and resets any filters previously set.

    Returns:
        None
    """
    logging.captureWarnings(True)
    warnings.resetwarnings()

suppress_specific_warnings(category)

Suppress warnings of a specific category.

Parameters:

Name Type Description Default
category type[Warning]

Warning class/type to suppress (for example, :class:DeprecationWarning).

required

Returns:

Type Description
None

None

Source code in src/recnexteval/utils/logging_tools.py
86
87
88
89
90
91
92
93
94
95
def suppress_specific_warnings(category: type[Warning]) -> None:
    """Suppress warnings of a specific category.

    Args:
        category: Warning class/type to suppress (for example, :class:`DeprecationWarning`).

    Returns:
        None
    """
    warnings.filterwarnings("ignore", category=category)

warnings_suppressed()

Context manager that temporarily suppresses all warnings.

Yields:

Name Type Description
None Generator

Warnings are suppressed inside the context block.

Source code in src/recnexteval/utils/logging_tools.py
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
@contextmanager
def warnings_suppressed() -> Generator:
    """Context manager that temporarily suppresses all warnings.

    Yields:
        None: Warnings are suppressed inside the context block.
    """
    logging.captureWarnings(False)
    warnings.filterwarnings("ignore")
    try:
        yield
    finally:
        logging.captureWarnings(True)
        warnings.resetwarnings()

prepare_logger(log_config_filename)

Prepare and configure logging from a YAML file.

This function locates or creates a logging configuration YAML file using :func:recnexteval.utils.yaml_tool.create_config_yaml, ensures the directory for the configured log file exists, writes an ASCII art header to the log file, and configures the Python logging system using :func:logging.config.dictConfig.

Parameters:

Name Type Description Default
log_config_filename str

Name of the logging configuration YAML file.

required

Returns:

Name Type Description
dict dict

The parsed logging configuration dictionary.

Raises:

Type Description
FileNotFoundError

If the resolved YAML configuration file cannot be found.

ValueError

If there is an error parsing the YAML content.

Source code in src/recnexteval/utils/logging_tools.py
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
def prepare_logger(log_config_filename: str) -> dict:
    """Prepare and configure logging from a YAML file.

    This function locates or creates a logging configuration YAML file using
    :func:`recnexteval.utils.yaml_tool.create_config_yaml`, ensures the
    directory for the configured log file exists, writes an ASCII art header
    to the log file, and configures the Python logging system using
    :func:`logging.config.dictConfig`.

    Args:
        log_config_filename: Name of the logging configuration YAML file.

    Returns:
        dict: The parsed logging configuration dictionary.

    Raises:
        FileNotFoundError: If the resolved YAML configuration file cannot be found.
        ValueError: If there is an error parsing the YAML content.
    """
    _, yaml_file_path = create_config_yaml(log_config_filename)
    try:
        with open(yaml_file_path, "r") as stream:
            config = yaml.load(
                stream, Loader=yaml.FullLoader
            )
    except FileNotFoundError:
        raise FileNotFoundError(f"Configuration file not found at {yaml_file_path}.")
    except yaml.YAMLError as e:
        raise ValueError(f"Error parsing YAML configuration: {e}")

    # Get the log file path from the configuration
    log_file = config["handlers"]["file"]["filename"]

    # Ensure the log file directory exists
    dir_name = os.path.dirname(log_file)
    safe_dir(dir_name)

    # Write ASCII art to the log file
    with open(log_file, "w") as log:
        ascii_art = pyfiglet.figlet_format("recnexteval")
        log.write(ascii_art)
        log.write("\n")

    logging.config.dictConfig(config)
    logging.captureWarnings(True)
    return config