Browse Source

feat: 添加站点日志记录,优化响应时间中间件,更新页面内容

alpha
谢亚昕 2 months ago
parent
commit
e7425ec594
  1. 17
      src/logger.js
  2. 11
      src/main.js
  3. 57
      src/middlewares/ResponseTime/index.js
  4. 2
      src/views/page/index/index.pug

17
src/logger.js

@ -50,6 +50,18 @@ log4js.configure({
pattern: '[%d{yyyy-MM-dd hh:mm:ss}] [%p] %m',
},
},
site: {
type: "file",
filename: "logs/site.log",
maxLogSize: 102400,
pattern: "-yyyy-MM-dd.log",
alwaysIncludePattern: true,
backups: 3,
layout: {
type: 'pattern',
pattern: '[%d{yyyy-MM-dd hh:mm:ss}] [%p] %m',
},
},
console: {
type: "console",
layout: {
@ -60,6 +72,8 @@ log4js.configure({
},
categories: {
jobs: { appenders: ["console", "jobs"], level: "ALL" },
site: { appenders: ["site"], level: "ALL" },
console: { appenders: ["console"], level: "ALL" },
error: { appenders: ["console", "error"], level: "error" },
default: { appenders: ["console", "all"], level: "ALL" },
debug: { appenders: ["debug"], level: "debug" },
@ -68,5 +82,8 @@ log4js.configure({
// 导出常用logger实例,便于直接引用
export const logger = log4js.getLogger();
export const debugLogger = log4js.getLogger('debug');
export const jobLogger = log4js.getLogger('jobs');
export const errorLogger = log4js.getLogger('error');
export const siteLogger = log4js.getLogger('site');
export const consoleLogger = log4js.getLogger('console');

11
src/main.js

@ -1,5 +1,5 @@
// 日志、全局插件、定时任务等基础设施
import "./logger.js"
import { consoleLogger } from "./logger.js"
import "./jobs/index.js"
// 第三方依赖
@ -10,7 +10,6 @@ import log4js from "log4js"
// 应用插件与自动路由
import LoadMiddlewares from "./middlewares/install.js"
const logger = log4js.getLogger()
const app = new Koa()
// 注册插件
@ -33,10 +32,10 @@ const server = app.listen(PORT, () => {
return "localhost"
}
const localIP = getLocalIP()
logger.trace(`===================【服务器地址】====================`)
logger.trace(` http://localhost:${port} (本地地址) `)
logger.trace(` http://${localIP}:${port} (本地地址) `)
logger.trace(`===================【服务器地址】====================`)
consoleLogger.trace(`===================【服务器地址】====================`)
consoleLogger.trace(` http://localhost:${port} (本地地址) `)
consoleLogger.trace(` http://${localIP}:${port} (本地地址) `)
consoleLogger.trace(`===================【服务器地址】====================`)
})
export default app

57
src/middlewares/ResponseTime/index.js

@ -1,4 +1,11 @@
import { logger } from "@/logger"
import { siteLogger, logger } from "@/logger"
// 静态资源扩展名列表
const staticExts = [".css", ".js", ".png", ".jpg", ".jpeg", ".gif", ".ico", ".svg", ".map", ".woff", ".woff2", ".ttf", ".eot"]
function isStaticResource(path) {
return staticExts.some(ext => path.endsWith(ext))
}
/**
* 响应时间记录中间件
@ -6,15 +13,51 @@ import { logger } from "@/logger"
* @param {Function} next - Koa中间件链函数
*/
export default async (ctx, next) => {
if(!ctx.path.includes('/api')) {
return await next()
if (isStaticResource(ctx.path)) {
await next()
return
}
logger.info("====================[REQ]====================")
logger.info(`➡️ ${ctx.method} ${ctx.path}`)
if (!ctx.path.includes("/api")) {
const start = Date.now()
await next()
const ms = Date.now() - start
ctx.set("X-Response-Time", `${ms}ms`)
if (ms > 500) {
siteLogger.info(`${ctx.path} | ⏱️ ${ms}ms`)
}
return
}
// API日志记录
const start = Date.now()
await next()
const ms = Date.now() - start
ctx.set("X-Response-Time", `${ms}ms`)
logger.info(`⬅️ ${ctx.method} ${ctx.url} | ⏱️ ${ms}ms`)
logger.info("====================[END]====================\n")
const Threshold = 0
if (ms > Threshold) {
logger.info("====================[➡️REQ]====================")
// 用户信息(假设ctx.state.user存在)
const user = ctx.state && ctx.state.user ? ctx.state.user : null
// IP
const ip = ctx.ip || ctx.request.ip || ctx.headers["x-forwarded-for"] || ctx.req.connection.remoteAddress
// 请求参数
const params = {
query: ctx.query,
body: ctx.request.body,
}
// 响应状态码
const status = ctx.status
// 组装日志对象
const logObj = {
method: ctx.method,
path: ctx.path,
url: ctx.url,
user: user ? { id: user.id, username: user.username } : null,
ip,
params,
status,
ms,
}
logger.info(JSON.stringify(logObj, null, 2))
logger.info("====================[⬅️END]====================\n")
}
}

2
src/views/page/index/index.pug

@ -5,4 +5,4 @@ extends /layouts/page.pug
//- include /htmx/login.pug
block pageContent
div sad
div adsd

Loading…
Cancel
Save