34feac02 by shady

增加部分log日志文件处理

1 parent 41026f54
......@@ -44,10 +44,65 @@ def init_logging(log_level=logging.INFO):
创建logs目录并配置基本的文件日志记录
"""
try:
# 获取脚本所在目录
script_dir = Path(__file__).parent
# 智能选择logs目录 - 与images目录使用相同的逻辑
def get_logs_directory() -> Path:
"""获取可用的logs目录,支持开发环境和打包环境"""
def get_candidate_logs_paths():
"""获取logs候选路径列表"""
system = platform.system()
candidates = []
# 1. 优先尝试:当前目录的logs文件夹
if getattr(sys, 'frozen', False):
# 打包环境:使用可执行文件所在目录
candidates.append(Path(sys.executable).parent / "logs")
else:
# 开发环境:使用脚本所在目录
candidates.append(Path(__file__).parent / "logs")
# 2. 备选方案:用户目录
if system == "Darwin": # macOS
candidates.append(Path.home() / "Library/Application Support/ZB100ImageGenerator/logs")
candidates.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
elif system == "Windows":
candidates.append(Path(os.environ.get("APPDATA", "")) / "ZB100ImageGenerator/logs")
candidates.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
else: # Linux
candidates.append(Path.home() / ".config/zb100imagegenerator/logs")
candidates.append(Path.home() / "Documents/ZB100ImageGenerator/logs")
return candidates
def test_logs_write_access(path: Path) -> bool:
"""测试logs路径是否有写入权限"""
try:
# 尝试创建目录
path.mkdir(parents=True, exist_ok=True)
# 测试写入权限
test_file = path / ".write_test"
test_file.write_text("test")
test_file.unlink() # 删除测试文件
return True
except Exception:
return False
# 测试候选路径
for candidate_path in get_candidate_logs_paths():
if test_logs_write_access(candidate_path):
print(f"使用logs目录: {candidate_path}")
return candidate_path
# 所有路径都失败,使用临时目录
fallback_path = Path(tempfile.gettempdir()) / "ZB100ImageGenerator_logs"
print(f"警告: 所有logs路径都不可用,使用临时目录: {fallback_path}")
fallback_path.mkdir(exist_ok=True)
return fallback_path
logs_dir = get_logs_directory()
# 尝试加载日志配置
script_dir = Path(__file__).parent if not getattr(sys, 'frozen', False) else Path(sys.executable).parent
config_path = script_dir / "config.json"
logging_config = {
"enabled": True,
......@@ -72,9 +127,8 @@ def init_logging(log_level=logging.INFO):
level_str = logging_config.get("level", "INFO").upper()
log_level = getattr(logging, level_str, logging.INFO)
# 创建logs目录
logs_dir = script_dir / "logs"
logs_dir.mkdir(exist_ok=True)
# 确保logs目录存在
logs_dir.mkdir(parents=True, exist_ok=True)
# 配置日志文件路径
log_file = logs_dir / "app.log"
......