whyclxw
2024-07-02 022fa467ee76ae7b8d02706f75d250a1e7280569
日志管理
1个文件已修改
3个文件已添加
314 ■■■■■ 已修改文件
src/main/java/com/whyc/aop/CustomExceptionResultHandler.java 44 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/aop/OperationLogAspect.java 241 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/service/UserInfService.java 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/util/JsonUtil.java 25 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/aop/CustomExceptionResultHandler.java
New file
@@ -0,0 +1,44 @@
package com.whyc.aop;
import com.whyc.constant.OperationLogEnum;
import com.whyc.dto.Response;
import com.whyc.service.OperationLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 针对RestController层捕捉异常,结果统一返回
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class, Service.class})
public class CustomExceptionResultHandler {
    @Autowired
    private OperationLogService logService;
    /**错误捕捉,状态码:202*/
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.ACCEPTED)
    public Response sendErrorResponse2Defined(Exception e, HttpServletResponse response, HttpServletRequest request){
        String exceptionStr = e.toString();
        String requestURI = request.getRequestURI();
        //单项提取-登录超时
        Integer type = OperationLogEnum.TYPE_1_SYS.getType();
        if (exceptionStr.contains("login") && exceptionStr.contains("imeout")) {
            logService.record(OperationLogEnum.TYPE_1_SYS.getType(),OperationLogEnum.TYPE_2_CONNECTION_TIMEOUT.getType(), "登录请求超时", "异常信息:" + exceptionStr);
        } else {
            logService.record(OperationLogEnum.TYPE_1_SYS.getType(),OperationLogEnum.TYPE_2_EXCEPTION.getType(),"接口调用异常", "接口调用异常:调用接口" + requestURI + "发生错误:" + exceptionStr);
        }
        return new Response().set(0, "接口请求异常,请联系软件人员进行处理.异常信息" + exceptionStr);
    }
}
src/main/java/com/whyc/aop/OperationLogAspect.java
New file
@@ -0,0 +1,241 @@
package com.whyc.aop;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.whyc.constant.OperationLogEnum;
import com.whyc.dto.Response;
import com.whyc.service.OperationLogService;
import com.whyc.util.JsonUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.HashMap;
/**
 * 定义aop,对特定的接口进行内容捕捉,生成操作日志
 * 切面为controller
 * 切点为Point表达式
 * 具体连接点为JoinPoint
 * 处理方式为doAfterReturning
 */
@Component
@Aspect
public class OperationLogAspect {
    @Autowired
    private OperationLogService service;
    /**定义切点*/
    @Pointcut(value = "execution(public * com.whyc..controller.*.add*(..))" +
            "|| execution(public * com.whyc..controller.*.delete*(..))" +
            "|| execution(public * com.whyc..controller.*.update*(..))" +
            "|| execution(public * com.whyc..controller.LoginController.*(..))" +
            "|| execution(public * com.whyc..controller.UserInfController.resetSnId*(..))"
    )
    private void operationLogPointcut(){};
    /**aop处理类,对捕捉到的切点接口,进行数据处理*/
    @AfterReturning(pointcut = "operationLogPointcut()",returning = "resp")
    public void doAfterReturnOperation(JoinPoint point,Object resp){
        Response response = (Response) resp;
        Signature signature = point.getSignature();
        String methodSignature = signature.toString();
        //方法名
        // e.g:update
        String methodName = signature.getName();
        //执行的类全名
        // e.g: com.whyc.controller.CKPowerDevRtSetController
        String fullClassName = signature.getDeclaringTypeName();
        //获取类型
        String[] fullClassNameSplit = fullClassName.split("\\.");
        //类名
        // e.g: CKPowerDevRtSetController
        String classNameTrue = fullClassNameSplit[fullClassNameSplit.length - 1];
        Integer type1 = 0;
        Integer type2 = 0;
        String operationTypeName = "";
        //系统级
        if (classNameTrue.equals("UserInfController")) {
            if(methodName.contains("add")){ //用户新增
                type1 = OperationLogEnum.TYPE_1_SYS.getType();
                type2 = OperationLogEnum.TYPE_2_USER_ADD.getType();
                operationTypeName = OperationLogEnum.TYPE_2_USER_ADD.getName();
            }else if(methodName.contains("update")){ //用户修改
                type1 = OperationLogEnum.TYPE_1_SYS.getType();
                type2 = OperationLogEnum.TYPE_2_USER_UPDATE.getType();
                operationTypeName = OperationLogEnum.TYPE_2_USER_UPDATE.getName();
            }else if(methodName.contains("delete")){ //用户删除
                type1 = OperationLogEnum.TYPE_1_SYS.getType();
                type2 = OperationLogEnum.TYPE_2_USER_DELETE.getType();
                operationTypeName = OperationLogEnum.TYPE_2_USER_DELETE.getName();
            }else if(methodName.contains("resetSnId")){ //密码重置
                type1 = OperationLogEnum.TYPE_1_SYS.getType();
                type2 = OperationLogEnum.TYPE_2_USER_UPDATE_PASSWORD.getType();
                operationTypeName = OperationLogEnum.TYPE_2_USER_UPDATE_PASSWORD.getName();
            }
        }else if(classNameTrue.equals("LoginController")){
            if(methodName.equals("login")){
                if((boolean) response.getData()){ //用户登录
                    type1 = OperationLogEnum.TYPE_1_SYS.getType();
                    type2 = OperationLogEnum.TYPE_2_LOGIN.getType();
                    operationTypeName = OperationLogEnum.TYPE_2_LOGIN.getName();
                }else { //用户登录失败
                    type1 = OperationLogEnum.TYPE_1_SYS.getType();
                    type2 = OperationLogEnum.TYPE_2_LOGIN_FAIL.getType();
                    operationTypeName = OperationLogEnum.TYPE_2_LOGIN_FAIL.getName();
                }
            }
            else if(methodName.equals("logout")){ //用户退出
                type1 = OperationLogEnum.TYPE_1_SYS.getType();
                type2 = OperationLogEnum.TYPE_2_LOGOUT.getType();
                operationTypeName = OperationLogEnum.TYPE_2_LOGOUT.getName();
            }
            else if(methodName.equals("changeSnId")){ //用户密码重置
                type1 = OperationLogEnum.TYPE_1_SYS.getType();
                type2 = OperationLogEnum.TYPE_2_USER_UPDATE_PASSWORD.getType();
                operationTypeName = OperationLogEnum.TYPE_2_USER_UPDATE_PASSWORD.getName();
            }
        }
        //业务级
        else if(classNameTrue.equals("CKPowerDevSignalSetController")
        ||classNameTrue.equals("CKPowerDevRtSetController")){ //电源设备设置
            if(methodName.startsWith("update")){
                type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
                type2 = OperationLogEnum.TYPE_2_POWER_UPDATE.getType();
                operationTypeName = OperationLogEnum.TYPE_2_POWER_UPDATE.getName();
            }
        }else if(classNameTrue.equals("CKPowerDevBattRtStateSetController")){ //核容设备信息相关设置
            if(methodName.startsWith("update")){
                type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
                type2 = OperationLogEnum.TYPE_2_BATTERY_UPDATE.getType();
                operationTypeName = OperationLogEnum.TYPE_2_BATTERY_UPDATE.getName();
            }
        }
        else if(classNameTrue.equals("CKPowerDevHrTestParamController")) { //核容设备遥调遥控
            if (methodName.startsWith("update")) {
                type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
                type2 = OperationLogEnum.TYPE_2_BATTERY_TEST_PARAM_UPDATE.getType();
                operationTypeName = OperationLogEnum.TYPE_2_BATTERY_TEST_PARAM_UPDATE.getName();
            }
        }
        else if(classNameTrue.contains("Alarm")
                ||classNameTrue.contains("Alm")){ //告警设置
            if(methodName.startsWith("update")){
                type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
                type2 = OperationLogEnum.TYPE_2_ALARM.getType();
                operationTypeName = OperationLogEnum.TYPE_2_ALARM.getName();
            }
        }
        else if(classNameTrue.contains("BreakerInfController")){ //断路器
            type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
            type2 = OperationLogEnum.TYPE_2_BREAKER.getType();
            operationTypeName = OperationLogEnum.TYPE_2_BREAKER.getName();
        }
        else if(classNameTrue.contains("CKPowerDevBreakerControlController")){ //断路器控制
            type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
            type2 = OperationLogEnum.TYPE_2_BREAKER_CONTROL.getType();
            operationTypeName = OperationLogEnum.TYPE_2_BREAKER_CONTROL.getName();
        }
        else if(classNameTrue.contains("GatewayInfController")){ //网关
            type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
            type2 = OperationLogEnum.TYPE_2_GATEWAY.getType();
            operationTypeName = OperationLogEnum.TYPE_2_GATEWAY.getName();
        }
        else if(classNameTrue.contains("CKPowerDevModecontrolController")){ //电源设备模块控制操作
            type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
            type2 = OperationLogEnum.TYPE_2_POWER_MODE_CONTROL.getType();
            operationTypeName = OperationLogEnum.TYPE_2_POWER_MODE_CONTROL.getName();
        }
        else if(classNameTrue.contains("CKPowerDevModeparamController")){ //电源设备模块参数操作
            type1 = OperationLogEnum.TYPE_1_SERVICE.getType();
            type2 = OperationLogEnum.TYPE_2_POWER_MODE_PARAM.getType();
            operationTypeName = OperationLogEnum.TYPE_2_POWER_MODE_PARAM.getName();
        }
        // TODO else if()
        String module = "模块";
        String className = classNameTrue.replace("Controller", module);
       /* //操作时间
        Date operationTime = new Date();
        //客户端ip
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String terminalIp = request.getRemoteAddr();*/
        //操作信息
        //获取切点方法信息
        String[] parameterNames = ((MethodSignature) signature).getParameterNames();
        Object[] args = point.getArgs();
        HashMap<String, Object> map = new HashMap<>();
        for (int i = 0; i < parameterNames.length; i++) {
            if (args[i] != null) {
                StringBuilder paramBuilder = new StringBuilder();
                //String param = args[i].toString();
                try {
                    JsonObject paramJsonObject = JsonUtil.getGson().toJsonTree(args[i]).getAsJsonObject();
                    if(paramJsonObject.has("logList")){
                        paramJsonObject.remove("logList");
                        JsonElement jsonElement = new JsonPrimitive("logList字段忽略存储");
                        paramJsonObject.add("logList",jsonElement);
                    }
                    paramBuilder.append(paramJsonObject.toString());
                }catch (Exception e){
                    paramBuilder.append(args[i].toString());
                }
                /*String[] paramSetArr = param.split(",");
                int paramSetLength = paramSetArr.length;
                for (int j = 0; j < paramSetLength; j++) {
                    String paramSet = paramSetArr[j];
                    if(j == 0){ //首行,特殊情况,存在null但是要保留
                        if(paramSet.endsWith("=null")){
                            if(paramSet.contains("(")){
                                paramBuilder.append(paramSet.substring(0,paramSet.lastIndexOf("(")+1));
                                continue;
                            }
                        }
                    }else if(j == paramSetLength -1){ //末行,特殊情况,存在null但是要保留
                        if(paramSet.endsWith("=null)")){
                            paramBuilder.append(")");
                            continue;
                        }
                    }
                    //其他非null情况
                    if(!paramSet.endsWith("=null")){
                        paramBuilder.append(paramSet);
                    }
                }*/
                //map.put(parameterNames[i], args[i].toString());
                map.put(parameterNames[i], paramBuilder.toString());
            }
        }
        //登录接口的密码,不存储
        if (methodSignature.contains("LoginController.login")) {
            map.put("usnId","密码密文保密,忽略存储");
        }
        //修改密码接口的密码,也不存储
        else if(methodSignature.contains("LoginController.changeSnId")){
            map.put("oldSnId","旧密码密文保密,忽略存储");
            map.put("newSnId","新密码密文保密,忽略存储");
        }
        String operationMsg = "执行了" + className + "的" + operationTypeName + "操作.";
        String operationDetail = "具体调用方法为:" + methodName + ",具体参数为:" + map.toString();
        service.record(type1, type2, operationMsg, operationDetail);
    }
}
src/main/java/com/whyc/service/UserInfService.java
@@ -176,13 +176,13 @@
        }
        //根据用户id查询用户信息
        QueryWrapper qWrapper=new QueryWrapper();
        qWrapper.eq("uid",uid);
        qWrapper.eq("uid",Integer.valueOf(uid));
        qWrapper.last("limit 1");
        UserInf uinf=mapper.selectOne(qWrapper);
        //编辑
        UpdateWrapper wrapper =new UpdateWrapper();
        wrapper.set("uid",Integer.valueOf(maxUid)+1);
        wrapper.eq("uid",uid);
        wrapper.eq("uid",Integer.valueOf(uid));
        int flag= mapper.update(null,wrapper);
        //如果是普通用户自己强退,将用户名对应的sessionId变更
        ServletContext servletContext = request.getServletContext();
src/main/java/com/whyc/util/JsonUtil.java
New file
@@ -0,0 +1,25 @@
package com.whyc.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
public class JsonUtil {
    /**
     *
     * @param dataType    需要解析的日期的格式如:"yyyy-MM-dd HH:mm:ss"
     * @return    得到对应的gson对象
     */
    public static Gson getGson(String dataType){
        return new GsonBuilder().setDateFormat(dataType).create();
    }
    /**
     * 获取默认的gson对象
     * @return
     */
    public static Gson getGson(){
        return new Gson();
    }
}