Kamixitong/scripts/fix_logging.py
2025-12-12 11:35:14 +08:00

169 lines
5.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
日志轮转问题快速修复脚本
解决Windows系统上的文件锁定问题
"""
import os
import sys
import time
import shutil
from pathlib import Path
def fix_logging_issues():
"""修复日志轮转问题"""
print("=" * 60)
print("🔧 KaMiXiTong 日志问题修复工具")
print("=" * 60)
logs_dir = Path('logs')
log_file = logs_dir / 'kamaxitong.log'
# 1. 确保日志目录存在
print("\n1. 检查日志目录...")
if not logs_dir.exists():
logs_dir.mkdir(parents=True, exist_ok=True)
print(" ✅ 已创建日志目录")
else:
print(" ✅ 日志目录已存在")
# 2. 清理可能锁定的日志文件
print("\n2. 清理可能锁定的日志文件...")
if log_file.exists():
try:
# 尝试删除或重命名
backup_file = logs_dir / f'kamaxitong_{int(time.time())}.log'
shutil.move(str(log_file), str(backup_file))
print(f" ✅ 已将原日志文件备份为: {backup_file.name}")
except PermissionError as e:
print(f" ⚠️ 无法移动日志文件: {str(e)}")
print(" 💡 请手动关闭占用日志文件的进程")
return False
except Exception as e:
print(f" ❌ 备份失败: {str(e)}")
return False
# 3. 清理旧的日志文件
print("\n3. 清理旧的日志文件...")
old_logs = list(logs_dir.glob('*.log.*'))
if old_logs:
for old_log in old_logs:
try:
old_log.unlink()
print(f" ✅ 已删除: {old_log.name}")
except Exception as e:
print(f" ⚠️ 无法删除 {old_log.name}: {str(e)}")
else:
print(" ✅ 没有旧的日志文件")
# 4. 创建新的日志文件
print("\n4. 创建新的日志文件...")
try:
log_file.touch()
print(f" ✅ 已创建新的日志文件: {log_file}")
except Exception as e:
print(f" ❌ 创建日志文件失败: {str(e)}")
return False
# 5. 检查文件权限
print("\n5. 检查文件权限...")
try:
# 测试写入权限
with open(log_file, 'a', encoding='utf-8') as f:
f.write(f"# 日志文件创建时间: {time.strftime('%Y-%m-%d %H:%M:%S')}\n")
print(" ✅ 文件写入权限正常")
except PermissionError as e:
print(f" ❌ 文件权限错误: {str(e)}")
print(" 💡 请以管理员权限运行此脚本")
return False
# 6. 生成日志配置检查报告
print("\n" + "=" * 60)
print("✅ 日志问题修复完成!")
print("=" * 60)
print("\n📋 修复摘要:")
print(f" 日志目录: {logs_dir.absolute()}")
print(f" 日志文件: {log_file.absolute()}")
print(f" 文件大小: {log_file.stat().st_size} 字节")
print(f" 创建时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
print("\n🔍 下一步操作:")
print(" 1. 重启 KaMiXiTong 应用")
print(" 2. 检查日志是否正常写入: tail -f logs/kamaxitong.log")
print(" 3. 监控日志轮转是否正常")
print("\n💡 提示:")
print(" - 如果仍有问题,请检查是否有其他进程占用日志文件")
print(" - 在生产环境中,建议使用外部日志系统(如 ELK")
print(" - 可以通过设置 LOG_LEVEL=DEBUG 来获取更详细的日志")
return True
def check_windows_processes():
"""检查可能占用日志文件的Windows进程"""
print("\n" + "=" * 60)
print("🔍 检查占用日志文件的进程")
print("=" * 60)
log_file = Path('logs/kamaxitong.log')
if not log_file.exists():
print("❌ 日志文件不存在")
return
try:
import psutil
print(f"\n正在检查进程...")
found_processes = []
for proc in psutil.process_iter(['pid', 'name', 'open_files']):
try:
# 检查进程打开的文件
if proc.info['open_files']:
for file_path in proc.info['open_files']:
if 'kamaxitong.log' in str(file_path):
found_processes.append({
'pid': proc.info['pid'],
'name': proc.info['name'],
'file': str(file_path)
})
except (psutil.NoSuchProcess, psutil.AccessDenied):
pass
if found_processes:
print("\n⚠️ 发现以下进程占用日志文件:")
for proc in found_processes:
print(f" PID: {proc['pid']}, 进程: {proc['name']}")
print(f" 文件: {proc['file']}")
else:
print("\n✅ 没有发现占用日志文件的进程")
except ImportError:
print("\n⚠️ psutil 未安装,无法检查进程")
print(" 安装命令: pip install psutil")
def main():
"""主函数"""
# 修复日志问题
if not fix_logging_issues():
sys.exit(1)
# 检查Windows进程仅在Windows上
if os.name == 'nt':
try:
check_windows_processes()
except Exception as e:
print(f"\n⚠️ 进程检查失败: {str(e)}")
print("\n" + "=" * 60)
print("🎉 修复完成!")
print("=" * 60)
print("\n请重启应用以应用修复")
if __name__ == '__main__':
main()