- Add archive_old_logs() method to LoggerManager in log_utils.py - Logs are automatically moved to Archive/YYYY-MM/ directory when new log is created - Create archive_existing_logs.py script for one-time migration of existing logs - Archive 386 existing log files into organized year-month structure - Keep only current log file in log/ root directory for cleaner management 🤖 Generated with [Qoder][https://lingma.aliyun.com]
93 lines
2.5 KiB
Python
93 lines
2.5 KiB
Python
#!/usr/bin/env python
|
|
# -*- coding: utf-8 -*-
|
|
"""
|
|
一次性脚本:将 log/ 根目录下的所有历史日志按年月移动到 Archive/ 目录
|
|
|
|
使用方法:
|
|
python archive_existing_logs.py
|
|
"""
|
|
import os
|
|
import shutil
|
|
import re
|
|
from datetime import datetime
|
|
from typing import Optional
|
|
|
|
|
|
def extract_year_month_from_filename(filename: str) -> Optional[str]:
|
|
"""从日志文件名中提取年月信息
|
|
|
|
支持的格式:
|
|
- prefix_YYYYMMDD_HHMMSS.log
|
|
- incremental_YYYYMMDD_HHMMSS.log
|
|
- full_sync_YYYYMMDD_HHMMSS.log
|
|
- excel_sync_YYYYMMDD_HHMMSS.log
|
|
"""
|
|
match = re.search(r'(\d{4})(\d{2})\d{2}_\d{6}', filename)
|
|
if match:
|
|
year = match.group(1)
|
|
month = match.group(2)
|
|
return f"{year}-{month}"
|
|
|
|
return None
|
|
|
|
|
|
def archive_existing_logs():
|
|
"""归档现有的所有日志文件到 Archive/YYYY-MM/ 目录"""
|
|
log_dir = os.path.join(os.getcwd(), "log")
|
|
archive_base = os.path.join(log_dir, "Archive")
|
|
|
|
if not os.path.exists(log_dir):
|
|
print(f"日志目录不存在: {log_dir}")
|
|
return
|
|
|
|
os.makedirs(archive_base, exist_ok=True)
|
|
|
|
moved_count = 0
|
|
skipped_count = 0
|
|
|
|
for filename in os.listdir(log_dir):
|
|
if not filename.endswith('.log'):
|
|
continue
|
|
|
|
src = os.path.join(log_dir, filename)
|
|
|
|
# 跳过目录
|
|
if os.path.isdir(src):
|
|
continue
|
|
|
|
# 提取年月信息
|
|
year_month = extract_year_month_from_filename(filename)
|
|
|
|
# 如果无法从文件名提取,使用文件修改时间
|
|
if not year_month:
|
|
try:
|
|
stat = os.stat(src)
|
|
mtime = datetime.fromtimestamp(stat.st_mtime)
|
|
year_month = mtime.strftime("%Y-%m")
|
|
except:
|
|
year_month = "unknown"
|
|
|
|
# 创建年月子目录
|
|
month_dir = os.path.join(archive_base, year_month)
|
|
os.makedirs(month_dir, exist_ok=True)
|
|
|
|
# 移动文件
|
|
dst = os.path.join(month_dir, filename)
|
|
|
|
try:
|
|
shutil.move(src, dst)
|
|
moved_count += 1
|
|
print(f"[OK] {filename} -> Archive/{year_month}/")
|
|
except Exception as e:
|
|
print(f"[FAIL] 移动失败 {filename}: {e}")
|
|
skipped_count += 1
|
|
|
|
print(f"\n完成!")
|
|
print(f" 已归档: {moved_count} 个文件")
|
|
print(f" 失败: {skipped_count} 个文件")
|
|
print(f" 归档路径: {archive_base}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
archive_existing_logs()
|