浏览代码

feat:新增日志中间件

master
leiyun 3 天前
父节点
当前提交
ced9316fcd
共有 3 个文件被更改,包括 43 次插入21 次删除
  1. +5
    -0
      src/config/middleware.js
  2. +0
    -21
      src/controller/base.js
  3. +38
    -0
      src/middleware/request_log.js

+ 5
- 0
src/config/middleware.js 查看文件

@@ -1,7 +1,12 @@
const path = require('path');
const isDev = think.env === 'development';
const requestLog = require('../middleware/request_log.js');

module.exports = [
{
handle: requestLog,
options: {}
},
{
handle: 'meta',
options: {


+ 0
- 21
src/controller/base.js 查看文件

@@ -19,11 +19,6 @@ const WHITE_LIST = [
module.exports = class extends think.Controller {
async __before() {
const path = this.ctx.path;

// 记录请求开始时间和参数
this._requestStart = Date.now();
this._requestPath = path;
this._requestParams = { ...this.get(), ...this.post() };
// 白名单放行(同时匹配带.html后缀的路径)
const pathNoSuffix = path.replace(/\.html$/, '');
if (WHITE_LIST.includes(path) || WHITE_LIST.includes(pathNoSuffix)) {
@@ -68,22 +63,6 @@ module.exports = class extends think.Controller {
}
}

async __after() {
const dayjs = require('dayjs');
const elapsed = ((Date.now() - (this._requestStart || Date.now())) / 1000).toFixed(3);
const result = JSON.stringify(this.ctx.body || '').slice(0, 500);
const log = [
'=================== 请求日志 ===================',
`path: ${this._requestPath || this.ctx.path}`,
`params: ${JSON.stringify(this._requestParams || {})}`,
`result: ${result}`,
`time: ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`,
`耗时: ${elapsed}秒`,
'=================== 请求结束 ===================',
].join('\n');
console.log(log);
}

// 加载用户权限
async loadUserPermissions() {
if (!this.adminUser) return;


+ 38
- 0
src/middleware/request_log.js 查看文件

@@ -0,0 +1,38 @@
const dayjs = require('dayjs');

module.exports = () => {
return async (ctx, next) => {
// 跳过静态资源和source map
if (ctx.path.startsWith('/static/') || ctx.path === '/favicon.ico' || ctx.path.endsWith('.map')) {
return next();
}

const start = Date.now();
const params = { ...ctx.query, ...(ctx.request.body || {}) };

try {
await next();
} catch (e) {
throw e;
} finally {
// 只打印 JSON 接口响应(this.success / this.fail / this.json)
const body = ctx.body;
const isJson = body && typeof body === 'object' && ('code' in body || 'errno' in body || 'data' in body);
if (isJson) {
const elapsed = ((Date.now() - start) / 1000).toFixed(3);
const result = JSON.stringify(body).slice(0, 500);
const log = [
'=================== 请求日志 ===================',
`path: ${ctx.path}`,
`method: ${ctx.method}`,
`params: ${JSON.stringify(params)}`,
`result: ${result}`,
`time: ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`,
`耗时: ${elapsed}秒`,
'=================== 请求结束 ===================',
].join('\n');
console.log(log);
}
}
};
};

正在加载...
取消
保存