add logging

This commit is contained in:
Julian Freeman
2025-12-02 10:44:14 -04:00
parent 068bc1c79e
commit d2cafc328f
6 changed files with 312 additions and 30 deletions

58
spec/logging_feature.md Normal file
View File

@@ -0,0 +1,58 @@
# Feature Request: Real-time Logging & UI Refinement
## 1. Context & Objective
Users currently experience download failures without sufficient context or error details, making troubleshooting difficult.
The objective is to introduce a dedicated **Logs System** within the application to capture, display, and persist detailed execution logs from the `yt-dlp` process.
Additionally, the application's sidebar layout requires balancing for better UX.
## 2. Requirements
### 2.1. Backend (Rust) - Logging Infrastructure
* **Stream Capture**: The `downloader` module must capture both `STDOUT` (progress) and `STDERR` (errors/warnings) from the `yt-dlp` process.
* **Event Emission**: Emit a new Tauri event `download-log` to the frontend in real-time.
* Payload: `{ id: String, message: String, level: 'info' | 'error' | 'debug' }`
* **Persistence (Optional but Recommended)**: Ideally, write logs to a local file (e.g., `logs/{date}.log` or `logs/{task_id}.log`) for post-mortem analysis. *For this iteration, real-time event emission is priority.*
### 2.2. Frontend - Logs View
* **New Route**: `/logs`
* **UI Layout**:
* A dedicated **Logs Tab** in the main navigation.
* A console-like view displaying a stream of log messages.
* Filters: Filter by "Task ID" or "Level" (Error/Info).
* **Real-time**: The view must update automatically as new log events arrive.
* **Detail**: Failed downloads must show the specific error message returned by `yt-dlp` (e.g., "Sign in required", "Video unavailable").
### 2.3. UI/UX - Sidebar Refactoring
* **Reordering**:
* **Top Section**: Home (Downloader), History.
* **Bottom Section**: Logs, Settings.
* **Removal**: Remove the "Version Number" text from the bottom of the sidebar (it can be moved to the Settings page if needed, or just removed as requested).
## 3. Implementation Steps
### Step 1: Rust Backend Updates
* Modify `src-tauri/src/downloader.rs`:
* Update `download_video` to spawn the process with `Stdio::piped()` for both stdout and stderr.
* Use `tokio::select!` or separate tasks to read both streams concurrently.
* Emit `download-log` events for every line read.
* Ensure the final error message (if exit code != 0) is explicitly captured and returned/logged.
### Step 2: Frontend Store & Logic
* Create `src/stores/logs.ts`:
* State: `logs: LogEntry[]`.
* Action: `addLog(entry)`.
* Listener: Listen for `download-log` events globally.
### Step 3: Frontend UI
* Create `src/views/Logs.vue`:
* Display logs in a scrollable container.
* Style error logs in red, info in gray/white.
* Update `src/App.vue`:
* Add the `FileText` (or similar) icon for Logs.
* Refactor the sidebar Flexbox layout to push Logs and Settings to the bottom.
* Remove the version footer.
* Update `src/router/index.ts` to include the new route.
## 4. Success Criteria
* When a download fails, the user can go to the "Logs" tab and see the exact error output from `yt-dlp`.
* The sidebar looks balanced with navigation items split between top and bottom.

View File

@@ -46,6 +46,13 @@ pub struct ProgressEvent {
pub status: String, // "downloading", "processing", "finished", "error" pub status: String, // "downloading", "processing", "finished", "error"
} }
#[derive(Serialize, Clone, Debug)]
pub struct LogEvent {
pub id: String,
pub message: String,
pub level: String, // "info", "error"
}
pub async fn fetch_metadata(app: &AppHandle, url: &str, parse_mix_playlist: bool) -> Result<MetadataResult> { pub async fn fetch_metadata(app: &AppHandle, url: &str, parse_mix_playlist: bool) -> Result<MetadataResult> {
let ytdlp_path = ytdlp::get_ytdlp_path(app)?; let ytdlp_path = ytdlp::get_ytdlp_path(app)?;
@@ -148,31 +155,60 @@ pub async fn download_video(
let mut child = Command::new(ytdlp_path) let mut child = Command::new(ytdlp_path)
.args(&args) .args(&args)
.stdout(Stdio::piped()) .stdout(Stdio::piped())
.stderr(Stdio::piped()) .stderr(Stdio::piped()) // Capture stderr for logs
.spawn()?; .spawn()?;
let stdout = child.stdout.take().ok_or(anyhow!("Failed to open stdout"))?; let stdout = child.stdout.take().ok_or(anyhow!("Failed to open stdout"))?;
let mut reader = BufReader::new(stdout); let stderr = child.stderr.take().ok_or(anyhow!("Failed to open stderr"))?;
let mut line = String::new();
let mut stdout_reader = BufReader::new(stdout);
// Regex for progress: [download] 42.5% of 10.00MiB at 2.00MiB/s ETA 00:05 let mut stderr_reader = BufReader::new(stderr);
let re = Regex::new(r"\[download\]\s+(\d+\.?\d*)%").unwrap(); let re = Regex::new(r"\[download\]\s+(\d+\.?\d*)%").unwrap();
while reader.read_line(&mut line).await? > 0 { // Loop to read both streams
if let Some(caps) = re.captures(&line) { loop {
if let Some(pct_match) = caps.get(1) { let mut out_line = String::new();
if let Ok(pct) = pct_match.as_str().parse::<f64>() { let mut err_line = String::new();
// Emit event
app.emit("download-progress", ProgressEvent { tokio::select! {
id: id.clone(), res = stdout_reader.read_line(&mut out_line) => {
progress: pct, if res.unwrap_or(0) == 0 {
speed: "TODO".to_string(), // Speed parsing is a bit more complex, skipping for MVP or adding regex for it break; // EOF
status: "downloading".to_string(), }
}).ok();
// Log info
app.emit("download-log", LogEvent {
id: id.clone(),
message: out_line.trim().to_string(),
level: "info".to_string(),
}).ok();
// Parse progress
if let Some(caps) = re.captures(&out_line) {
if let Some(pct_match) = caps.get(1) {
if let Ok(pct) = pct_match.as_str().parse::<f64>() {
app.emit("download-progress", ProgressEvent {
id: id.clone(),
progress: pct,
speed: "TODO".to_string(),
status: "downloading".to_string(),
}).ok();
}
}
} }
} }
res = stderr_reader.read_line(&mut err_line) => {
if res.unwrap_or(0) > 0 {
// Log error
app.emit("download-log", LogEvent {
id: id.clone(),
message: err_line.trim().to_string(),
level: "error".to_string(),
}).ok();
}
}
} }
line.clear();
} }
let status = child.wait().await?; let status = child.wait().await?;
@@ -194,4 +230,4 @@ pub async fn download_video(
}).ok(); }).ok();
Err(anyhow!("Download process failed")) Err(anyhow!("Download process failed"))
} }
} }

View File

@@ -2,18 +2,21 @@
<script setup lang="ts"> <script setup lang="ts">
import { onMounted } from 'vue' import { onMounted } from 'vue'
import { RouterView, RouterLink, useRoute } from 'vue-router' import { RouterView, RouterLink, useRoute } from 'vue-router'
import { Home, History, Settings as SettingsIcon, Download } from 'lucide-vue-next' import { Home, History, Settings as SettingsIcon, Download, FileText } from 'lucide-vue-next'
import { useSettingsStore } from './stores/settings' import { useSettingsStore } from './stores/settings'
import { useQueueStore } from './stores/queue' import { useQueueStore } from './stores/queue'
import { useLogsStore } from './stores/logs'
const settingsStore = useSettingsStore() const settingsStore = useSettingsStore()
const queueStore = useQueueStore() const queueStore = useQueueStore()
const logsStore = useLogsStore()
const route = useRoute() const route = useRoute()
onMounted(async () => { onMounted(async () => {
await settingsStore.loadSettings() await settingsStore.loadSettings()
await settingsStore.initYtdlp() await settingsStore.initYtdlp()
await queueStore.initListener() await queueStore.initListener()
await logsStore.initListener()
}) })
</script> </script>
@@ -28,7 +31,8 @@ onMounted(async () => {
<span class="font-bold text-lg hidden lg:block">StreamCapture</span> <span class="font-bold text-lg hidden lg:block">StreamCapture</span>
</div> </div>
<nav class="flex-1 px-4 space-y-2 mt-4"> <nav class="flex-1 px-4 space-y-2 mt-4 flex flex-col">
<!-- Top Section -->
<RouterLink to="/" <RouterLink to="/"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors" class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
:class="route.path === '/' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'" :class="route.path === '/' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
@@ -45,21 +49,25 @@ onMounted(async () => {
<span class="hidden lg:block font-medium">History</span> <span class="hidden lg:block font-medium">History</span>
</RouterLink> </RouterLink>
<RouterLink to="/settings" <div class="flex-1"></div>
<!-- Bottom Section -->
<RouterLink to="/logs"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors" class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors"
:class="route.path === '/logs' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
>
<FileText class="w-5 h-5 shrink-0" />
<span class="hidden lg:block font-medium">Logs</span>
</RouterLink>
<RouterLink to="/settings"
class="flex items-center gap-3 px-4 py-3 rounded-xl transition-colors mb-4"
:class="route.path === '/settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'" :class="route.path === '/settings' ? 'bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400' : 'hover:bg-gray-100 dark:hover:bg-zinc-800'"
> >
<SettingsIcon class="w-5 h-5 shrink-0" /> <SettingsIcon class="w-5 h-5 shrink-0" />
<span class="hidden lg:block font-medium">Settings</span> <span class="hidden lg:block font-medium">Settings</span>
</RouterLink> </RouterLink>
</nav> </nav>
<div class="p-4 border-t border-gray-200 dark:border-zinc-800">
<div class="text-xs text-gray-400 text-center lg:text-left truncate">
<p v-if="settingsStore.isInitializing">Initializing...</p>
<p v-else>v{{ settingsStore.ytdlpVersion }}</p>
</div>
</div>
</aside> </aside>
<!-- Main Content --> <!-- Main Content -->
@@ -67,4 +75,4 @@ onMounted(async () => {
<RouterView /> <RouterView />
</main> </main>
</div> </div>
</template> </template>

View File

@@ -2,6 +2,7 @@ import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue' import Home from '../views/Home.vue'
import History from '../views/History.vue' import History from '../views/History.vue'
import Settings from '../views/Settings.vue' import Settings from '../views/Settings.vue'
import Logs from '../views/Logs.vue'
const router = createRouter({ const router = createRouter({
history: createWebHistory(), history: createWebHistory(),
@@ -16,6 +17,11 @@ const router = createRouter({
name: 'history', name: 'history',
component: History component: History
}, },
{
path: '/logs',
name: 'logs',
component: Logs
},
{ {
path: '/settings', path: '/settings',
name: 'settings', name: 'settings',
@@ -24,4 +30,4 @@ const router = createRouter({
] ]
}) })
export default router export default router

54
src/stores/logs.ts Normal file
View File

@@ -0,0 +1,54 @@
// filepath: src/stores/logs.ts
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { listen } from '@tauri-apps/api/event'
export interface LogEntry {
id: string
taskId: string
message: string
level: 'info' | 'error'
timestamp: number
}
interface LogEvent {
id: string
message: string
level: string
}
export const useLogsStore = defineStore('logs', () => {
const logs = ref<LogEntry[]>([])
const isListening = ref(false)
function addLog(taskId: string, message: string, level: 'info' | 'error') {
logs.value.push({
id: crypto.randomUUID(),
taskId,
message,
level,
timestamp: Date.now()
})
// Optional: Limit log size to avoid memory issues
if (logs.value.length > 5000) {
logs.value = logs.value.slice(-5000)
}
}
async function initListener() {
if (isListening.value) return
isListening.value = true
await listen<LogEvent>('download-log', (event) => {
const { id, message, level } = event.payload
addLog(id, message, level as 'info' | 'error')
})
}
function clearLogs() {
logs.value = []
}
return { logs, addLog, initListener, clearLogs }
})

120
src/views/Logs.vue Normal file
View File

@@ -0,0 +1,120 @@
// filepath: src/views/Logs.vue
<script setup lang="ts">
import { ref, computed, nextTick, watch } from 'vue'
import { useLogsStore } from '../stores/logs'
import { Trash2, Search } from 'lucide-vue-next'
const logsStore = useLogsStore()
const logsContainer = ref<HTMLElement | null>(null)
const autoScroll = ref(true)
const filterLevel = ref<'all' | 'info' | 'error'>('all')
const searchQuery = ref('')
const filteredLogs = computed(() => {
return logsStore.logs.filter(log => {
if (filterLevel.value !== 'all' && log.level !== filterLevel.value) return false
if (searchQuery.value && !log.message.toLowerCase().includes(searchQuery.value.toLowerCase()) && !log.taskId.includes(searchQuery.value)) return false
return true
})
})
// Auto-scroll
watch(() => logsStore.logs.length, () => {
if (autoScroll.value) {
nextTick(() => {
if (logsContainer.value) {
logsContainer.value.scrollTop = logsContainer.value.scrollHeight
}
})
}
})
function formatTime(ts: number) {
return new Date(ts).toLocaleTimeString()
}
</script>
<template>
<div class="flex flex-col h-full">
<!-- Header -->
<div class="px-8 py-6 border-b border-gray-200 dark:border-zinc-800 flex justify-between items-center bg-white dark:bg-zinc-900">
<div>
<h1 class="text-2xl font-bold text-zinc-900 dark:text-white">Execution Logs</h1>
<p class="text-sm text-gray-500 dark:text-gray-400 mt-1">Real-time output from download processes.</p>
</div>
<div class="flex items-center gap-3">
<!-- Search -->
<div class="relative">
<Search class="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" />
<input
v-model="searchQuery"
type="text"
placeholder="Search logs..."
class="pl-9 pr-4 py-2 bg-gray-100 dark:bg-zinc-800 rounded-lg text-sm outline-none focus:ring-2 focus:ring-blue-500 border-none w-48"
/>
</div>
<!-- Level Filter -->
<div class="flex bg-gray-100 dark:bg-zinc-800 rounded-lg p-1">
<button
@click="filterLevel = 'all'"
class="px-3 py-1.5 rounded-md text-xs font-medium transition-colors"
:class="filterLevel === 'all' ? 'bg-white dark:bg-zinc-700 shadow-sm text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>All</button>
<button
@click="filterLevel = 'info'"
class="px-3 py-1.5 rounded-md text-xs font-medium transition-colors"
:class="filterLevel === 'info' ? 'bg-white dark:bg-zinc-700 shadow-sm text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>Info</button>
<button
@click="filterLevel = 'error'"
class="px-3 py-1.5 rounded-md text-xs font-medium transition-colors"
:class="filterLevel === 'error' ? 'bg-white dark:bg-zinc-700 shadow-sm text-zinc-900 dark:text-white' : 'text-gray-500 hover:text-zinc-900 dark:hover:text-white'"
>Error</button>
</div>
<button
@click="logsStore.clearLogs"
class="p-2 text-gray-500 hover:bg-red-50 hover:text-red-600 dark:hover:bg-red-900/20 rounded-lg transition-colors"
title="Clear Logs"
>
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
<!-- Logs Console -->
<div class="flex-1 overflow-hidden relative bg-gray-900 text-gray-300 font-mono text-xs md:text-sm">
<div
ref="logsContainer"
class="absolute inset-0 overflow-auto p-4 space-y-1 custom-scrollbar"
@scroll="(e) => {
const target = e.target as HTMLElement;
autoScroll = target.scrollTop + target.clientHeight >= target.scrollHeight - 10;
}"
>
<div v-if="filteredLogs.length === 0" class="h-full flex items-center justify-center text-gray-600">
No logs to display
</div>
<div v-for="log in filteredLogs" :key="log.id" class="flex gap-3 hover:bg-gray-800/50 px-2 py-0.5 rounded">
<span class="text-gray-600 shrink-0 select-none w-20">{{ formatTime(log.timestamp) }}</span>
<span
class="break-all whitespace-pre-wrap"
:class="log.level === 'error' ? 'text-red-400' : 'text-gray-300'"
>{{ log.message }}</span>
</div>
</div>
<!-- Auto-scroll indicator -->
<div v-if="!autoScroll" class="absolute bottom-4 right-4">
<button
@click="() => { if(logsContainer) logsContainer.scrollTop = logsContainer.scrollHeight }"
class="bg-blue-600 hover:bg-blue-700 text-white text-xs px-3 py-1.5 rounded-full shadow-lg transition-colors"
>
Resume Auto-scroll
</button>
</div>
</div>
</div>
</template>