<h1>日志记录教程</h1>

配置并使用ToolUniverse的全面日志系统

ToolUniverse provides a robust logging system to help you monitor tool execution, debug issues, and track research workflows.

Logging Overview


ToolUniverse 使用 Python 的标准日志模块,并结合增强的格式化和表情符号指示器。该日志系统提供:

  • 5个标准日志级别:DEBUG、INFO、WARNING、ERROR、CRITICAL

  • 1 自定义级别:进度(用于工作流程跟踪)

  • 表情符号指示器:用于不同消息类型的视觉提示

  • 灵活配置:环境变量、编程设置和按实例控制

Log Levels Explained


了解何时使用每个日志级别:

调试级别

使用时机:用于故障排除的详细诊断信息

  • 工具加载详情

  • API 请求/响应数据

  • 内部状态变化

  • 参数验证步骤

from tooluniverse import ToolUniverse
from tooluniverse.logging_config import setup_logging

# Enable DEBUG logging
setup_logging('DEBUG')

tu = ToolUniverse()
tu.load_tools()  # Will show detailed tool loading information

请提供您需要翻译的具体文本,我将根据您的要求进行翻译。

🔍 DEBUG: Tool files:
🔍 DEBUG: {
  "opentargets": "/path/to/opentarget_tools.json",
  "pubchem": "/path/to/pubchem_tools.json"
}

INFO 等级(默认)

使用时机:关于正常操作的常规信息

  • 工具注册确认

  • 工作流进度更新

  • 配置更改

  • 成功操作

# INFO is the default level
tu = ToolUniverse()
tu.register_custom_tool(MyCustomTool, "my_tool")
# Output: ℹ️ INFO: Custom tool 'my_tool' registered successfully!

请提供您需要翻译的具体文本,我将根据您的要求进行翻译。

ℹ️ INFO: Loading 245 tools from 12 categories
ℹ️ INFO: Custom tool 'protein_analyzer' registered successfully!

进度等级(自定义)

使用时机:跟踪长时间运行工作流的进度

  • 多步骤研究流程

  • 批量处理操作

  • 数据采集工作流程

from tooluniverse.logging_config import get_logger

logger = get_logger('workflow')

def drug_discovery_pipeline(compounds):
    logger.progress(f"Starting analysis of {len(compounds)} compounds")

    for i, compound in enumerate(compounds):
        logger.progress(f"Processing compound {i+1}/{len(compounds)}: {compound}")
        # ... processing logic ...

    logger.progress("Drug discovery pipeline completed")

请提供您需要翻译的具体文本,我将根据您的要求进行翻译。

📈 PROGRESS: Starting analysis of 150 compounds
📈 PROGRESS: Processing compound 1/150: aspirin
📈 PROGRESS: Processing compound 2/150: ibuprofen

警告级别

使用时机:发生了意外情况,但执行仍然继续进行

  • API 速率限制

  • 已弃用的工具使用

  • 缺少可选参数

  • 回退操作

# Warnings appear automatically when issues occur
result = tu.run({
    "name": "NonExistentTool",  # This will trigger a warning
    "arguments": {"query": "test"}
})

请提供您需要翻译的具体文本,我将根据您的要求进行翻译。

⚠️ WARNING: Tool 'NonExistentTool' not found, similar tools: ['ExistingTool1', 'ExistingTool2']

错误级别

使用时机:导致特定操作无法进行的严重问题

  • 工具执行失败

  • API 认证错误

  • 无效参数

  • 网络超时

请提供您需要翻译的具体文本,我将根据您的要求进行翻译。

❌ ERROR: Failed to execute tool 'PubChem_search': Invalid API key
❌ ERROR: OpenTargets query timeout after 30 seconds

关键级别

使用时机:可能导致程序停止的严重错误

  • 系统级故障

  • 配置损坏

  • 资源耗尽

请提供您需要翻译的具体文本,我将根据您的要求进行翻译。

🚨 CRITICAL: Failed to initialize ToolUniverse: Configuration file corrupted

️ Configuration Methods

方法二:全局配置

以编程方式设置所有 ToolUniverse 操作的日志级别:

from tooluniverse.logging_config import setup_logging
from tooluniverse import ToolUniverse

# Configure logging before creating ToolUniverse instances
setup_logging('WARNING')  # Only show warnings and errors

tu = ToolUniverse()
tu.load_tools()  # Will use WARNING level

方法三:逐实例配置

为不同的 ToolUniverse 实例设置不同的日志级别:

from tooluniverse import ToolUniverse

# Create instances with different log levels
debug_tu = ToolUniverse(log_level='DEBUG')    # Detailed logging
quiet_tu = ToolUniverse(log_level='ERROR')    # Only errors

# Default instance uses global/environment setting
default_tu = ToolUniverse()

方法四:动态电平变化

执行过程中更改日志级别:

from tooluniverse.logging_config import set_log_level
from tooluniverse import ToolUniverse

tu = ToolUniverse()

# Start with minimal logging
set_log_level('ERROR')
tu.load_tools()  # Quiet loading

# Enable verbose logging for debugging
set_log_level('DEBUG')
result = tu.run({"name": "PubChem_search", "arguments": {"query": "aspirin"}})

# Return to normal logging
set_log_level('INFO')

️ Custom Logging in Your Code

在您的脚本中使用 ToolUniverse Logger

from tooluniverse.logging_config import get_logger

# Get a logger for your module
logger = get_logger('my_research_script')

def analyze_compounds(compound_list):
    logger.info(f"Starting analysis of {len(compound_list)} compounds")

    results = []
    for i, compound in enumerate(compound_list):
        logger.debug(f"Processing {compound}")

        try:
            # Your analysis logic here
            result = perform_analysis(compound)
            results.append(result)
            logger.progress(f"Completed {i+1}/{len(compound_list)} compounds")

        except Exception as e:
            logger.error(f"Failed to analyze {compound}: {e}")
            continue

    logger.info(f"Analysis completed. {len(results)} successful results")
    return results

便捷功能

ToolUniverse 提供便捷的快速日志记录功能:

  from tooluniverse.logging_config import debug, info, warning, error, critical, progress

  # Quick logging without creating logger instances
  info("Starting research workflow")
  debug("Loading configuration from file")
  progress("Processing 25% complete")
  warning("API rate limit approaching")
  error("Tool execution failed")
  critical("System resources exhausted")

Common Logging Patterns

研究工作流程日志记录

from tooluniverse import ToolUniverse
from tooluniverse.logging_config import get_logger, setup_logging

# Setup logging for research workflow
setup_logging('INFO')
logger = get_logger('drug_discovery')

def drug_discovery_workflow(target_disease):
    logger.info(f"🎯 Starting drug discovery for: {target_disease}")

    tu = ToolUniverse()
    tu.load_tools()

    # Step 1: Find disease targets
    logger.progress("Step 1: Identifying disease targets")
    targets_query = {
        "name": "OpenTargets_get_associated_targets_by_disease_name",
        "arguments": {"diseaseName": target_disease, "limit": 10}
    }

    try:
        targets = tu.run(targets_query)
        logger.info(f"✅ Found {len(targets.get('data', []))} targets")
    except Exception as e:
        logger.error(f"❌ Target identification failed: {e}")
        return None

    # Step 2: Find compounds
    logger.progress("Step 2: Searching for compounds")
    # ... more workflow steps ...

    logger.info("🎉 Drug discovery workflow completed successfully")
    return results

调试失败的工具

from tooluniverse import ToolUniverse
from tooluniverse.logging_config import setup_logging

# Enable debug logging to diagnose tool issues
setup_logging('DEBUG')

tu = ToolUniverse()
tu.load_tools()

# Debug a failing query
problematic_query = {
    "name": "PubChem_get_compound_info",
    "arguments": {"compound_name": "invalid_compound_name"}
}

try:
    result = tu.run(problematic_query)
except Exception as e:
    # Debug logs will show detailed error information
    print(f"Query failed: {e}")

批量处理与进度跟踪

  from tooluniverse import ToolUniverse
  from tooluniverse.logging_config import get_logger

  logger = get_logger('batch_processor')
  tu = ToolUniverse()
  tu.load_tools()

  def process_compound_batch(compounds):
      logger.info(f"🚀 Starting batch processing of {len(compounds)} compounds")

      results = []
      errors = []

      for i, compound in enumerate(compounds):
          logger.progress(f"Processing {i+1}/{len(compounds)}: {compound}")

          query = {
              "name": "PubChem_get_compound_info",
              "arguments": {"compound_name": compound}
          }

          try:
              result = tu.run(query)
              results.append(result)
              logger.debug(f"✅ Successfully processed {compound}")
          except Exception as e:
              errors.append((compound, str(e)))
              logger.warning(f"⚠️ Failed to process {compound}: {e}")

      logger.info(f"📊 Batch complete: {len(results)} successful, {len(errors)} failed")
      return results, errors

Best Practices

选择合适的日志级别

  • 生产环境:使用 INFO 或 WARNING 级别以减少噪音

  • 开发:使用 DEBUG 进行详细诊断

  • CI/CD:使用 ERROR 仅显示失败信息

  • 演示:使用 PROGRESS 显示工作流程步骤

import os
from tooluniverse.logging_config import setup_logging

# Environment-based logging configuration
if os.getenv('ENVIRONMENT') == 'production':
    setup_logging('WARNING')
elif os.getenv('ENVIRONMENT') == 'development':
    setup_logging('DEBUG')
else:
    setup_logging('INFO')  # Default

构建您的日志消息结构

使用统一的格式以提升可读性:

logger = get_logger('workflow')

# Good: Clear, actionable messages
logger.info("🎯 Starting protein analysis workflow")
logger.progress("Step 1/5: Loading protein sequences")
logger.error("❌ PubChem API returned 404 for compound 'xyz123'")

# Avoid: Vague or uninformative messages
logger.info("Processing")  # Too vague
logger.debug("Data: " + str(huge_dict))  # Too much data

记录重要上下文

包含调试相关的详细信息:

  logger = get_logger('tool_executor')

  def execute_tool_safely(tool_name, arguments):
      logger.debug(f"Executing tool: {tool_name}")
      logger.debug(f"Arguments: {arguments}")

      try:
          result = tu.run({"name": tool_name, "arguments": arguments})
          logger.info(f"✅ Tool '{tool_name}' completed successfully")
          return result
      except Exception as e:
          logger.error(f"❌ Tool '{tool_name}' failed: {e}")
          logger.debug(f"Full traceback:", exc_info=True)  # Include stack trace in debug
          raise

Troubleshooting Logging

常见问题及解决方案

问题:无日志消息显示

# Solution: Check if logging is configured
from tooluniverse.logging_config import setup_logging
setup_logging('DEBUG')  # Ensure logging is enabled

问题:日志消息过多

# Solution: Increase log level to reduce verbosity
from tooluniverse.logging_config import set_log_level
set_log_level('WARNING')  # Only warnings and errors

问题:日志消息未显示表情符号

# This is normal in some terminals. The logging still works,
# just without emoji indicators. No action needed.

问题:希望禁用所有日志记录

# Solution: Set to CRITICAL level
from tooluniverse.logging_config import setup_logging
setup_logging('CRITICAL')

检查当前日志级别

  from tooluniverse.logging_config import get_logger

  logger = get_logger()
  current_level = logger.getEffectiveLevel()
  print(f"Current log level: {current_level}")

  # Level numbers: DEBUG=10, INFO=20, PROGRESS=25, WARNING=30, ERROR=40, CRITICAL=50

Log Output Examples

以下是不同日志级别的实际示例:

  🔍 DEBUG: Tool files loaded from: /path/to/tools/
  🔍 DEBUG: Validating parameters for PubChem_search
  ℹ️ INFO: Loading 245 tools from 12 categories
  📈 PROGRESS: Processing compound 15/100: caffeine
  ⚠️ WARNING: API rate limit reached, waiting 2 seconds
  ❌ ERROR: OpenTargets query failed: Connection timeout
  🚨 CRITICAL: Failed to initialize tool registry

Next Steps

既然您已经了解了 ToolUniverse 的日志记录:

  • ** Workflows** → 科学工作流 - Apply logging to scientific workflows

  • ** Extend Tools** → 导航 - Add logging to custom tools

  • ** Troubleshooting** → 故障排除教程 - Debug common logging issues

小技巧

专业提示:日常使用建议从 INFO 级别开始,排查问题时切换到 DEBUG 级别,长时间运行的工作流则使用 PROGRESS 级别以跟踪执行进度!