|
| 1 | +#!/usr/bin/env python3 |
| 2 | +# -*- coding: utf-8 -*- |
| 3 | +""" |
| 4 | +VulnShop 日志模块 |
| 5 | +
|
| 6 | +使用Python内置logging库,支持: |
| 7 | +- 同时输出到控制台和文件 |
| 8 | +- 滚动日志文件(RotatingFileHandler) |
| 9 | +- 通过JSON配置文件进行配置 |
| 10 | +- 多个日志器:主日志、访问日志、SQL日志、错误日志 |
| 11 | +""" |
| 12 | + |
| 13 | +import os |
| 14 | +import json |
| 15 | +import logging |
| 16 | +import logging.config |
| 17 | +import logging.handlers |
| 18 | +from pathlib import Path |
| 19 | + |
| 20 | + |
| 21 | +# 日志目录 |
| 22 | +LOG_DIR = Path(__file__).parent / "logs" |
| 23 | +CONFIG_FILE = Path(__file__).parent / "logging_config.json" |
| 24 | + |
| 25 | +# 默认配置(当配置文件不存在时使用) |
| 26 | +DEFAULT_CONFIG = { |
| 27 | + "version": 1, |
| 28 | + "disable_existing_loggers": False, |
| 29 | + "formatters": { |
| 30 | + "standard": { |
| 31 | + "format": "[%(asctime)s] %(levelname)-8s %(name)s - %(message)s", |
| 32 | + "datefmt": "%Y-%m-%d %H:%M:%S" |
| 33 | + }, |
| 34 | + "detailed": { |
| 35 | + "format": "[%(asctime)s] %(levelname)-8s [%(name)s:%(funcName)s:%(lineno)d] - %(message)s", |
| 36 | + "datefmt": "%Y-%m-%d %H:%M:%S" |
| 37 | + }, |
| 38 | + "access": { |
| 39 | + "format": "[%(asctime)s] %(message)s", |
| 40 | + "datefmt": "%Y-%m-%d %H:%M:%S" |
| 41 | + } |
| 42 | + }, |
| 43 | + "handlers": { |
| 44 | + "console": { |
| 45 | + "class": "logging.StreamHandler", |
| 46 | + "level": "DEBUG", |
| 47 | + "formatter": "standard", |
| 48 | + "stream": "ext://sys.stdout" |
| 49 | + }, |
| 50 | + "file": { |
| 51 | + "class": "logging.handlers.RotatingFileHandler", |
| 52 | + "level": "DEBUG", |
| 53 | + "formatter": "detailed", |
| 54 | + "filename": str(LOG_DIR / "vulnshop.log"), |
| 55 | + "maxBytes": 10485760, # 10MB |
| 56 | + "backupCount": 5, |
| 57 | + "encoding": "utf-8" |
| 58 | + }, |
| 59 | + "access_file": { |
| 60 | + "class": "logging.handlers.RotatingFileHandler", |
| 61 | + "level": "INFO", |
| 62 | + "formatter": "access", |
| 63 | + "filename": str(LOG_DIR / "access.log"), |
| 64 | + "maxBytes": 10485760, |
| 65 | + "backupCount": 5, |
| 66 | + "encoding": "utf-8" |
| 67 | + }, |
| 68 | + "error_file": { |
| 69 | + "class": "logging.handlers.RotatingFileHandler", |
| 70 | + "level": "ERROR", |
| 71 | + "formatter": "detailed", |
| 72 | + "filename": str(LOG_DIR / "error.log"), |
| 73 | + "maxBytes": 5242880, # 5MB |
| 74 | + "backupCount": 3, |
| 75 | + "encoding": "utf-8" |
| 76 | + } |
| 77 | + }, |
| 78 | + "loggers": { |
| 79 | + "vulnshop": { |
| 80 | + "level": "DEBUG", |
| 81 | + "handlers": ["console", "file"], |
| 82 | + "propagate": False |
| 83 | + }, |
| 84 | + "vulnshop.access": { |
| 85 | + "level": "INFO", |
| 86 | + "handlers": ["console", "access_file"], |
| 87 | + "propagate": False |
| 88 | + }, |
| 89 | + "vulnshop.sql": { |
| 90 | + "level": "DEBUG", |
| 91 | + "handlers": ["console", "file"], |
| 92 | + "propagate": False |
| 93 | + }, |
| 94 | + "vulnshop.error": { |
| 95 | + "level": "ERROR", |
| 96 | + "handlers": ["console", "error_file"], |
| 97 | + "propagate": False |
| 98 | + } |
| 99 | + }, |
| 100 | + "root": { |
| 101 | + "level": "INFO", |
| 102 | + "handlers": ["console", "file"] |
| 103 | + } |
| 104 | +} |
| 105 | + |
| 106 | + |
| 107 | +def _ensure_log_dir(): |
| 108 | + """确保日志目录存在""" |
| 109 | + LOG_DIR.mkdir(parents=True, exist_ok=True) |
| 110 | + |
| 111 | + |
| 112 | +def _fix_log_paths(config: dict) -> dict: |
| 113 | + """修正配置中的日志文件路径为绝对路径""" |
| 114 | + handlers = config.get("handlers", {}) |
| 115 | + for handler_name, handler_config in handlers.items(): |
| 116 | + if "filename" in handler_config: |
| 117 | + filename = handler_config["filename"] |
| 118 | + # 如果是相对路径,转换为绝对路径 |
| 119 | + if not os.path.isabs(filename): |
| 120 | + handler_config["filename"] = str(LOG_DIR / os.path.basename(filename)) |
| 121 | + return config |
| 122 | + |
| 123 | + |
| 124 | +def load_config() -> dict: |
| 125 | + """加载日志配置""" |
| 126 | + _ensure_log_dir() |
| 127 | + |
| 128 | + if CONFIG_FILE.exists(): |
| 129 | + try: |
| 130 | + with open(CONFIG_FILE, 'r', encoding='utf-8') as f: |
| 131 | + config = json.load(f) |
| 132 | + return _fix_log_paths(config) |
| 133 | + except Exception as e: |
| 134 | + print(f"[WARNING] Failed to load logging config: {e}, using default config") |
| 135 | + return _fix_log_paths(DEFAULT_CONFIG.copy()) |
| 136 | + else: |
| 137 | + return _fix_log_paths(DEFAULT_CONFIG.copy()) |
| 138 | + |
| 139 | + |
| 140 | +def setup_logging(): |
| 141 | + """初始化日志系统""" |
| 142 | + config = load_config() |
| 143 | + logging.config.dictConfig(config) |
| 144 | + |
| 145 | + |
| 146 | +def get_logger(name: str = "vulnshop") -> logging.Logger: |
| 147 | + """ |
| 148 | + 获取日志器 |
| 149 | + |
| 150 | + Args: |
| 151 | + name: 日志器名称 |
| 152 | + - "vulnshop": 主日志器 |
| 153 | + - "vulnshop.access": 访问日志器 |
| 154 | + - "vulnshop.sql": SQL日志器 |
| 155 | + - "vulnshop.error": 错误日志器 |
| 156 | + |
| 157 | + Returns: |
| 158 | + logging.Logger: 日志器实例 |
| 159 | + """ |
| 160 | + return logging.getLogger(name) |
| 161 | + |
| 162 | + |
| 163 | +# 便捷函数 |
| 164 | +def get_main_logger() -> logging.Logger: |
| 165 | + """获取主日志器""" |
| 166 | + return get_logger("vulnshop") |
| 167 | + |
| 168 | + |
| 169 | +def get_access_logger() -> logging.Logger: |
| 170 | + """获取访问日志器""" |
| 171 | + return get_logger("vulnshop.access") |
| 172 | + |
| 173 | + |
| 174 | +def get_sql_logger() -> logging.Logger: |
| 175 | + """获取SQL日志器""" |
| 176 | + return get_logger("vulnshop.sql") |
| 177 | + |
| 178 | + |
| 179 | +def get_error_logger() -> logging.Logger: |
| 180 | + """获取错误日志器""" |
| 181 | + return get_logger("vulnshop.error") |
| 182 | + |
| 183 | + |
| 184 | +# 模块加载时自动初始化日志系统 |
| 185 | +setup_logging() |
| 186 | + |
| 187 | +# 导出的日志器实例 |
| 188 | +logger = get_main_logger() |
| 189 | +access_logger = get_access_logger() |
| 190 | +sql_logger = get_sql_logger() |
| 191 | +error_logger = get_error_logger() |
0 commit comments