Skip to content

🎬 火宝短剧 - 基于AI的一站式短剧生成平台 《一句话生成完整短剧,从剧本到成片全自动化》 Huobao Drama - An AI-Powered End-to-End Short Drama Generator "One Sentence to Complete Drama: Fully Automated from Script to Final Video"

TypeScript

feat: add global request logger and error handler

Connor590e8c47d48c
diff --git a/backend/src/index.ts b/backend/src/index.ts
index 5f0e82c..caa6cec 100644
--- a/backend/src/index.ts
+++ b/backend/src/index.ts
@@ -2,7 +2,6 @@ import { serve } from '@hono/node-server'
import { serveStatic } from '@hono/node-server/serve-static'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
-import { logger } from 'hono/logger'
import path from 'path'
import { fileURLToPath } from 'url'
@@ -17,6 +16,7 @@ import upload from './routes/upload.js'
import aiConfigs, { aiProviders } from './routes/aiConfigs.js'
import agentConfigs from './routes/agentConfigs.js'
import agent from './routes/agent.js'
+import { requestLogger, errorHandler } from './middleware/logger.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const projectRoot = path.resolve(__dirname, '../..')
@@ -25,10 +25,11 @@ const app = new Hono()
// Middleware
app.use('*', cors({
- origin: ['http://localhost:3012', 'http://localhost:5678', 'http://localhost:5679'],
+ origin: ['http://localhost:3013', 'http://localhost:5679'],
credentials: true,
}))
-app.use('*', logger())
+app.use('*', errorHandler)
+app.use('*', requestLogger)
// Health check
app.get('/api/v1/health', (c) => c.json({ status: 'ok', timestamp: new Date().toISOString() }))
@@ -53,8 +54,8 @@ app.route('/api/v1', api)
// Serve static files (storage)
app.use('/static/*', serveStatic({ root: path.join(projectRoot, 'data') }))
-// Serve frontend
-const distPath = path.join(projectRoot, 'web', 'dist')
+// Serve frontend (production build)
+const distPath = path.join(projectRoot, 'frontend', 'dist')
app.use('*', serveStatic({ root: distPath }))
app.get('*', serveStatic({ root: distPath, path: 'index.html' }))
diff --git a/backend/src/middleware/logger.ts b/backend/src/middleware/logger.ts
new file mode 100644
index 0000000..4909e57
--- /dev/null
+++ b/backend/src/middleware/logger.ts
@@ -0,0 +1,68 @@
+import type { MiddlewareHandler } from 'hono'
+
+const colors = {
+ reset: '\x1b[0m',
+ dim: '\x1b[2m',
+ green: '\x1b[32m',
+ yellow: '\x1b[33m',
+ red: '\x1b[31m',
+ cyan: '\x1b[36m',
+ magenta: '\x1b[35m',
+}
+
+function statusColor(status: number): string {
+ if (status >= 500) return colors.red
+ if (status >= 400) return colors.yellow
+ if (status >= 300) return colors.cyan
+ return colors.green
+}
+
+function formatTime(): string {
+ return new Date().toLocaleTimeString('zh-CN', { hour12: false })
+}
+
+/**
+ * 全局日志中间件 — 打印请求方法/路径/状态/耗时/请求体
+ */
+export const requestLogger: MiddlewareHandler = async (c, next) => {
+ const method = c.req.method
+ const path = c.req.path
+ const start = performance.now()
+
+ // 打印请求
+ const time = formatTime()
+ let bodyInfo = ''
+ if (['POST', 'PUT', 'PATCH'].includes(method)) {
+ try {
+ const clone = c.req.raw.clone()
+ const text = await clone.text()
+ if (text) {
+ const truncated = text.length > 500 ? text.slice(0, 500) + '...' : text
+ bodyInfo = `\n ${colors.dim}body: ${truncated}${colors.reset}`
+ }
+ } catch {}
+ }
+
+ console.log(`${colors.dim}${time}${colors.reset} ${colors.cyan}${method}${colors.reset} ${path}${bodyInfo}`)
+
+ await next()
+
+ const ms = (performance.now() - start).toFixed(0)
+ const status = c.res.status
+ const sc = statusColor(status)
+ console.log(`${colors.dim}${time}${colors.reset} ${colors.cyan}${method}${colors.reset} ${path} ${sc}${status}${colors.reset} ${colors.dim}${ms}ms${colors.reset}`)
+}
+
+/**
+ * 全局错误处理 — 捕获未处理异常,打印完整堆栈
+ */
+export const errorHandler: MiddlewareHandler = async (c, next) => {
+ try {
+ await next()
+ } catch (err: any) {
+ const status = err.status || 500
+ console.error(`${colors.red}[ERROR]${colors.reset} ${c.req.method} ${c.req.path}`)
+ console.error(err.stack || err.message || err)
+ return c.json({ code: status, message: err.message || 'Internal Server Error' }, status)
+ }
+}