1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- 'use strict';
- module.exports = ({ toMongoDB = false }) =>
- async function requestLog(ctx, next) {
- await next();
- try {
- const request = ctx.request;
- // 请求路由
- const url = request.url;
- // 请求方法
- const method = request.method;
- // get 请求不发日志
- if (method === 'GET') return;
- // 请求的分站标识
- const tenant = ctx.tenant || 'master';
- // 请求的用户
- const user = ctx.user;
- // 当前模块
- const module = ctx.app.config.module;
- // 所有的请求路由
- const routers = ctx.router.stack;
- // 匹配路由及http请求方法
- const route = routers.find(route => {
- const reg = new RegExp(route.regexp);
- // 正则验证
- const regResult = reg.test(url);
- // http方法验证
- const methodResult = route.methods.includes(method);
- if (regResult && methodResult) return true;
- return false;
- });
- if (!route) return;
- // 不往数据库里写,就回去
- if (!toMongoDB) return;
- // 组织数据,给MQ,让日志服务去写
- const { id: user_id, account, name } = user;
- const logData = { user_id, account, name, _tenant: tenant, opera: route.name, path: url, module };
- // 先用mq发送,不行再用http发
- if (ctx.mq) {
- ctx.service.util.rabbitMq.sendToMqQueue(logData, 'logs');
- } else {
- // http请求
- const httpPrefix = ctx.app.config.httpPrefix;
- if (httpPrefix && httpPrefix.logs) {
- const uri = `${httpPrefix.logs}/logs`;
- ctx.service.util.httpUtil.cpost(uri, logData);
- }
- }
- } catch (error) {
- // 没啥可输出,别中断就行
- }
- };
|