new_wukong/utils/logger.py
2024-05-15 20:33:56 +08:00

53 lines
1.9 KiB
Python

import logging
import logging.config
from pathlib import Path
from typing import *
from .constants import CONFIG_DEFAULT_PATH, TEMP_PATH, FILE_ENCODING
CONFIG_LOGGER_FILE_PATH = CONFIG_DEFAULT_PATH / "logger.yml"
# 类型别名简化复杂注解
ConfigFunc = Callable[[str], Dict[str, Any]]
# 默认日志配置
def _default_config(_):
logging.basicConfig(level=logging.NOTSET)
# 更新日志配置文件的文件路径
def _update_handlers_filenames(config: dict[str, Any], base_filepath: Path) -> None:
for handler_config in config.get('handlers', {}).values():
if 'filename' in handler_config:
handler_config['filename'] = str(base_filepath.joinpath(handler_config['filename']))
# 使用文件配置日志
def _setup_logger(config_path : Path,
config_func : ConfigFunc = _default_config,
log_filepath: Optional[Path] = None,
file_encoding: str = 'utf-8') -> dict[str, Any]:
try:
if config_path.exists():
config = config_func(
config_path.read_text(encoding=file_encoding))
value = config.get('handlers', None)
if log_filepath is not None and value is not None:
_update_handlers_filenames(config, log_filepath)
logging.config.dictConfig(config)
return config
else:
config_func()
return None
except Exception as e:
raise RuntimeError(f"Failed to setup logger: {e}")
# 默认使用yaml配置
def yml_config(file_content : str):
import yaml
return yaml.safe_load(file_content)
# 对外接口
def setup_logger(config_path : Path = CONFIG_LOGGER_FILE_PATH,
config_func : Callable[[str], str| dict[str, Any]] = yml_config,
log_filepath : Path = TEMP_PATH,
file_encoding : str = FILE_ENCODING) -> bool:
return _setup_logger(config_path, config_func, log_filepath, file_encoding) is not None