vs_log_macros.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. # vs_log_macros.py
  2. import logging
  3. import os
  4. import sys
  5. # --- 日志配置 ---
  6. # 1. 确保日志目录存在
  7. LOG_DIR = "logs"
  8. if not os.path.exists(LOG_DIR):
  9. os.makedirs(LOG_DIR)
  10. LOG_FILE = os.path.join(LOG_DIR, "vs_app.log")
  11. # 2. 定义日志格式 (包含时间)
  12. # 格式示例: [2023-10-27 10:30:01] [INFO] [MainThread] [TAG] Message...
  13. LOG_FORMAT = '[%(asctime)s] [%(levelname)s] [%(threadName)s] %(message)s'
  14. DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
  15. # 3. 获取日志级别
  16. log_level_str = os.environ.get("VSC_LOG_LEVEL", "INFO").upper()
  17. log_level = getattr(logging, log_level_str, logging.INFO)
  18. # 4. 配置 logging (同时输出到控制台和文件)
  19. logging.basicConfig(
  20. level=log_level,
  21. format=LOG_FORMAT,
  22. datefmt=DATE_FORMAT,
  23. handlers=[
  24. # 输出到控制台
  25. logging.StreamHandler(sys.stdout),
  26. # 输出到文件 (追加模式,UTF-8编码)
  27. logging.FileHandler(LOG_FILE, mode='a', encoding='utf-8')
  28. ]
  29. )
  30. # --- 宏定义 ---
  31. def VSC_INFO(tag, message, *args):
  32. """
  33. Usage: VSC_INFO("network", "Connected to %s:%d", ip, port)
  34. Output: [Time] [INFO] [Thread] [network] Connected to 127.0.0.1:80
  35. """
  36. logging.info(f"[{tag}] {message}", *args)
  37. def VSC_DEBUG(tag, message, *args):
  38. logging.debug(f"[{tag}] {message}", *args)
  39. def VSC_WARN(tag, message, *args):
  40. logging.warning(f"[{tag}] {message}", *args)
  41. def VSC_ERROR(tag, message, *args):
  42. logging.error(f"[{tag}] {message}", *args)