Egg中间件:生成日志

1,088 阅读1分钟

1.需求

  • 需要将用户的增删改查操作以列表的形式展示出来。
  • 包含用户名、操作类型(增删改查)、操作模块、备注。

2.分析

首先需要实现当用户进行增删改查操作时,将对应的信息存入数据库。需要的字段信息可以从请求(ctx.request)中获取:

  • 用户名:当前登录账号的名称;
  • 操作类型:为当前请求的类型(GET|POST|DELETE|PUT);
  • 操作模块:从路由中截取,路由规则为/web/{{模块名称}}/{{其他}}

一.中间件

1. 编写中间件

/middleware目录下新建LogMiddleware.js文件:

'use strict';
module.exports = () => {
    return async function log(ctx, next) {
    ...//在这里编写逻辑
    }
};

2. 在应用中使用中间件

编辑/config/config.default.js文件:

module.exports = {
    // 配置需要的中间件,数组顺序即为中间件的加载顺序
    middleware: [ 'LogMiddleware' ],
};

二、生成日志

1. 获取数据

const arr = ctx.request.url.split('/');
const model = arr[2];
const type = ctx.request.method;

global.log = {
    user_id: ctx.user.account_id,
    log_model: model,
    log_type: type,
    log_message: null,
};

2. 处理数据

存入数据库的字段,操作模块为String ,操作类型为Number:

switch (log_model) {
    case 'ferry': model = '实时监控'; break;
    ...
    case 'area': model = '区域管理'; break;
    default: model = '用户管理';
}
switch (log_type) { // (1:查看 2:创建 3:修改 4:删除)
    case 'GET': type = 1; break;
    case 'POST': type = 2; break;
    case 'PUT': type = 3; break;
    default: type = 4;
}

3. 创建一条日志

ctx.model.Log.create(global.log);

4. 完整代码

if (ctx.request.path !== '/auth/login/web') {//排除登录接口
    const type = ctx.request.method;
    const arr = ctx.request.url.split('/');
    const model = arr[2];
    try {
        global.log = {
            user_id: ctx.user.account_id,//另外一个中间件,将当前用户信息存在了ctx.user下
            log_model: model,
            log_type: type,
            log_message: null,
        };
        await next();
        if (global.log.log_message) {
            const { log_type, log_model } = global.log;
            let model = '',
                type = '';
            switch (log_model) {
                ...
            }
            switch (log_type) { // (1:查看 2:创建 3:修改 4:删除)
                ...
            }
            global.log.log_model = model;
            global.log.log_type = type;
            ctx.model.Log.create(global.log);
        }
    } catch (error) {
        console.log('LogERROR:', error);
        this.ctx.body = {
        code: 50000,
        message: `LogERROR:${error}`,
        };
    }
} else {
    await next();
}

5. 触发生成日志

在Controller文件中,需要生成日志的接口下添加如下代码:

async index() {
    ...
    global.log.log_message = '查看用户列表';
}
async delete() {
    ...
    global.log.log_message = `删除id为${body.ids}的用户`;
}