89 lines
2.6 KiB
TypeScript
89 lines
2.6 KiB
TypeScript
import { NextRequest, NextResponse } from 'next/server'
|
|
import { getServerSession } from 'next-auth'
|
|
import { authOptions } from '@/lib/auth'
|
|
import { hasSystemAdminPermission, isSuperAdmin } from '@/lib/department-permission'
|
|
import { execFile } from 'child_process'
|
|
import { promisify } from 'util'
|
|
|
|
const execFileAsync = promisify(execFile)
|
|
const LOG_CONTAINER_NAME = 'youyidian-3d-material'
|
|
const DEFAULT_LOG_LINES = 100
|
|
const MAX_LOG_LINES = 5000
|
|
const MAX_LOG_OUTPUT_LENGTH = 50000
|
|
|
|
function normalizeLogLines(value: string | null): number {
|
|
const parsed = Number.parseInt(value || '', 10)
|
|
if (!Number.isFinite(parsed)) {
|
|
return DEFAULT_LOG_LINES
|
|
}
|
|
|
|
return Math.min(Math.max(parsed, 1), MAX_LOG_LINES)
|
|
}
|
|
|
|
function filterLogsByKeyword(logs: string, keyword: string): string {
|
|
const normalizedKeyword = keyword.trim().toLocaleLowerCase()
|
|
if (!normalizedKeyword) {
|
|
return logs
|
|
}
|
|
|
|
return logs
|
|
.split(/\r?\n/)
|
|
.filter((line) => line.toLocaleLowerCase().includes(normalizedKeyword))
|
|
.join('\n')
|
|
}
|
|
|
|
/**
|
|
* 获取系统日志(仅管理员)
|
|
* 用于调试和监控系统状态
|
|
*/
|
|
export async function GET(request: NextRequest) {
|
|
try {
|
|
// 验证管理员权限
|
|
const session = await getServerSession(authOptions)
|
|
if (!session || !(session.user as any).id) {
|
|
return NextResponse.json({ error: '未登录' }, { status: 401 })
|
|
}
|
|
|
|
const userId = (session.user as any).id
|
|
const userRole = (session.user as any).role
|
|
const isSuperAdminUser = await isSuperAdmin(userId)
|
|
if (!hasSystemAdminPermission(userRole, isSuperAdminUser)) {
|
|
return NextResponse.json({ error: '无权限访问' }, { status: 403 })
|
|
}
|
|
|
|
// 获取查询参数
|
|
const searchParams = request.nextUrl.searchParams
|
|
const lines = normalizeLogLines(searchParams.get('lines'))
|
|
const keyword = searchParams.get('keyword') || ''
|
|
|
|
const { stdout, stderr } = await execFileAsync(
|
|
'docker',
|
|
['logs', '--tail', String(lines), LOG_CONTAINER_NAME],
|
|
{
|
|
maxBuffer: 10 * 1024 * 1024, // 10MB
|
|
timeout: 10000,
|
|
encoding: 'utf8',
|
|
},
|
|
)
|
|
|
|
const rawLogs = [stdout, stderr].filter(Boolean).join('\n')
|
|
const logs = filterLogsByKeyword(rawLogs, keyword)
|
|
|
|
return NextResponse.json({
|
|
success: true,
|
|
lines: logs ? logs.split(/\r?\n/).length : 0,
|
|
logs: logs.substring(0, MAX_LOG_OUTPUT_LENGTH),
|
|
truncated: logs.length > MAX_LOG_OUTPUT_LENGTH,
|
|
})
|
|
} catch (error) {
|
|
console.error('[SystemLogs] Error:', error)
|
|
return NextResponse.json(
|
|
{
|
|
error: '获取日志失败',
|
|
logs: '',
|
|
},
|
|
{ status: 500 }
|
|
)
|
|
}
|
|
}
|