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