logging: use LogLevel enum and add functions to set/get the current level

This commit is contained in:
Izalia Mae 2024-01-21 06:39:49 -05:00
parent 965ac73c6d
commit 9808674b98

View file

@ -4,20 +4,62 @@ import logging
import os import os
import typing import typing
from enum import IntEnum
from pathlib import Path from pathlib import Path
if typing.TYPE_CHECKING: if typing.TYPE_CHECKING:
from typing import Any, Callable from typing import Any, Callable, Type
LOG_LEVELS: dict[str, int] = { class LogLevel(IntEnum):
'DEBUG': logging.DEBUG, DEBUG = logging.DEBUG
'VERBOSE': 15, VERBOSE = 15
'INFO': logging.INFO, INFO = logging.INFO
'WARNING': logging.WARNING, WARNING = logging.WARNING
'ERROR': logging.ERROR, ERROR = logging.ERROR
'CRITICAL': logging.CRITICAL CRITICAL = logging.CRITICAL
}
def __str__(self) -> str:
return self.name
@classmethod
def parse(cls: Type[IntEnum], data: object) -> IntEnum:
if isinstance(data, cls):
return data
if isinstance(data, str):
data = data.upper()
try:
return cls[data]
except KeyError:
pass
try:
return cls(data)
except ValueError:
pass
raise AttributeError(f'Invalid enum property for {cls.__name__}: {data}')
def get_level() -> LogLevel:
return LogLevel.parse(logging.root.level)
def set_level(level: LogLevel | str) -> None:
logging.root.setLevel(LogLevel.parse(level))
def verbose(message: str, *args: Any, **kwargs: Any) -> None:
if not logging.root.isEnabledFor(LogLevel['VERBOSE']):
return
logging.log(LogLevel['VERBOSE'], message, *args, **kwargs)
debug: Callable = logging.debug debug: Callable = logging.debug
@ -27,14 +69,7 @@ error: Callable = logging.error
critical: Callable = logging.critical critical: Callable = logging.critical
def verbose(message: str, *args: Any, **kwargs: Any) -> None: logging.addLevelName(LogLevel['VERBOSE'], 'VERBOSE')
if not logging.root.isEnabledFor(LOG_LEVELS['VERBOSE']):
return
logging.log(LOG_LEVELS['VERBOSE'], message, *args, **kwargs)
logging.addLevelName(LOG_LEVELS['VERBOSE'], 'VERBOSE')
env_log_level = os.environ.get('LOG_LEVEL', 'INFO').upper() env_log_level = os.environ.get('LOG_LEVEL', 'INFO').upper()
try: try:
@ -45,11 +80,11 @@ except KeyError:
try: try:
log_level = LOG_LEVELS[env_log_level] log_level = LogLevel[env_log_level]
except KeyError: except KeyError:
logging.warning('Invalid log level: %s', env_log_level) print('Invalid log level:', env_log_level)
log_level = logging.INFO log_level = LogLevel['INFO']
handlers = [logging.StreamHandler()] handlers = [logging.StreamHandler()]