完成警告消息对应中文显示
This commit is contained in:
96
common/type_mapping.py
Normal file
96
common/type_mapping.py
Normal file
@@ -0,0 +1,96 @@
|
||||
# common/type_mapping.py
|
||||
"""
|
||||
告警类型映射配置模块
|
||||
从 config.yaml 加载告警 code 到 label 的映射关系
|
||||
"""
|
||||
|
||||
import yaml
|
||||
from typing import Dict, Optional
|
||||
from utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
class TypeMapping:
|
||||
"""类型映射类"""
|
||||
|
||||
def __init__(self, mapping: Dict[str, str], name: str = ""):
|
||||
self._mapping = mapping or {}
|
||||
self._name = name
|
||||
|
||||
def get(self, code: str, default: Optional[str] = None) -> str:
|
||||
"""获取label,支持自定义默认值"""
|
||||
if default is None:
|
||||
default = f"{code}"
|
||||
return self._mapping.get(code, default)
|
||||
|
||||
def __getitem__(self, code: str) -> str:
|
||||
"""支持 [] 语法访问"""
|
||||
return self.get(code)
|
||||
|
||||
def __contains__(self, code: str) -> bool:
|
||||
"""支持 in 操作符"""
|
||||
return code in self._mapping
|
||||
|
||||
def all(self) -> Dict[str, str]:
|
||||
"""获取所有映射"""
|
||||
return self._mapping.copy()
|
||||
|
||||
def codes(self) -> list:
|
||||
"""获取所有code"""
|
||||
return list(self._mapping.keys())
|
||||
|
||||
def labels(self) -> list:
|
||||
"""获取所有label"""
|
||||
return list(self._mapping.values())
|
||||
|
||||
|
||||
# 全局映射实例
|
||||
_alert_types: Optional[TypeMapping] = None
|
||||
|
||||
|
||||
def init_type_mappings(config_path: str = "config.yaml"):
|
||||
"""
|
||||
从配置文件初始化类型映射
|
||||
|
||||
Args:
|
||||
config_path: 配置文件路径
|
||||
"""
|
||||
global _alert_types
|
||||
|
||||
try:
|
||||
with open(config_path, "r", encoding="utf-8") as f:
|
||||
cfg = yaml.safe_load(f)
|
||||
|
||||
_alert_types = TypeMapping(
|
||||
cfg.get("alert_types", {}),
|
||||
name="告警类型"
|
||||
)
|
||||
|
||||
logger.info(f"[INFO] Alert type mappings initialized from {config_path}")
|
||||
logger.info(f" - alert_types: {len(_alert_types.codes())} items")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[ERROR] Failed to load type mappings from {config_path}: {e}")
|
||||
_alert_types = TypeMapping({}, "告警类型")
|
||||
|
||||
|
||||
def alert_types() -> TypeMapping:
|
||||
"""获取告警类型映射"""
|
||||
if _alert_types is None:
|
||||
init_type_mappings()
|
||||
return _alert_types
|
||||
|
||||
|
||||
def get_alert_label(code: str, default: str = None) -> str:
|
||||
"""
|
||||
快捷获取告警类型label
|
||||
|
||||
Args:
|
||||
code: 告警类型代码
|
||||
default: 默认值,未提供时返回 "未知告警类型(code)"
|
||||
|
||||
Returns:
|
||||
告警类型中文名称
|
||||
"""
|
||||
return alert_types().get(code, default)
|
||||
Reference in New Issue
Block a user