Log
Display logs line by line, using different colors for log levels and automatically scrolling to new entries. Suitable for build output, task execution records, and live application logs.
Import
import { HuiLog } from '@nscode/handy-ui'
Basic usage
Pass a log array through logs. Each entry must have at least content. height sets the panel height, defaults to 300, and treats numbers as pixels.
<script setup lang="ts">
import { HuiLog } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = [
{ content: 'Application started, listening on port 8080' },
{ content: 'Database connected' },
{ content: 'Loading configuration file application.yml' }
]
</script>
<template>
<HuiLog :logs="logs" :height="200" />
</template>
Log levels
level supports info, warn, error, and debug, defaulting to info. Warning and error rows have a subtle background; debug rows use lighter text.
<script setup lang="ts">
import { HuiLog } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = [
{ content: 'info: Order SO20260001 created', level: 'info' },
{ content: 'warn: Only 3 units of product A-102 remain', level: 'warn' },
{ content: 'error: Payment API timed out (5000ms)', level: 'error' },
{ content: 'debug: Request parameters {"page":1,"size":20}', level: 'debug' },
{ content: 'Defaults to info when level is omitted' }
]
</script>
<template>
<HuiLog :logs="logs" :height="200" />
</template>
Timestamps
Entries with timestamp display it before their content. The component does not format timestamps: strings are displayed as provided. Entries without a timestamp show no time.
<script setup lang="ts">
import { HuiLog } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = [
{ content: 'Service started', timestamp: '2026-11-17 10:00:00' },
{ content: 'Memory usage: 85%', level: 'warn', timestamp: '2026-11-17 10:00:05' },
{
content: 'Scheduled task “Clean temporary files” failed',
level: 'error',
timestamp: '10:00:12'
},
{ content: 'This entry has no timestamp' }
]
</script>
<template>
<HuiLog :logs="logs" :height="160" />
</template>
Height
Numeric height values are pixels. Strings are used as provided, such as '10em' or '50vh'. For '100%', the parent must have a height. Overflowing logs scroll inside the panel.
<script setup lang="ts">
import { HuiLog, HuiSpace } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = Array.from({ length: 12 }, (_, i) => ({
content: `Synchronizing order batch ${i + 1}`
}))
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiLog :logs="logs" :height="120" />
<div style="height: 180px">
<HuiLog :logs="logs" height="100%" />
</div>
</HuiSpace>
</template>
The first example uses :height="120"; the second uses height="100%" inside a 180px-high parent.
Loading
When loading is true, an indicator appears in the upper-right corner and the log area is dimmed. Click the button to simulate fetching logs and append them after 1.5 seconds:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiLog, HuiSpace } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs = ref<LogItem[]>([
{ content: 'Starting build for web-admin', timestamp: '10:00:00' },
{ content: 'Dependencies installed', timestamp: '10:00:18' }
])
const loading = ref(false)
const steps = [
'Compiling TypeScript',
'Bundling static assets',
'Uploading to object storage',
'Build complete'
]
const fetchMore = () => {
loading.value = true
window.setTimeout(() => {
const step = steps[(logs.value.length - 2) % steps.length]
logs.value.push({ content: step, timestamp: new Date().toTimeString().slice(0, 8) })
loading.value = false
}, 1500)
}
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton :loading="loading" icon="refresh" @click="fetchMore">Fetch new logs</HuiButton>
</HuiSpace>
<HuiLog :logs="logs" :loading="loading" :height="160" />
</HuiSpace>
</template>
Automatic scrolling
autoScroll is enabled by default. Replacing the log array or pushing entries scrolls to the bottom. Scrolling up to read older logs pauses automatic scrolling, so new entries do not pull you back down. It resumes when you return to the bottom or call scrollToBottom(). With :auto-scroll="false", new entries leave the scroll position unchanged.
Click Start output to simulate a live log (one entry every 0.3 seconds, stopping automatically at 200 entries). Toggle automatic scrolling to compare:
<script setup lang="ts">
import { onUnmounted, ref, watch } from 'vue'
import { HuiButton, HuiLog, HuiMessageBox, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs = ref<LogItem[]>([])
const autoScroll = ref(true)
const running = ref(false)
// Log deletion confirmation: streaming panel. Read-only protection applies to clearing, not output timing.
const readonly = ref(false)
const pending = ref(false)
let alive = true
let revision = 0
watch([logs, readonly], () => revision++, { deep: true, flush: 'sync' })
let timer: number | undefined
let count = 0
const stop = () => {
window.clearInterval(timer)
timer = undefined
running.value = false
}
const start = () => {
if (timer !== undefined) return
running.value = true
timer = window.setInterval(() => {
count++
const level = count % 13 === 0 ? 'error' : count % 5 === 0 ? 'warn' : 'info'
const content =
level === 'error'
? 'Inventory API timed out; preparing to retry'
: level === 'warn'
? `Order SO${20260000 + count} has an incomplete shipping address`
: `Synchronizing order SO${20260000 + count}`
logs.value.push({ content, level, timestamp: new Date().toTimeString().slice(0, 8) })
if (logs.value.length >= 200) stop()
}, 300)
}
const clearStreamingLogs = async () => {
if (readonly.value || pending.value || !logs.value.length) return
const target = logs.value
const request = revision
const snapshot = target.slice()
pending.value = true
try {
await HuiMessageBox.confirm({
title: 'Clear streaming logs',
message: `Clear all ${snapshot.length} entries in this streaming panel (including ${snapshot[0].content})? Only this panel is cleared; output continues and other data is unaffected. New entries while confirmation is pending invalidate this operation.`,
type: 'warning'
})
if (!alive || readonly.value || request !== revision || logs.value !== target) return
logs.value = []
} catch {
// Canceling, closing, or pressing Esc preserves the logs, output state, and counter.
} finally {
if (alive) pending.value = false
}
}
onUnmounted(() => {
alive = false
revision++
stop()
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton v-if="!running" type="primary" icon="arrow-right" @click="start"
>Start output</HuiButton
>
<HuiButton v-else icon="close" @click="stop">Stop</HuiButton>
<HuiButton :disabled="readonly || pending || !logs.length" @click="clearStreamingLogs"
>Clear</HuiButton
>
<HuiSwitch v-model="autoScroll" active-text="Automatic scrolling (auto-scroll)" />
<HuiSwitch v-model="readonly" active-text="Read-only clear protection" />
</HuiSpace>
<HuiLog :logs="logs" :auto-scroll="autoScroll" :height="240" />
</HuiSpace>
</template>
Scrolling to the top and bottom
Use a ref to call scrollToTop() and scrollToBottom(). The scroll event receives the current scrollTop.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiLog, HuiSpace } from '@nscode/handy-ui'
import type { LogExpose, LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = Array.from({ length: 100 }, (_, i) => ({
content: `Line ${i + 1}: Processing file report-${String(i + 1).padStart(3, '0')}.csv`
}))
const logRef = ref<LogExpose | null>(null)
const scrollTop = ref<number | null>(null)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton icon="arrow-up" @click="logRef?.scrollToTop()">Scroll to top</HuiButton>
<HuiButton icon="arrow-down" @click="logRef?.scrollToBottom()">Scroll to bottom</HuiButton>
<span>scrollTop:{{ scrollTop ?? 'Shown after scrolling' }}</span>
</HuiSpace>
<HuiLog ref="logRef" :logs="logs" :height="200" @scroll="scrollTop = Math.round($event)" />
</HuiSpace>
</template>
Search filtering
When search-query is nonempty, only entries whose content contains the query are shown. Matching is case-insensitive, and matching text is not highlighted. Try error or 订单 (the order keyword in the sample data):
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInput, HuiLog, HuiSpace } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const keyword = ref('')
const logs: LogItem[] = [
{ content: 'ERROR 订单服务连接数据库失败', level: 'error' },
{ content: 'error in payment service', level: 'error' },
{ content: 'INFO 订单 SO20260001 创建成功' },
{ content: 'WARN 磁盘剩余空间不足 10%', level: 'warn' },
{ content: 'INFO 用户张伟登录成功' }
]
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInput v-model="keyword" placeholder="Search logs" clearable style="max-width: 240px" />
<HuiLog :logs="logs" :search-query="keyword" :height="160" />
</HuiSpace>
</template>
Maximum number of lines
max-lines displays only the last N entries after applying search-query. It does not modify the provided logs; manage old data yourself when logs keep growing. This example has 200 entries. Change the number to compare the visible range:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputNumber, HuiLog, HuiSpace } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = Array.from({ length: 200 }, (_, i) => ({
content: `Log entry ${i + 1}`
}))
const maxLines = ref<number | undefined>(100)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<span>Show at most</span>
<HuiInputNumber v-model="maxLines" :min="1" :max="200" :step="10" />
<span>lines (entries {{ 200 - (maxLines ?? 200) + 1 }} to 200)</span>
</HuiSpace>
<HuiLog :logs="logs" :max-lines="maxLines" :height="200" />
</HuiSpace>
</template>
Virtual scrolling
Enable virtual-scroll for large log collections, such as tens of thousands of entries. Only the visible rows are rendered. Each row is fixed at 24px high and occupies a single line, with overflow shown as an ellipsis. scrollToTop(), scrollToBottom(), and scroll also work in virtual mode.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiLog, HuiSpace } from '@nscode/handy-ui'
import type { LogExpose, LogItem } from '@nscode/handy-ui'
const levels = ['info', 'warn', 'error', 'debug'] as const
const logs: LogItem[] = Array.from({ length: 10000 }, (_, i) => ({
content:
i % 50 === 0
? `Log entry ${i + 1}: This long entry demonstrates how virtual mode keeps each entry on one line and truncates overflow with an ellipsis. Use normal mode to read the full content.`
: `Log entry ${i + 1}`,
level: levels[i % 4]
}))
const logRef = ref<LogExpose | null>(null)
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton icon="arrow-up" @click="logRef?.scrollToTop()">First entry</HuiButton>
<HuiButton icon="arrow-down" @click="logRef?.scrollToBottom()">Last entry</HuiButton>
</HuiSpace>
<HuiLog ref="logRef" :logs="logs" virtual-scroll :height="400" />
</HuiSpace>
</template>
Clearing logs
logs is a prop, so the component cannot modify it directly. clearLogs() emits update:logs([]) and clear:
- With
v-model:logs, the bound array is cleared automatically (the upper panel). - With
:logsalone, clear the array in yourclearhandler (the lower panel).
Each user-facing clear action first confirms the target panel and entry count. Canceling, closing, or pressing Esc preserves the data. Log changes, restoring initial entries, toggling read-only state, or unmounting while confirmation is pending invalidates it. Restore initial logs adds only missing entries and preserves later additions. The read-only switch protects these example actions; it is not an HuiLog prop. The underlying clearLogs() method still only emits notifications.
<script setup lang="ts">
import { onUnmounted, ref, watch } from 'vue'
import { HuiButton, HuiLog, HuiMessageBox, HuiSpace, HuiSwitch } from '@nscode/handy-ui'
import type { LogExpose, LogItem } from '@nscode/handy-ui'
const initial: LogItem[] = [
{ content: 'Starting backup of database order_db' },
{ content: 'Backup complete, file size: 128MB' }
]
const logs = ref<LogItem[]>([...initial])
const logRef = ref<LogExpose | null>(null)
const otherLogs = ref<LogItem[]>([...initial])
const otherRef = ref<LogExpose | null>(null)
const clearCount = ref(0)
// Log deletion confirmation: both panels share one pending state.
const readonly = ref(false)
const pending = ref(false)
let alive = true
let revision = 0
watch([logs, otherLogs, readonly], () => revision++, { deep: true, flush: 'sync' })
const handleClear = () => {
otherLogs.value = []
clearCount.value++
}
const requestClear = async (panel: 'model' | 'event') => {
const target = panel === 'model' ? logs.value : otherLogs.value
const control = panel === 'model' ? logRef.value : otherRef.value
if (readonly.value || pending.value || !target.length || !control) return
const request = revision
const snapshot = target.slice()
const label = panel === 'model' ? 'v-model:logs panel' : ':logs + @clear panel'
pending.value = true
try {
await HuiMessageBox.confirm({
title: 'Clear logs',
message: `Clear the ${label}: all ${snapshot.length} entries (including ${snapshot[0].content})? The other panel is preserved. This panel will call clearLogs() only after confirmation.`,
type: 'warning'
})
const current = panel === 'model' ? logs.value : otherLogs.value
const currentControl = panel === 'model' ? logRef.value : otherRef.value
if (
!alive ||
readonly.value ||
request !== revision ||
current !== target ||
currentControl !== control
)
return
control.clearLogs()
} catch {
// Canceling, closing, or pressing Esc preserves both panels and does not increment the clear event count.
} finally {
if (alive) pending.value = false
}
}
const restored = (current: LogItem[]) => {
const existing = new Set(current.map((log) => log.content))
return [...initial.filter((log) => !existing.has(log.content)), ...current]
}
const restore = () => {
logs.value = restored(logs.value)
otherLogs.value = restored(otherLogs.value)
}
onUnmounted(() => {
alive = false
revision++
})
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiSpace wrap>
<HuiButton
icon="trash"
:disabled="readonly || pending || !logs.length"
@click="requestClear('model')"
>Clear (v-model:logs)</HuiButton
>
<HuiButton
icon="trash"
:disabled="readonly || pending || !otherLogs.length"
@click="requestClear('event')"
>Clear (:logs + @clear)</HuiButton
>
<HuiButton @click="restore">Restore initial logs</HuiButton>
<HuiSwitch v-model="readonly" active-text="Read-only clear protection" />
</HuiSpace>
<HuiLog ref="logRef" v-model:logs="logs" :height="100" />
<HuiLog ref="otherRef" :logs="otherLogs" :height="100" @clear="handleClear" />
<p>clear has fired {{ clearCount }} times</p>
</HuiSpace>
</template>
Custom row content
The default slot replaces each row's content and receives { log, index }. The component still controls the level color and background.
<script setup lang="ts">
import { HuiLog } from '@nscode/handy-ui'
import type { LogItem } from '@nscode/handy-ui'
const logs: LogItem[] = [
{ content: 'Order SO20260001 created', level: 'info' },
{ content: 'Only 3 units of product A-102 remain', level: 'warn' },
{ content: 'Payment API timed out', level: 'error' },
{ content: 'Request parameters {"page":1}', level: 'debug' },
{ content: 'Defaults to info when the level is omitted' }
]
</script>
<template>
<HuiLog :logs="logs" :height="160">
<template #default="{ log, index }">
<span style="display: inline-block; width: 3em">{{ index + 1 }}</span>
<span>[{{ (log.level || 'info').toUpperCase() }}] {{ log.content }}</span>
</template>
</HuiLog>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| logs | LogItem[] | [] | Log data; supports v-model:logs |
| loading | boolean | false | Show an upper-right loading indicator and dim the log area |
| maxLines | number | undefined | Maximum number of visible entries, keeping the last N; all entries are shown when omitted |
| autoScroll | boolean | true | Automatically scroll to new entries; pauses when the user scrolls away from the bottom and resumes upon returning |
| searchQuery | string | '' | Case-insensitive substring query without match highlighting |
| virtualScroll | boolean | false | Enable virtual scrolling with fixed 24px rows and ellipsis for long lines |
| height | number | string | 300 | Panel height; numbers are pixels and strings are used as provided, such as '50vh' or '100%' (requires a parent height) |
Events
| Event | Parameters | Description |
|---|---|---|
| scroll | (scrollTop: number) | Emitted when the log area scrolls, including in virtual mode |
| clear | () | Emitted when clearLogs() is called |
| update:logs | (logs: LogItem[]) | Emitted with an empty array when clearLogs() is called; used by v-model:logs |
Slots
| Slot | Scope | Description |
|---|---|---|
| default | { log: LogItem; index: number } | Custom content for each row |
Methods
| Method | Parameters | Description |
|---|---|---|
| scrollToBottom | - | Scroll to the bottom and resume automatic scrolling |
| scrollToTop | - | Scroll to the top |
| clearLogs | - | Emit update:logs([]) and clear; use v-model:logs to actually clear the bound data |
Types
import type { LogItem, LogLevel, LogProps, LogExpose } from '@nscode/handy-ui'
type LogLevel = 'info' | 'warn' | 'error' | 'debug'
interface LogItem {
content: string
level?: LogLevel
timestamp?: string
[key: string]: unknown
}
interface LogExpose {
scrollToBottom: () => void
scrollToTop: () => void
clearLogs: () => void
}