- 修改config.py中的文件路径和定时发送时间 - 在各个脚本中添加日志记录功能,提升错误追踪和调试能力 - 更新README.md,详细说明程序功能和使用方法 - 重构scheduler.py、sendmsg.py、send_openmsg.py和send_filemsg.py,增强代码可读性和可维护性
232 lines
8.0 KiB
Python
232 lines
8.0 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
日志查看工具
|
|
用于快速查看和搜索wxmsg程序的日志文件
|
|
"""
|
|
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
from datetime import datetime, timedelta
|
|
import argparse
|
|
|
|
def list_log_files():
|
|
"""列出所有可用的日志文件"""
|
|
logs_dir = Path("wxauto_logs")
|
|
if not logs_dir.exists():
|
|
print("❌ 日志目录不存在: wxauto_logs/")
|
|
return []
|
|
|
|
log_files = []
|
|
for log_file in logs_dir.glob("*.log"):
|
|
stat = log_file.stat()
|
|
size_mb = stat.st_size / (1024 * 1024)
|
|
modified_time = datetime.fromtimestamp(stat.st_mtime)
|
|
|
|
log_files.append({
|
|
'name': log_file.name,
|
|
'path': log_file,
|
|
'size_mb': size_mb,
|
|
'modified': modified_time
|
|
})
|
|
|
|
# 按修改时间排序,最新的在前
|
|
log_files.sort(key=lambda x: x['modified'], reverse=True)
|
|
|
|
return log_files
|
|
|
|
def show_log_files():
|
|
"""显示日志文件列表"""
|
|
log_files = list_log_files()
|
|
|
|
if not log_files:
|
|
print("📁 没有找到日志文件")
|
|
return
|
|
|
|
print("📋 可用的日志文件:")
|
|
print("=" * 80)
|
|
print(f"{'文件名':<30} {'大小(MB)':<10} {'最后修改':<20} {'状态'}")
|
|
print("=" * 80)
|
|
|
|
for log_file in log_files:
|
|
status = "🟢 最新" if log_file['modified'].date() == datetime.now().date() else "🟡 旧"
|
|
print(f"{log_file['name']:<30} {log_file['size_mb']:<10.2f} {log_file['modified'].strftime('%Y-%m-%d %H:%M:%S'):<20} {status}")
|
|
|
|
print("=" * 80)
|
|
|
|
def view_log_file(filename, lines=50, search=None, level=None):
|
|
"""查看指定的日志文件"""
|
|
logs_dir = Path("wxauto_logs")
|
|
log_path = logs_dir / filename
|
|
|
|
if not log_path.exists():
|
|
print(f"❌ 日志文件不存在: {filename}")
|
|
return
|
|
|
|
print(f"📖 查看日志文件: {filename}")
|
|
print(f"📁 文件路径: {log_path.absolute()}")
|
|
print(f"📊 文件大小: {log_path.stat().st_size / 1024:.2f} KB")
|
|
print("=" * 80)
|
|
|
|
try:
|
|
with open(log_path, 'r', encoding='utf-8') as f:
|
|
all_lines = f.readlines()
|
|
|
|
# 过滤行
|
|
filtered_lines = []
|
|
for line in all_lines:
|
|
# 按级别过滤
|
|
if level and level.upper() not in line.upper():
|
|
continue
|
|
# 按搜索词过滤
|
|
if search and search.lower() not in line.lower():
|
|
continue
|
|
filtered_lines.append(line)
|
|
|
|
# 显示最后N行
|
|
if lines > 0:
|
|
filtered_lines = filtered_lines[-lines:]
|
|
|
|
if not filtered_lines:
|
|
print("🔍 没有找到匹配的日志条目")
|
|
return
|
|
|
|
print(f"📝 显示 {len(filtered_lines)} 条日志条目:")
|
|
print("-" * 80)
|
|
|
|
for line in filtered_lines:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
|
|
# 高亮显示不同级别的日志
|
|
if "ERROR" in line:
|
|
print(f"🔴 {line}")
|
|
elif "WARNING" in line:
|
|
print(f"🟡 {line}")
|
|
elif "INFO" in line:
|
|
print(f"🔵 {line}")
|
|
elif "DEBUG" in line:
|
|
print(f"⚪ {line}")
|
|
else:
|
|
print(f" {line}")
|
|
|
|
except Exception as e:
|
|
print(f"❌ 读取日志文件失败: {str(e)}")
|
|
|
|
def search_logs(search_term, level=None, days=1):
|
|
"""搜索所有日志文件"""
|
|
logs_dir = Path("wxauto_logs")
|
|
if not logs_dir.exists():
|
|
print("❌ 日志目录不存在: wxauto_logs/")
|
|
return
|
|
|
|
print(f"🔍 在所有日志文件中搜索: '{search_term}'")
|
|
if level:
|
|
print(f"📊 日志级别: {level}")
|
|
print(f"📅 搜索范围: 最近 {days} 天")
|
|
print("=" * 80)
|
|
|
|
found_count = 0
|
|
cutoff_date = datetime.now() - timedelta(days=days)
|
|
|
|
for log_file in logs_dir.glob("*.log"):
|
|
try:
|
|
stat = log_file.stat()
|
|
modified_time = datetime.fromtimestamp(stat.st_mtime)
|
|
|
|
# 检查文件是否在时间范围内
|
|
if modified_time < cutoff_date:
|
|
continue
|
|
|
|
with open(log_file, 'r', encoding='utf-8') as f:
|
|
file_lines = f.readlines()
|
|
|
|
matching_lines = []
|
|
for line in file_lines:
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
|
|
# 按级别过滤
|
|
if level and level.upper() not in line.upper():
|
|
continue
|
|
# 按搜索词过滤
|
|
if search_term.lower() in line.lower():
|
|
matching_lines.append(line)
|
|
|
|
if matching_lines:
|
|
print(f"\n📁 文件: {log_file.name}")
|
|
print(f"📅 修改时间: {modified_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
|
print(f"🔍 找到 {len(matching_lines)} 条匹配记录:")
|
|
print("-" * 60)
|
|
|
|
for line in matching_lines[:20]: # 限制每个文件显示20条
|
|
# 高亮显示不同级别的日志
|
|
if "ERROR" in line:
|
|
print(f"🔴 {line}")
|
|
elif "WARNING" in line:
|
|
print(f"🟡 {line}")
|
|
elif "INFO" in line:
|
|
print(f"🔵 {line}")
|
|
elif "DEBUG" in line:
|
|
print(f"⚪ {line}")
|
|
else:
|
|
print(f" {line}")
|
|
|
|
if len(matching_lines) > 20:
|
|
print(f"... 还有 {len(matching_lines) - 20} 条记录")
|
|
|
|
found_count += len(matching_lines)
|
|
|
|
except Exception as e:
|
|
print(f"❌ 读取文件 {log_file.name} 失败: {str(e)}")
|
|
|
|
print("=" * 80)
|
|
print(f"🔍 搜索完成,总共找到 {found_count} 条匹配记录")
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description="WXMSG日志查看工具")
|
|
parser.add_argument("action", choices=["list", "view", "search"],
|
|
help="操作类型: list(列出文件), view(查看文件), search(搜索)")
|
|
parser.add_argument("--file", "-f", help="要查看的日志文件名")
|
|
parser.add_argument("--lines", "-n", type=int, default=50,
|
|
help="显示的行数 (默认: 50, 0表示全部)")
|
|
parser.add_argument("--search", "-s", help="搜索关键词")
|
|
parser.add_argument("--level", "-l", choices=["INFO", "WARNING", "ERROR", "DEBUG"],
|
|
help="按日志级别过滤")
|
|
parser.add_argument("--days", "-d", type=int, default=1,
|
|
help="搜索最近几天的日志 (默认: 1)")
|
|
|
|
args = parser.parse_args()
|
|
|
|
if args.action == "list":
|
|
show_log_files()
|
|
|
|
elif args.action == "view":
|
|
if not args.file:
|
|
print("❌ 请指定要查看的日志文件名")
|
|
print("💡 使用 --file 参数或先运行 'python view_logs.py list' 查看可用文件")
|
|
return
|
|
view_log_file(args.file, args.lines, args.search, args.level)
|
|
|
|
elif args.action == "search":
|
|
if not args.search:
|
|
print("❌ 请指定搜索关键词")
|
|
print("💡 使用 --search 参数指定要搜索的内容")
|
|
return
|
|
search_logs(args.search, args.level, args.days)
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) == 1:
|
|
print("🔧 WXMSG日志查看工具")
|
|
print("=" * 40)
|
|
print("用法:")
|
|
print(" python view_logs.py list # 列出所有日志文件")
|
|
print(" python view_logs.py view -f filename.log # 查看指定日志文件")
|
|
print(" python view_logs.py search -s keyword # 搜索日志内容")
|
|
print("\n更多帮助: python view_logs.py --help")
|
|
print("=" * 40)
|
|
else:
|
|
main()
|