fromenumimportEnumfromtypingimportLiteral,Union# Type aliasesLevelStr=Literal["debug","info","warning","error","critical"]LevelSpec=Union["LogLevel",LevelStr,int]
[docs]classLogLevel(Enum):"""Log levels for ctxlog."""DEBUG=10INFO=20WARNING=30ERROR=40CRITICAL=50
[docs]@classmethoddefparse(cls,level:Union["LogLevel",str,int])->"LogLevel":"""Parse a string or int to a LogLevel. Args: level: The log level as a string or int. Returns: The corresponding LogLevel enum value. Raises: ValueError: If the level is not a valid log level. """ifisinstance(level,LogLevel):returnlevelelifisinstance(level,str):returncls.from_string(level)elifisinstance(level,int):forlog_levelinLogLevel:iflog_level.value==level:returnlog_levelraiseValueError(f"Invalid log level: {level}.")else:raiseTypeError(f"Expected str, int, or LogLevel, got {type(level)}.")
[docs]@classmethoddeffrom_string(cls,level_str:str)->"LogLevel":"""Convert a string to a LogLevel. Args: level_str: The string representation of the log level. Returns: The corresponding LogLevel enum value. Raises: ValueError: If the string is not a valid log level. """level_map={"debug":cls.DEBUG,"info":cls.INFO,"warning":cls.WARNING,"error":cls.ERROR,"critical":cls.CRITICAL,}iflevel_str.lower()notinlevel_map:valid_levels=", ".join(level_map.keys())raiseValueError(f"Invalid log level: {level_str}. Valid levels are: {valid_levels}")returnlevel_map[level_str.lower()]
[docs]def__str__(self)->str:"""Return the string representation of the log level."""returnself.name.lower()