> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tensorone.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Cluster Logs

> Retrieve and manage cluster logs for debugging, monitoring, and troubleshooting

## Overview

Cluster Logs provide comprehensive logging capabilities for GPU clusters including system logs, application logs, error logs, and audit trails. Essential for debugging issues, monitoring application behavior, and maintaining audit compliance.

## Endpoints

### Get Logs

```bash curl
GET https://api.tensorone.ai/v1/clusters/{cluster_id}/logs
```

### Stream Logs

```bash curl
GET https://api.tensorone.ai/v1/clusters/{cluster_id}/logs/stream
```

### Search Logs

```bash curl
POST https://api.tensorone.ai/v1/clusters/{cluster_id}/logs/search
```

### Download Logs

```bash curl
GET https://api.tensorone.ai/v1/clusters/{cluster_id}/logs/download
```

## Get Logs

### Query Parameters

| Parameter | Type | Required | Description |
| - | - | - | - |
| `log_type` | string | No | Log type: `system`, `application`, `error`, `audit`, `docker`, `gpu` |
| `level` | string | No | Log level: `debug`, `info`, `warn`, `error`, `fatal` |
| `start_time` | string | No | Start time (ISO 8601 format) |
| `end_time` | string | No | End time (ISO 8601 format) |
| `limit` | integer | No | Maximum number of log entries (default: 100, max: 1000) |
| `offset` | integer | No | Number of entries to skip (for pagination) |
| `search` | string | No | Search term to filter logs |
| `source` | string | No | Log source: `container`, `host`, `gpu_driver`, `application` |
| `format` | string | No | Response format: `json`, `text` (default: `json`) |
| `tail` | boolean | No | Get most recent logs first (default: true) |

### Log Types

| Type | Description | Sources |
| - | - | - |
| `system` | System-level logs (kernel, services, drivers) | syslog, systemd, kernel |
| `application` | Application and user process logs | stdout, stderr, app logs |
| `error` | Error and exception logs | error handlers, crash reports |
| `audit` | Security and access audit logs | auth, API access, file access |
| `docker` | Container runtime logs | Docker daemon, container logs |
| `gpu` | GPU driver and CUDA logs | nvidia-smi, CUDA runtime |

### Request Examples

```bash curl
# Get recent application logs
curl -X GET "https://api.tensorone.ai/v1/clusters/cluster_abc123/logs?log_type=application&limit=50" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Get error logs from last hour
curl -X GET "https://api.tensorone.ai/v1/clusters/cluster_abc123/logs?log_type=error&level=error&start_time=2024-01-15T15:00:00Z" \
  -H "Authorization: Bearer YOUR_API_KEY"

# Search for specific terms in logs
curl -X GET "https://api.tensorone.ai/v1/clusters/cluster_abc123/logs?search=CUDA&log_type=gpu" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

```python Python
import requests
import json
from datetime import datetime, timedelta

def get_cluster_logs(cluster_id, log_type=None, level=None, limit=100, search=None):
    """Get cluster logs with filtering"""
    
    params = {"limit": limit, "tail": True}
    
    if log_type:
        params["log_type"] = log_type
    if level:
        params["level"] = level
    if search:
        params["search"] = search
    
    response = requests.get(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/logs",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params=params
    )
    
    return response.json()

def get_error_logs(cluster_id, hours_back=24):
    """Get error logs from the last N hours"""
    
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=hours_back)
    
    params = {
        "log_type": "error",
        "level": "error",
        "start_time": start_time.isoformat() + "Z",
        "end_time": end_time.isoformat() + "Z",
        "limit": 500
    }
    
    response = requests.get(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/logs",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params=params
    )
    
    return response.json()

def analyze_training_logs(cluster_id, search_terms=None):
    """Analyze training logs for common patterns"""
    
    if not search_terms:
        search_terms = ["loss", "accuracy", "epoch", "error", "cuda", "memory"]
    
    analysis = {
        "cluster_id": cluster_id,
        "search_terms": search_terms,
        "findings": {},
        "error_summary": {},
        "performance_indicators": {}
    }
    
    for term in search_terms:
        logs = get_cluster_logs(cluster_id, log_type="application", search=term, limit=200)
        
        if logs["success"]:
            log_entries = logs["data"]["logs"]
            analysis["findings"][term] = {
                "count": len(log_entries),
                "recent_entries": log_entries[:5],  # Most recent 5
                "time_range": {
                    "first": log_entries[-1]["timestamp"] if log_entries else None,
                    "last": log_entries[0]["timestamp"] if log_entries else None
                }
            }
    
    # Get error summary
    error_logs = get_error_logs(cluster_id, hours_back=24)
    if error_logs["success"]:
        errors = error_logs["data"]["logs"]
        error_types = {}
        
        for error in errors:
            error_type = error.get("message", "").split(":")[0]
            error_types[error_type] = error_types.get(error_type, 0) + 1
        
        analysis["error_summary"] = {
            "total_errors": len(errors),
            "error_types": error_types,
            "recent_errors": errors[:3]
        }
    
    return analysis

def debug_cluster_issues(cluster_id):
    """Debug common cluster issues using logs"""
    
    debug_info = {
        "cluster_id": cluster_id,
        "timestamp": datetime.now().isoformat(),
        "checks": {}
    }
    
    # Check 1: GPU issues
    gpu_logs = get_cluster_logs(cluster_id, log_type="gpu", limit=100)
    gpu_issues = []
    
    if gpu_logs["success"]:
        for log in gpu_logs["data"]["logs"]:
            message = log.get("message", "").lower()
            if any(issue in message for issue in ["out of memory", "cuda error", "driver", "temperature"]):
                gpu_issues.append(log)
    
    debug_info["checks"]["gpu_health"] = {
        "status": "ok" if len(gpu_issues) == 0 else "issues_found",
        "issue_count": len(gpu_issues),
        "recent_issues": gpu_issues[:3]
    }
    
    # Check 2: System resources
    system_logs = get_cluster_logs(cluster_id, log_type="system", search="memory", limit=50)
    memory_issues = []
    
    if system_logs["success"]:
        for log in system_logs["data"]["logs"]:
            message = log.get("message", "").lower()
            if any(issue in message for issue in ["out of memory", "oom", "killed"]):
                memory_issues.append(log)
    
    debug_info["checks"]["memory_health"] = {
        "status": "ok" if len(memory_issues) == 0 else "issues_found", 
        "issue_count": len(memory_issues),
        "recent_issues": memory_issues[:3]
    }
    
    # Check 3: Application errors
    app_errors = get_error_logs(cluster_id, hours_back=2)
    critical_errors = []
    
    if app_errors["success"]:
        for error in app_errors["data"]["logs"]:
            if error.get("level") in ["error", "fatal"]:
                critical_errors.append(error)
    
    debug_info["checks"]["application_health"] = {
        "status": "ok" if len(critical_errors) == 0 else "issues_found",
        "error_count": len(critical_errors),
        "recent_errors": critical_errors[:3]
    }
    
    # Overall health assessment
    issues_found = sum(1 for check in debug_info["checks"].values() if check["status"] != "ok")
    debug_info["overall_health"] = "healthy" if issues_found == 0 else f"{issues_found}_issues_found"
    
    return debug_info

# Example usage
logs = get_cluster_logs("cluster_abc123", log_type="application", limit=50)
print(f"Retrieved {len(logs['data']['logs'])} log entries")

# Analyze training progress
training_analysis = analyze_training_logs("cluster_training_001")
print(f"Found {training_analysis['findings']['loss']['count']} loss-related log entries")

# Debug cluster issues
debug_results = debug_cluster_issues("cluster_abc123")
print(f"Cluster health: {debug_results['overall_health']}")
```

```javascript JavaScript
async function getClusterLogs(clusterId, options = {}) {
  const params = new URLSearchParams();
  
  // Set default options
  const defaults = {
    limit: 100,
    tail: true,
    format: 'json'
  };
  
  const config = { ...defaults, ...options };
  
  Object.entries(config).forEach(([key, value]) => {
    if (value !== undefined && value !== null) {
      params.append(key, value);
    }
  });
  
  const response = await fetch(
    `https://api.tensorone.ai/v1/clusters/${clusterId}/logs?${params}`,
    {
      headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
    }
  );
  
  return await response.json();
}

// Real-time log monitoring
class LogMonitor {
  constructor(clusterId, options = {}) {
    this.clusterId = clusterId;
    this.isMonitoring = false;
    this.eventSource = null;
    this.filters = options.filters || {};
    this.onLog = options.onLog || this.defaultLogHandler;
    this.onError = options.onError || this.defaultErrorHandler;
  }
  
  async startStreaming() {
    if (this.isMonitoring) {
      console.log('Log monitoring already active');
      return;
    }
    
    this.isMonitoring = true;
    console.log(`Starting log stream for cluster ${this.clusterId}`);
    
    // Use Server-Sent Events for real-time log streaming
    const params = new URLSearchParams(this.filters);
    const streamUrl = `https://api.tensorone.ai/v1/clusters/${this.clusterId}/logs/stream?${params}`;
    
    this.eventSource = new EventSource(streamUrl, {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    });
    
    this.eventSource.onmessage = (event) => {
      try {
        const logEntry = JSON.parse(event.data);
        this.onLog(logEntry);
      } catch (error) {
        console.error('Error parsing log entry:', error);
      }
    };
    
    this.eventSource.onerror = (error) => {
      console.error('Log stream error:', error);
      this.onError(error);
    };
  }
  
  stopStreaming() {
    if (this.eventSource) {
      this.eventSource.close();
      this.eventSource = null;
    }
    this.isMonitoring = false;
    console.log('Log streaming stopped');
  }
  
  defaultLogHandler(logEntry) {
    const timestamp = new Date(logEntry.timestamp).toLocaleTimeString();
    const level = logEntry.level.toUpperCase().padEnd(5);
    const source = logEntry.source.padEnd(12);
    
    console.log(`[${timestamp}] ${level} ${source} ${logEntry.message}`);
    
    // Highlight errors and warnings
    if (logEntry.level === 'error' || logEntry.level === 'fatal') {
      console.error(`🚨 CRITICAL: ${logEntry.message}`);
    } else if (logEntry.level === 'warn') {
      console.warn(`⚠️  WARNING: ${logEntry.message}`);
    }
  }
  
  defaultErrorHandler(error) {
    console.error('Log monitoring error:', error);
  }
}

// Training log analyzer
class TrainingLogAnalyzer {
  constructor(clusterId) {
    this.clusterId = clusterId;
    this.patterns = {
      loss: /loss[:\s=]+([0-9.]+)/i,
      accuracy: /acc(?:uracy)?[:\s=]+([0-9.]+)/i,
      epoch: /epoch[:\s=]+([0-9]+)/i,
      learning_rate: /lr[:\s=]+([0-9.e-]+)/i,
      cuda_error: /cuda.*error/i,
      oom_error: /out of memory|oom/i
    };
  }
  
  async analyzeTrainingProgress() {
    console.log('Analyzing training progress...');
    
    // Get recent application logs
    const logs = await getClusterLogs(this.clusterId, {
      log_type: 'application',
      limit: 500,
      start_time: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() // Last 2 hours
    });
    
    if (!logs.success) {
      throw new Error(`Failed to get logs: ${logs.error.message}`);
    }
    
    const analysis = {
      total_log_entries: logs.data.logs.length,
      training_metrics: {
        loss_values: [],
        accuracy_values: [],
        epochs: [],
        learning_rates: []
      },
      issues: {
        cuda_errors: [],
        memory_errors: [],
        other_errors: []
      },
      progress_summary: {}
    };
    
    // Analyze each log entry
    logs.data.logs.forEach(logEntry => {
      const message = logEntry.message;
      
      // Extract training metrics
      Object.entries(this.patterns).forEach(([metric, pattern]) => {
        const match = message.match(pattern);
        if (match) {
          const value = parseFloat(match[1]);
          if (!isNaN(value)) {
            switch (metric) {
              case 'loss':
                analysis.training_metrics.loss_values.push({
                  value,
                  timestamp: logEntry.timestamp
                });
                break;
              case 'accuracy':
                analysis.training_metrics.accuracy_values.push({
                  value,
                  timestamp: logEntry.timestamp
                });
                break;
              case 'epoch':
                analysis.training_metrics.epochs.push({
                  value: parseInt(value),
                  timestamp: logEntry.timestamp
                });
                break;
              case 'learning_rate':
                analysis.training_metrics.learning_rates.push({
                  value,
                  timestamp: logEntry.timestamp
                });
                break;
            }
          }
        }
      });
      
      // Identify issues
      if (this.patterns.cuda_error.test(message)) {
        analysis.issues.cuda_errors.push(logEntry);
      } else if (this.patterns.oom_error.test(message)) {
        analysis.issues.memory_errors.push(logEntry);
      } else if (logEntry.level === 'error') {
        analysis.issues.other_errors.push(logEntry);
      }
    });
    
    // Generate progress summary
    analysis.progress_summary = this.generateProgressSummary(analysis.training_metrics);
    
    return analysis;
  }
  
  generateProgressSummary(metrics) {
    const summary = {};
    
    // Loss trend
    if (metrics.loss_values.length > 1) {
      const firstLoss = metrics.loss_values[metrics.loss_values.length - 1].value;
      const lastLoss = metrics.loss_values[0].value;
      const lossImprovement = firstLoss - lastLoss;
      
      summary.loss_trend = {
        first_loss: firstLoss,
        latest_loss: lastLoss,
        improvement: lossImprovement,
        improvement_percent: (lossImprovement / firstLoss) * 100,
        trend: lossImprovement > 0 ? 'improving' : 'degrading'
      };
    }
    
    // Accuracy trend
    if (metrics.accuracy_values.length > 1) {
      const firstAcc = metrics.accuracy_values[metrics.accuracy_values.length - 1].value;
      const lastAcc = metrics.accuracy_values[0].value;
      const accImprovement = lastAcc - firstAcc;
      
      summary.accuracy_trend = {
        first_accuracy: firstAcc,
        latest_accuracy: lastAcc,
        improvement: accImprovement,
        improvement_percent: (accImprovement / firstAcc) * 100,
        trend: accImprovement > 0 ? 'improving' : 'degrading'
      };
    }
    
    // Current epoch
    if (metrics.epochs.length > 0) {
      summary.current_epoch = Math.max(...metrics.epochs.map(e => e.value));
      summary.total_epochs_logged = metrics.epochs.length;
    }
    
    // Learning rate info
    if (metrics.learning_rates.length > 0) {
      const rates = metrics.learning_rates.map(lr => lr.value);
      summary.learning_rate = {
        current: rates[0],
        min: Math.min(...rates),
        max: Math.max(...rates),
        is_decaying: rates.length > 1 && rates[0] < rates[rates.length - 1]
      };
    }
    
    return summary;
  }
  
  async generateReport() {
    const analysis = await this.analyzeTrainingProgress();
    
    console.log('\n=== Training Progress Report ===');
    console.log(`Cluster: ${this.clusterId}`);
    console.log(`Log entries analyzed: ${analysis.total_log_entries}`);
    
    // Progress summary
    if (analysis.progress_summary.loss_trend) {
      const loss = analysis.progress_summary.loss_trend;
      console.log(`\n📈 Loss Progress:`);
      console.log(`  Current: ${loss.latest_loss.toFixed(4)}`);
      console.log(`  Improvement: ${loss.improvement.toFixed(4)} (${loss.improvement_percent.toFixed(1)}%)`);
      console.log(`  Trend: ${loss.trend}`);
    }
    
    if (analysis.progress_summary.accuracy_trend) {
      const acc = analysis.progress_summary.accuracy_trend;
      console.log(`\n🎯 Accuracy Progress:`);
      console.log(`  Current: ${acc.latest_accuracy.toFixed(2)}%`);
      console.log(`  Improvement: +${acc.improvement.toFixed(2)}%`);
      console.log(`  Trend: ${acc.trend}`);
    }
    
    if (analysis.progress_summary.current_epoch) {
      console.log(`\n📚 Training Progress:`);
      console.log(`  Current Epoch: ${analysis.progress_summary.current_epoch}`);
    }
    
    // Issues summary
    const totalIssues = analysis.issues.cuda_errors.length + 
                       analysis.issues.memory_errors.length + 
                       analysis.issues.other_errors.length;
    
    if (totalIssues > 0) {
      console.log(`\n⚠️  Issues Found: ${totalIssues}`);
      if (analysis.issues.cuda_errors.length > 0) {
        console.log(`  CUDA Errors: ${analysis.issues.cuda_errors.length}`);
      }
      if (analysis.issues.memory_errors.length > 0) {
        console.log(`  Memory Errors: ${analysis.issues.memory_errors.length}`);
      }
      if (analysis.issues.other_errors.length > 0) {
        console.log(`  Other Errors: ${analysis.issues.other_errors.length}`);
      }
    } else {
      console.log('\n✅ No issues detected in recent logs');
    }
    
    return analysis;
  }
}

// Usage examples
async function monitorTrainingCluster(clusterId) {
  // Start real-time log monitoring
  const monitor = new LogMonitor(clusterId, {
    filters: {
      log_type: 'application',
      level: 'info'
    },
    onLog: (logEntry) => {
      // Custom log handler for training monitoring
      if (logEntry.message.includes('loss') || logEntry.message.includes('accuracy')) {
        console.log(`📊 ${logEntry.timestamp}: ${logEntry.message}`);
      }
    }
  });
  
  monitor.startStreaming();
  
  // Analyze training progress every 5 minutes
  const analyzer = new TrainingLogAnalyzer(clusterId);
  const analysisInterval = setInterval(async () => {
    try {
      await analyzer.generateReport();
    } catch (error) {
      console.error('Analysis error:', error);
    }
  }, 5 * 60 * 1000);
  
  // Cleanup function
  return () => {
    monitor.stopStreaming();
    clearInterval(analysisInterval);
  };
}

// Start monitoring
const stopMonitoring = await monitorTrainingCluster('cluster_training_001');

// Stop monitoring after 1 hour
setTimeout(stopMonitoring, 60 * 60 * 1000);
```

## Log Search

Advanced log search capabilities for complex queries and filtering.

```bash curl
# Search logs with complex query
curl -X POST "https://api.tensorone.ai/v1/clusters/cluster_abc123/logs/search" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "query": "level:error AND (CUDA OR memory)",
    "time_range": {
      "start": "2024-01-15T00:00:00Z",
      "end": "2024-01-15T23:59:59Z"
    },
    "limit": 100,
    "sort": "timestamp desc"
  }'
```

```python Python
def search_logs(cluster_id, query, time_range=None, limit=100):
    """Advanced log search with query syntax"""
    
    payload = {
        "query": query,
        "limit": limit,
        "sort": "timestamp desc"
    }
    
    if time_range:
        payload["time_range"] = time_range
    
    response = requests.post(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/logs/search",
        headers={
            "Authorization": f"Bearer {API_KEY}",
            "Content-Type": "application/json"
        },
        json=payload
    )
    
    return response.json()

def find_error_patterns(cluster_id, hours_back=24):
    """Find common error patterns in logs"""
    
    from datetime import datetime, timedelta
    
    end_time = datetime.now()
    start_time = end_time - timedelta(hours=hours_back)
    
    # Search for different types of errors
    error_queries = {
        "cuda_errors": "level:error AND CUDA",
        "memory_errors": "level:error AND (memory OR OOM OR \"out of memory\")",
        "python_exceptions": "level:error AND (Exception OR Error OR Traceback)",
        "system_errors": "source:system AND level:error",
        "docker_errors": "source:docker AND level:error"
    }
    
    error_analysis = {
        "time_range": {
            "start": start_time.isoformat(),
            "end": end_time.isoformat()
        },
        "error_categories": {}
    }
    
    for category, query in error_queries.items():
        results = search_logs(
            cluster_id,
            query,
            time_range={
                "start": start_time.isoformat() + "Z",
                "end": end_time.isoformat() + "Z"
            },
            limit=200
        )
        
        if results["success"]:
            logs = results["data"]["logs"]
            
            # Analyze error patterns
            error_messages = [log["message"] for log in logs]
            common_patterns = find_common_patterns(error_messages)
            
            error_analysis["error_categories"][category] = {
                "count": len(logs),
                "common_patterns": common_patterns,
                "recent_errors": logs[:5],
                "first_occurrence": logs[-1]["timestamp"] if logs else None,
                "last_occurrence": logs[0]["timestamp"] if logs else None
            }
    
    return error_analysis

def find_common_patterns(messages, min_frequency=2):
    """Find common patterns in error messages"""
    
    patterns = {}
    
    for message in messages:
        # Extract potential patterns (first 50 chars)
        pattern = message[:50]
        patterns[pattern] = patterns.get(pattern, 0) + 1
    
    # Return patterns that occur at least min_frequency times
    return {pattern: count for pattern, count in patterns.items() 
            if count >= min_frequency}

# Example usage
error_analysis = find_error_patterns("cluster_abc123", hours_back=12)

for category, data in error_analysis["error_categories"].items():
    if data["count"] > 0:
        print(f"\n{category}: {data['count']} errors")
        print(f"  Common patterns: {list(data['common_patterns'].keys())[:3]}")
        print(f"  Time span: {data['first_occurrence']} to {data['last_occurrence']}")
```

## Response Schema

```json Logs Response
{
  "success": true,
  "data": {
    "cluster_id": "cluster_abc123",
    "logs": [
      {
        "id": "log_entry_123",
        "timestamp": "2024-01-15T16:45:23.456Z",
        "level": "info",
        "source": "application",
        "log_type": "application",
        "message": "Training step 1500: loss=0.234, accuracy=94.2%",
        "process": {
          "pid": 1234,
          "name": "python",
          "command": "python train.py --model gpt2"
        },
        "metadata": {
          "host": "gpu-node-01",
          "container_id": "abc123def456",
          "thread_id": "MainThread",
          "file": "train.py",
          "line": 142
        },
        "tags": ["training", "metrics"]
      },
      {
        "id": "log_entry_124",
        "timestamp": "2024-01-15T16:45:20.123Z",
        "level": "error",
        "source": "gpu_driver",
        "log_type": "gpu",
        "message": "CUDA out of memory. Tried to allocate 2.00 GiB (GPU 0; 79.20 GiB total capacity)",
        "process": {
          "pid": 1234,
          "name": "python"
        },
        "metadata": {
          "host": "gpu-node-01",
          "gpu_id": 0,
          "cuda_version": "12.1",
          "driver_version": "530.30.02"
        },
        "tags": ["cuda", "memory", "error"],
        "stack_trace": [
          "File \"train.py\", line 89, in forward",
          "return self.model(inputs)",
          "RuntimeError: CUDA out of memory"
        ]
      }
    ],
    "pagination": {
      "total_count": 15420,
      "current_page": 1,
      "total_pages": 155,
      "has_next": true,
      "has_previous": false
    },
    "query_info": {
      "log_type": "application",
      "time_range": {
        "start": "2024-01-15T16:00:00Z",
        "end": "2024-01-15T17:00:00Z"
      },
      "filters_applied": ["log_type", "time_range"],
      "search_terms": null
    }
  },
  "meta": {
    "request_id": "req_logs_456",
    "query_time_ms": 127,
    "log_retention_days": 30
  }
}
```

```json Log Search Response
{
  "success": true,
  "data": {
    "query": "level:error AND (CUDA OR memory)",
    "total_matches": 47,
    "execution_time_ms": 89,
    "logs": [
      {
        "id": "log_entry_789",
        "timestamp": "2024-01-15T16:30:15.789Z",
        "level": "error",
        "source": "application",
        "message": "CUDA out of memory. Tried to allocate 1.50 GiB",
        "match_highlights": [
          "CUDA out of memory"
        ],
        "relevance_score": 0.95,
        "metadata": {
          "host": "gpu-node-01",
          "gpu_id": 0
        }
      }
    ],
    "facets": {
      "level": {
        "error": 47,
        "warn": 12
      },
      "source": {
        "application": 32,
        "gpu_driver": 15
      },
      "time_distribution": {
        "last_hour": 23,
        "last_6_hours": 47,
        "last_24_hours": 89
      }
    }
  }
}
```

## Download Logs

Export logs for offline analysis or archival purposes.

```bash curl
# Download logs as compressed archive
curl -X GET "https://api.tensorone.ai/v1/clusters/cluster_abc123/logs/download?format=json&compression=gzip&start_time=2024-01-15T00:00:00Z&end_time=2024-01-15T23:59:59Z" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  --output cluster_logs.json.gz
```

```python Python
def download_logs(cluster_id, start_time, end_time, format="json", compression="gzip"):
    """Download cluster logs for offline analysis"""
    
    params = {
        "format": format,
        "compression": compression,
        "start_time": start_time,
        "end_time": end_time
    }
    
    response = requests.get(
        f"https://api.tensorone.ai/v1/clusters/{cluster_id}/logs/download",
        headers={"Authorization": f"Bearer {API_KEY}"},
        params=params,
        stream=True
    )
    
    if response.status_code == 200:
        filename = f"cluster_{cluster_id}_logs_{start_time[:10]}.{format}"
        if compression:
            filename += f".{compression}"
        
        with open(filename, 'wb') as f:
            for chunk in response.iter_content(chunk_size=8192):
                f.write(chunk)
        
        return {"success": True, "filename": filename, "size_bytes": len(response.content)}
    
    return {"success": False, "error": response.text}

# Download last week's logs
from datetime import datetime, timedelta

end_time = datetime.now()
start_time = end_time - timedelta(days=7)

result = download_logs(
    "cluster_abc123",
    start_time.isoformat() + "Z",
    end_time.isoformat() + "Z",
    format="json",
    compression="gzip"
)

if result["success"]:
    print(f"Downloaded logs to {result['filename']} ({result['size_bytes']} bytes)")
```

## Use Cases

### Training Progress Monitoring

Monitor ML training progress through application logs.

```python
class TrainingProgressMonitor:
    def __init__(self, cluster_id):
        self.cluster_id = cluster_id
        self.progress_history = []
        self.alert_thresholds = {
            "loss_stagnation_steps": 100,
            "error_rate_threshold": 0.1,
            "memory_usage_threshold": 0.95
        }
    
    def monitor_training_session(self, duration_minutes=60, check_interval=30):
        """Monitor training session with periodic checks"""
        
        import time, threading
        
        self.monitoring = True
        end_time = time.time() + (duration_minutes * 60)
        
        def monitoring_loop():
            while self.monitoring and time.time() < end_time:
                try:
                    self.check_training_progress()
                    time.sleep(check_interval)
                except Exception as e:
                    print(f"Monitoring error: {e}")
                    time.sleep(check_interval)
        
        monitor_thread = threading.Thread(target=monitoring_loop)
        monitor_thread.daemon = True
        monitor_thread.start()
        
        return monitor_thread
    
    def check_training_progress(self):
        """Check current training progress from logs"""
        
        # Get recent application logs
        logs = get_cluster_logs(
            self.cluster_id,
            log_type="application",
            limit=50,
            search="loss"
        )
        
        if not logs["success"]:
            return
        
        current_progress = {
            "timestamp": time.time(),
            "loss_values": [],
            "accuracy_values": [],
            "error_count": 0,
            "memory_warnings": 0
        }
        
        for log_entry in logs["data"]["logs"]:
            message = log_entry["message"]
            
            # Extract loss values
            loss_match = re.search(r'loss[:\s=]+([0-9.]+)', message, re.IGNORECASE)
            if loss_match:
                current_progress["loss_values"].append(float(loss_match.group(1)))
            
            # Extract accuracy values
            acc_match = re.search(r'acc(?:uracy)?[:\s=]+([0-9.]+)', message, re.IGNORECASE)
            if acc_match:
                current_progress["accuracy_values"].append(float(acc_match.group(1)))
            
            # Count errors
            if log_entry["level"] in ["error", "fatal"]:
                current_progress["error_count"] += 1
            
            # Check for memory warnings
            if "memory" in message.lower() and "warning" in log_entry["level"]:
                current_progress["memory_warnings"] += 1
        
        self.progress_history.append(current_progress)
        
        # Check for alerts
        self.check_training_alerts(current_progress)
        
        # Print progress summary
        if current_progress["loss_values"]:
            avg_loss = sum(current_progress["loss_values"]) / len(current_progress["loss_values"])
            print(f"[{datetime.now().strftime('%H:%M:%S')}] Avg Loss: {avg_loss:.4f}, Errors: {current_progress['error_count']}")
    
    def check_training_alerts(self, current_progress):
        """Check for training issues and generate alerts"""
        
        alerts = []
        
        # Check loss stagnation
        if len(self.progress_history) >= 3:
            recent_losses = []
            for progress in self.progress_history[-3:]:
                if progress["loss_values"]:
                    recent_losses.extend(progress["loss_values"])
            
            if len(recent_losses) >= 5:
                loss_variance = statistics.variance(recent_losses)
                if loss_variance < 0.0001:  # Very low variance indicates stagnation
                    alerts.append("Loss appears to be stagnating")
        
        # Check error rate
        total_errors = sum(p["error_count"] for p in self.progress_history[-5:])
        if total_errors > self.alert_thresholds["error_rate_threshold"] * 50:  # Assuming 50 logs checked
            alerts.append(f"High error rate detected: {total_errors} errors in recent logs")
        
        # Check memory warnings
        if current_progress["memory_warnings"] > 0:
            alerts.append(f"Memory warnings detected: {current_progress['memory_warnings']}")
        
        if alerts:
            print(f"🚨 TRAINING ALERTS:")
            for alert in alerts:
                print(f"   • {alert}")
    
    def stop_monitoring(self):
        """Stop the monitoring process"""
        self.monitoring = False
    
    def get_training_summary(self):
        """Get comprehensive training summary"""
        
        if not self.progress_history:
            return {"error": "No progress data available"}
        
        all_losses = []
        all_accuracies = []
        total_errors = 0
        
        for progress in self.progress_history:
            all_losses.extend(progress["loss_values"])
            all_accuracies.extend(progress["accuracy_values"])
            total_errors += progress["error_count"]
        
        summary = {
            "monitoring_duration_minutes": (time.time() - self.progress_history[0]["timestamp"]) / 60,
            "total_progress_checks": len(self.progress_history),
            "loss_analysis": {},
            "accuracy_analysis": {},
            "error_analysis": {
                "total_errors": total_errors,
                "error_rate": total_errors / len(self.progress_history)
            }
        }
        
        if all_losses:
            summary["loss_analysis"] = {
                "first_loss": all_losses[-1],
                "last_loss": all_losses[0],
                "min_loss": min(all_losses),
                "avg_loss": sum(all_losses) / len(all_losses),
                "loss_improvement": all_losses[-1] - all_losses[0],
                "loss_trend": "improving" if all_losses[0] < all_losses[-1] else "degrading"
            }
        
        if all_accuracies:
            summary["accuracy_analysis"] = {
                "first_accuracy": all_accuracies[-1],
                "last_accuracy": all_accuracies[0],
                "max_accuracy": max(all_accuracies),
                "avg_accuracy": sum(all_accuracies) / len(all_accuracies),
                "accuracy_improvement": all_accuracies[0] - all_accuracies[-1]
            }
        
        return summary

# Usage
monitor = TrainingProgressMonitor("cluster_training_001")
monitor_thread = monitor.monitor_training_session(duration_minutes=120, check_interval=60)

# Get summary after training
summary = monitor.get_training_summary()
print("Training Summary:", json.dumps(summary, indent=2))
```

### Error Analysis and Debugging

Comprehensive error analysis for troubleshooting cluster issues.

```javascript
class ClusterDebugger {
  constructor(clusterId) {
    this.clusterId = clusterId;
  }
  
  async performComprehensiveDebug() {
    console.log(`🔍 Starting comprehensive debug for cluster ${this.clusterId}`);
    
    const debugReport = {
      cluster_id: this.clusterId,
      debug_timestamp: new Date().toISOString(),
      analysis: {
        system_health: await this.analyzeSystemHealth(),
        gpu_health: await this.analyzeGPUHealth(),
        application_health: await this.analyzeApplicationHealth(),
        network_health: await this.analyzeNetworkHealth(),
        resource_usage: await this.analyzeResourceUsage()
      },
      recommendations: []
    };
    
    // Generate recommendations based on findings
    debugReport.recommendations = this.generateRecommendations(debugReport.analysis);
    
    return debugReport;
  }
  
  async analyzeSystemHealth() {
    const systemLogs = await getClusterLogs(this.clusterId, {
      log_type: 'system',
      level: 'error',
      limit: 100,
      start_time: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString() // Last 2 hours
    });
    
    const analysis = {
      error_count: 0,
      critical_issues: [],
      kernel_issues: [],
      service_issues: [],
      health_score: 100
    };
    
    if (systemLogs.success) {
      analysis.error_count = systemLogs.data.logs.length;
      
      systemLogs.data.logs.forEach(log => {
        const message = log.message.toLowerCase();
        
        if (message.includes('kernel') || message.includes('panic')) {
          analysis.kernel_issues.push(log);
          analysis.health_score -= 20;
        } else if (message.includes('service') || message.includes('daemon')) {
          analysis.service_issues.push(log);
          analysis.health_score -= 10;
        } else if (message.includes('critical') || message.includes('fatal')) {
          analysis.critical_issues.push(log);
          analysis.health_score -= 15;
        }
      });
    }
    
    analysis.health_score = Math.max(0, analysis.health_score);
    analysis.status = analysis.health_score > 80 ? 'healthy' : 
                     analysis.health_score > 50 ? 'degraded' : 'critical';
    
    return analysis;
  }
  
  async analyzeGPUHealth() {
    const gpuLogs = await getClusterLogs(this.clusterId, {
      log_type: 'gpu',
      limit: 200,
      start_time: new Date(Date.now() - 60 * 60 * 1000).toISOString() // Last hour
    });
    
    const analysis = {
      cuda_errors: [],
      memory_errors: [],
      temperature_warnings: [],
      driver_issues: [],
      health_score: 100
    };
    
    if (gpuLogs.success) {
      gpuLogs.data.logs.forEach(log => {
        const message = log.message.toLowerCase();
        
        if (message.includes('cuda') && message.includes('error')) {
          analysis.cuda_errors.push(log);
          analysis.health_score -= 15;
        } else if (message.includes('out of memory') || message.includes('oom')) {
          analysis.memory_errors.push(log);
          analysis.health_score -= 20;
        } else if (message.includes('temperature') && message.includes('high')) {
          analysis.temperature_warnings.push(log);
          analysis.health_score -= 10;
        } else if (message.includes('driver')) {
          analysis.driver_issues.push(log);
          analysis.health_score -= 10;
        }
      });
    }
    
    analysis.health_score = Math.max(0, analysis.health_score);
    analysis.status = analysis.health_score > 80 ? 'healthy' : 
                     analysis.health_score > 50 ? 'degraded' : 'critical';
    
    return analysis;
  }
  
  async analyzeApplicationHealth() {
    // Search for application errors and exceptions
    const searchResults = await this.searchLogs(
      'level:error AND source:application',
      {
        start: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
        end: new Date().toISOString()
      }
    );
    
    const analysis = {
      total_errors: 0,
      exception_types: {},
      frequent_errors: {},
      performance_issues: [],
      health_score: 100
    };
    
    if (searchResults.success) {
      analysis.total_errors = searchResults.data.total_matches;
      
      searchResults.data.logs.forEach(log => {
        const message = log.message;
        
        // Categorize exceptions
        const exceptionMatch = message.match(/(\w+Error|\w+Exception)/);
        if (exceptionMatch) {
          const exceptionType = exceptionMatch[1];
          analysis.exception_types[exceptionType] = 
            (analysis.exception_types[exceptionType] || 0) + 1;
        }
        
        // Look for performance issues
        if (message.includes('timeout') || message.includes('slow') || 
            message.includes('performance')) {
          analysis.performance_issues.push(log);
        }
        
        // Count frequent error patterns
        const errorPattern = message.substring(0, 50);
        analysis.frequent_errors[errorPattern] = 
          (analysis.frequent_errors[errorPattern] || 0) + 1;
      });
      
      // Adjust health score based on error frequency
      if (analysis.total_errors > 50) {
        analysis.health_score -= 30;
      } else if (analysis.total_errors > 20) {
        analysis.health_score -= 20;
      } else if (analysis.total_errors > 10) {
        analysis.health_score -= 10;
      }
    }
    
    analysis.health_score = Math.max(0, analysis.health_score);
    analysis.status = analysis.health_score > 80 ? 'healthy' : 
                     analysis.health_score > 50 ? 'degraded' : 'critical';
    
    return analysis;
  }
  
  async analyzeNetworkHealth() {
    const networkLogs = await getClusterLogs(this.clusterId, {
      search: 'network',
      level: 'error',
      limit: 50,
      start_time: new Date(Date.now() - 60 * 60 * 1000).toISOString()
    });
    
    const analysis = {
      connection_errors: [],
      timeout_errors: [],
      dns_issues: [],
      health_score: 100
    };
    
    if (networkLogs.success) {
      networkLogs.data.logs.forEach(log => {
        const message = log.message.toLowerCase();
        
        if (message.includes('connection') && message.includes('error')) {
          analysis.connection_errors.push(log);
          analysis.health_score -= 10;
        } else if (message.includes('timeout')) {
          analysis.timeout_errors.push(log);
          analysis.health_score -= 5;
        } else if (message.includes('dns') || message.includes('resolve')) {
          analysis.dns_issues.push(log);
          analysis.health_score -= 5;
        }
      });
    }
    
    analysis.health_score = Math.max(0, analysis.health_score);
    analysis.status = analysis.health_score > 90 ? 'healthy' : 
                     analysis.health_score > 70 ? 'degraded' : 'critical';
    
    return analysis;
  }
  
  async analyzeResourceUsage() {
    // Look for resource-related log messages
    const resourceLogs = await getClusterLogs(this.clusterId, {
      search: 'memory OR disk OR cpu',
      limit: 100,
      start_time: new Date(Date.now() - 30 * 60 * 1000).toISOString() // Last 30 minutes
    });
    
    const analysis = {
      memory_warnings: [],
      disk_warnings: [],
      cpu_warnings: [],
      resource_exhaustion: []
    };
    
    if (resourceLogs.success) {
      resourceLogs.data.logs.forEach(log => {
        const message = log.message.toLowerCase();
        
        if (message.includes('memory') && (message.includes('low') || message.includes('warning'))) {
          analysis.memory_warnings.push(log);
        } else if (message.includes('disk') && (message.includes('full') || message.includes('space'))) {
          analysis.disk_warnings.push(log);
        } else if (message.includes('cpu') && message.includes('high')) {
          analysis.cpu_warnings.push(log);
        } else if (message.includes('exhausted') || message.includes('limit')) {
          analysis.resource_exhaustion.push(log);
        }
      });
    }
    
    return analysis;
  }
  
  generateRecommendations(analysis) {
    const recommendations = [];
    
    // System health recommendations
    if (analysis.system_health.status === 'critical') {
      recommendations.push({
        priority: 'high',
        category: 'system',
        title: 'Critical System Issues Detected',
        description: `${analysis.system_health.critical_issues.length} critical system issues found`,
        action: 'Restart cluster or contact support immediately'
      });
    }
    
    // GPU health recommendations
    if (analysis.gpu_health.cuda_errors.length > 0) {
      recommendations.push({
        priority: 'high',
        category: 'gpu',
        title: 'CUDA Errors Detected',
        description: `${analysis.gpu_health.cuda_errors.length} CUDA errors found`,
        action: 'Check CUDA version compatibility and driver installation'
      });
    }
    
    if (analysis.gpu_health.memory_errors.length > 0) {
      recommendations.push({
        priority: 'medium',
        category: 'gpu',
        title: 'GPU Memory Issues',
        description: `${analysis.gpu_health.memory_errors.length} memory errors found`,
        action: 'Reduce batch size or model complexity, or upgrade to higher memory GPU'
      });
    }
    
    // Application health recommendations
    if (analysis.application_health.total_errors > 20) {
      recommendations.push({
        priority: 'medium',
        category: 'application',
        title: 'High Application Error Rate',
        description: `${analysis.application_health.total_errors} application errors in last 2 hours`,
        action: 'Review application logs and fix recurring issues'
      });
    }
    
    return recommendations;
  }
  
  async searchLogs(query, timeRange) {
    const response = await fetch(
      `https://api.tensorone.ai/v1/clusters/${this.clusterId}/logs/search`,
      {
        method: 'POST',
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          query: query,
          time_range: timeRange,
          limit: 100
        })
      }
    );
    
    return await response.json();
  }
  
  async generateDebugReport() {
    const report = await this.performComprehensiveDebug();
    
    console.log('\n=== Cluster Debug Report ===');
    console.log(`Cluster: ${report.cluster_id}`);
    console.log(`Analysis Time: ${report.debug_timestamp}`);
    
    // Overall health summary
    const healthScores = [
      report.analysis.system_health.health_score,
      report.analysis.gpu_health.health_score,
      report.analysis.application_health.health_score,
      report.analysis.network_health.health_score
    ];
    
    const overallHealth = healthScores.reduce((sum, score) => sum + score, 0) / healthScores.length;
    
    console.log(`\n📊 Overall Health Score: ${overallHealth.toFixed(1)}/100`);
    
    // Component health
    console.log('\n🔧 Component Health:');
    console.log(`  System: ${report.analysis.system_health.status} (${report.analysis.system_health.health_score}/100)`);
    console.log(`  GPU: ${report.analysis.gpu_health.status} (${report.analysis.gpu_health.health_score}/100)`);
    console.log(`  Application: ${report.analysis.application_health.status} (${report.analysis.application_health.health_score}/100)`);
    console.log(`  Network: ${report.analysis.network_health.status} (${report.analysis.network_health.health_score}/100)`);
    
    // Recommendations
    if (report.recommendations.length > 0) {
      console.log('\n💡 Recommendations:');
      report.recommendations.forEach((rec, index) => {
        console.log(`  ${index + 1}. [${rec.priority.toUpperCase()}] ${rec.title}`);
        console.log(`     ${rec.description}`);
        console.log(`     Action: ${rec.action}`);
      });
    } else {
      console.log('\n✅ No critical issues found');
    }
    
    return report;
  }
}

// Usage
const debugger = new ClusterDebugger('cluster_abc123');
await debugger.generateDebugReport();
```

## Error Handling

```json Log Not Found
{
  "success": false,
  "error": {
    "code": "LOGS_NOT_AVAILABLE",
    "message": "Logs are not available for the specified time range",
    "details": {
      "requested_start": "2024-01-01T00:00:00Z",
      "requested_end": "2024-01-02T00:00:00Z",
      "available_start": "2024-01-14T00:00:00Z",
      "log_retention_days": 30
    }
  }
}
```

```json Search Query Error
{
  "success": false,
  "error": {
    "code": "INVALID_SEARCH_QUERY",
    "message": "Invalid search query syntax",
    "details": {
      "query": "level:error AND (invalid syntax",
      "error_position": 20,
      "suggestion": "Check parentheses matching and field names"
    }
  }
}
```

## Best Practices

1. **Log Level Management**: Use appropriate log levels to reduce noise
2. **Time Range Optimization**: Use specific time ranges for better performance
3. **Search Efficiency**: Use structured queries for complex log analysis
4. **Regular Monitoring**: Set up automated log monitoring for critical issues
5. **Log Retention**: Understand log retention policies for your use case
6. **Export Strategy**: Regular export of important logs for compliance and analysis


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.