vs_log_macros.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. # vs_log_macros.py
  2. import logging
  3. from logging.handlers import RotatingFileHandler
  4. import os
  5. import sys
  6. # --- 日志配置 ---
  7. # 1. 确保日志目录存在
  8. LOG_DIR = "logs"
  9. if not os.path.exists(LOG_DIR):
  10. os.makedirs(LOG_DIR)
  11. LOG_FILE = os.path.join(LOG_DIR, "vs_app.log")
  12. # 2. 定义日志格式 (包含时间)
  13. # 格式示例:[2023-10-27 10:30:01] [INFO] [MainThread] [TAG] Message...
  14. LOG_FORMAT = '[%(asctime)s][%(levelname)s][%(threadName)s]%(message)s'
  15. DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
  16. # 3. 获取日志级别
  17. log_level_str = os.environ.get("VSC_LOG_LEVEL", "INFO").upper()
  18. log_level = getattr(logging, log_level_str, logging.INFO)
  19. # 4. 配置日志滚动参数 (支持通过环境变量覆盖)
  20. # 默认单个日志文件大小: 10 MB (10 * 1024 * 1024 bytes)
  21. MAX_BYTES = int(os.environ.get("VSC_LOG_MAX_BYTES", 10 * 1024 * 1024))
  22. # 默认保留的备份文件数量: 5
  23. BACKUP_COUNT = int(os.environ.get("VSC_LOG_BACKUP_COUNT", 10))
  24. # 5. 创建 handlers
  25. # 控制台 handler
  26. console_handler = logging.StreamHandler(sys.stdout)
  27. # 滚动文件 handler
  28. rolling_file_handler = RotatingFileHandler(
  29. filename=LOG_FILE,
  30. mode='a',
  31. maxBytes=MAX_BYTES,
  32. backupCount=BACKUP_COUNT,
  33. encoding='utf-8'
  34. )
  35. # 6. 配置 logging (同时输出到控制台和滚动文件)
  36. logging.basicConfig(
  37. level=log_level,
  38. format=LOG_FORMAT,
  39. datefmt=DATE_FORMAT,
  40. handlers=[
  41. console_handler,
  42. rolling_file_handler
  43. ]
  44. )
  45. # --- 宏定义 ---
  46. def VSC_INFO(tag, message, *args):
  47. """
  48. Usage: VSC_INFO("network", "Connected to %s:%d", ip, port)
  49. Output: [Time][INFO][Thread][network]Connected to 127.0.0.1:80
  50. """
  51. logging.info(f"[{tag}]{message}", *args)
  52. def VSC_DEBUG(tag, message, *args):
  53. logging.debug(f"[{tag}]{message}", *args)
  54. def VSC_WARN(tag, message, *args):
  55. logging.warning(f"[{tag}]{message}", *args)
  56. def VSC_ERROR(tag, message, *args):
  57. logging.error(f"[{tag}]{message}", *args)