#!/usr/bin/env python3 """ 日志系统诊断脚本 用于排查新环境中日志文件无法创建的问题 """ import os import sys import logging import traceback from datetime import datetime def check_environment(): """检查环境信息""" print("=" * 60) print("环境诊断信息") print("=" * 60) print(f"Python版本: {sys.version}") print(f"当前工作目录: {os.getcwd()}") print(f"当前用户: {os.getenv('USERNAME', 'Unknown')}") print(f"操作系统: {os.name}") print(f"平台: {sys.platform}") # 检查logs目录 logs_dir = "logs" print(f"\nlogs目录检查:") print(f" logs目录是否存在: {os.path.exists(logs_dir)}") if os.path.exists(logs_dir): try: stat_info = os.stat(logs_dir) print(f" logs目录权限: {oct(stat_info.st_mode)[-3:]}") print(f" logs目录所有者: {stat_info.st_uid}") print(f" logs目录大小: {stat_info.st_size} bytes") except Exception as e: print(f" 获取logs目录信息失败: {e}") else: print(" logs目录不存在,将尝试创建") try: os.makedirs(logs_dir, exist_ok=True) print(f" logs目录创建成功: {os.path.exists(logs_dir)}") except Exception as e: print(f" logs目录创建失败: {e}") def test_basic_logging(): """测试基础日志功能""" print("\n" + "=" * 60) print("基础日志测试") print("=" * 60) # 测试标准logging模块 print("1. 测试标准logging模块:") try: basic_logger = logging.getLogger("basic_test") basic_logger.setLevel(logging.INFO) # 创建文件处理器 file_handler = logging.FileHandler("logs/basic_test.log", encoding='utf-8') file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) basic_logger.addHandler(file_handler) basic_logger.info("基础日志测试 - INFO") basic_logger.error("基础日志测试 - ERROR") print(" ✅ 基础日志测试成功") # 检查文件是否创建 if os.path.exists("logs/basic_test.log"): with open("logs/basic_test.log", "r", encoding='utf-8') as f: content = f.read() print(f" ✅ 日志文件创建成功,内容长度: {len(content)} 字符") else: print(" ❌ 日志文件未创建") except Exception as e: print(f" ❌ 基础日志测试失败: {e}") traceback.print_exc() def test_structured_logging(): """测试结构化日志功能""" print("\n" + "=" * 60) print("结构化日志测试") print("=" * 60) try: # 导入结构化日志模块 print("1. 导入结构化日志模块:") from app.utils.structured_log import get_structured_logger, LogLevel print(" ✅ 结构化日志模块导入成功") # 创建结构化日志记录器 print("2. 创建结构化日志记录器:") logger = get_structured_logger("debug_test", LogLevel.DEBUG) print(" ✅ 结构化日志记录器创建成功") # 测试日志记录 print("3. 测试日志记录:") logger.info("结构化日志测试 - INFO", test_param="test_value") logger.error("结构化日志测试 - ERROR", error_code=500) print(" ✅ 日志记录调用成功") # 检查日志文件 print("4. 检查日志文件:") app_log_exists = os.path.exists("logs/app.log") error_log_exists = os.path.exists("logs/error.log") print(f" app.log存在: {app_log_exists}") print(f" error.log存在: {error_log_exists}") if app_log_exists: with open("logs/app.log", "r", encoding='utf-8') as f: lines = f.readlines() print(f" app.log行数: {len(lines)}") if lines: last_line = lines[-1].strip() print(f" 最后一行: {last_line[:100]}...") if error_log_exists: with open("logs/error.log", "r", encoding='utf-8') as f: lines = f.readlines() print(f" error.log行数: {len(lines)}") if lines: last_line = lines[-1].strip() print(f" 最后一行: {last_line[:100]}...") print(" ✅ 结构化日志测试完成") except ImportError as e: print(f" ❌ 导入结构化日志模块失败: {e}") traceback.print_exc() except Exception as e: print(f" ❌ 结构化日志测试失败: {e}") traceback.print_exc() def test_file_permissions(): """测试文件权限""" print("\n" + "=" * 60) print("文件权限测试") print("=" * 60) test_files = [ "logs/test_write.txt", "logs/test_append.txt" ] for test_file in test_files: print(f"\n测试文件: {test_file}") # 测试写入 try: with open(test_file, "w", encoding='utf-8') as f: f.write(f"测试写入 - {datetime.now()}\n") print(f" ✅ 写入测试成功") except Exception as e: print(f" ❌ 写入测试失败: {e}") # 测试追加 try: with open(test_file, "a", encoding='utf-8') as f: f.write(f"测试追加 - {datetime.now()}\n") print(f" ✅ 追加测试成功") except Exception as e: print(f" ❌ 追加测试失败: {e}") # 检查文件 if os.path.exists(test_file): try: stat_info = os.stat(test_file) print(f" ✅ 文件存在,大小: {stat_info.st_size} bytes") except Exception as e: print(f" ❌ 获取文件信息失败: {e}") else: print(f" ❌ 文件不存在") def main(): """主函数""" print("日志系统诊断工具") print("=" * 60) print(f"诊断时间: {datetime.now()}") try: # 检查环境 check_environment() # 测试基础日志 test_basic_logging() # 测试结构化日志 test_structured_logging() # 测试文件权限 test_file_permissions() print("\n" + "=" * 60) print("诊断完成") print("=" * 60) except Exception as e: print(f"\n诊断过程中发生错误: {e}") traceback.print_exc() if __name__ == "__main__": main()