中操作日志文件记录的是什么_管理系统必备技(3):AOP记录操作日志

微信公众号:潇雷
当努力到一定程度,幸运自会与你不期而遇

一、前言

日志的出现,是为了实现记录操作员在本系统中的操作行为,可以有效的将用户的操作保存下来,做到有迹可循,同时,良好的日志规范,能快速有效的定位问题。

二、概述

2.1 实现思路

采用spring的基于注解的aop 实现日志功能,AOP也符合开闭原则,对代码的修改是禁止的,对代码的扩展是允许的。目前的日志版本是对操作员的信息、操作的方法、操作运行的时间,请求参数和返回参数等几个重要功能进行了记录,后续若有需求可以进行修改和补充。

  • 前期准备,设计日志表,需要哪些字段。

  • 自定义注解,注解中需要添加哪些属性,可以标识操作的类型

  • 编写切面类,通常切面类中需要需要一个切入点,以及围绕这个切入点进行的操作,可以在切入点的前面@Before、也可以在后面@After ,不过本项目中采用了在中间的形式@Around,可以记录下用户的操作时间,环绕通知可以完成前置、后置、最终等所有功能。

  • 入库:编写完通知后,最后在插入日志信息。

2.2 aop的执行流程
086ca0e88f33c51b0f87cda525fe6890.png

三、数据库设计

操作日志表:

字段类型描述
Oper_idbigint主键id
Oper_modelVarchar(64)操作模块
Oper_descVarchar(64)操作描述
Oper_requ_paramVarchar(1024)请求参数
Oper_resp_paramVarchar(1024)返回参数
Oper_user_idInteger操作员id
Oper_user_nameVarchar(255)操作员名称
Oper_uriVarchar(255)请求uri
Oper_ipVarchar(64)请求ip
Oper_create_timedatetime操作时间
Oper_finish_timebigint请求耗时时间:毫秒

四、代码实现

4.1 自定义注解
1@Target(ElementType.METHOD) //注解放置的目标位置,METHOD是可注解在方法级别上
2@Retention(RetentionPolicy.RUNTIME) //注解在哪个阶段执行,可以通过反射获取注解信息
3@Documented
4public @interface OperationLog {
5    String operModul() default ""; // 操作模块
6    String operDesc() default "";  // 操作说明
7}
4.2 切面类
  1@Aspect  //声明这是一个切面类
2@Component  //此类交由Spring容器管理
3public class OperLogAspect {
4
5    @Autowired
6    private OperLogService operLogService;
7
8    //设置操作日志切入点,记录操作日志, 在注解的位置切入代码
9    @Pointcut("@annotation(com.giant.cloud.component.aop.OperationLog)")
10    public void operLogPointCut(){
11    }
12
13    @Around(value = "operLogPointCut()")
14    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Exception {
15        // 1.方法执行前的处理,相当于前置通知
16        // 获取方法签名
17        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
18        // 获取方法
19        Method method = methodSignature.getMethod();
20        // 从切面织入点处通过反射机制获取织入点处的方法
21        Map<String,Object> joinPointInfo=getJoinPointInfoMap(joinPoint);
22        //获取RequestAttributes
23        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
24        // 从获取RequestAttributes中获取HttpServletRequest的信息
25        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
26
27        // 创建一个日志对象(准备记录日志)
28        SubOperLog operLog=new SubOperLog();
29
30        Long startTime=System.currentTimeMillis();
31        operLog.setOperCreateTime(DateUtil.date(startTime));//操作时间
32        Object result = null;
33
34        //让代理方法执行
35        try {
36            result = joinPoint.proceed();
37            // 获取方法上面的注解
38            OperationLog operationLog = method.getAnnotation(OperationLog.class);
39            if (operationLog != null) {
40                String operModul = operationLog.operModul();
41                String operDesc = operationLog.operDesc();
42                operLog.setOperModel(operModul);                // 操作模块
43                operLog.setOperDesc(operDesc);                  // 操作描述
44            }
45            // 请求的参数
46            Map<String, String> rtnMap = converMap(request.getParameterMap());
47            operLog.setOperRespParam(JSON.toJSONString(result));  //返回参数
48            operLog.setOperUri(request.getRequestURI());          //请求uri
49            operLog.setOperIp(getIpAddr(request));                //获取ip
50            //完善请求信息
51            Long returnTime=System.currentTimeMillis();
52            operLog.setOperFinishTime(returnTime-startTime);   //耗时时间
53
54            if(request.getRequestURI().equalsIgnoreCase("/login")){
55                if(StrUtil.isNotEmpty(joinPointInfo.get("paramMap").toString())){
56                    operLog.setOperRequParam(joinPointInfo.get("paramMap").toString());//请求参数
57                    String operRequParam = operLog.getOperRequParam();
58                    String resp=operLog.getOperRespParam();
59
60                    if(StrUtil.isNotEmpty(resp)){
61                        ObjectMapper objectMapper = new ObjectMapper();
62                        ResponseData  responseData=objectMapper.readValue(resp,ResponseData.class);
63                        SubUserVO subUserVO=objectMapper.convertValue(responseData.getData(),SubUserVO.class);
64                        operLog.setOperUserName(subUserVO.getName());
65                        operLog.setSysId(subUserVO.getSysId());
66                        operLog.setOperUserId(subUserVO.getId());
67                        operLogService.insertLog(operLog);
68                    }
69                }
70            }else{
71                if(StrUtil.isNotEmpty(joinPointInfo.get("paramMap").toString())){
72                    operLog.setOperRequParam(joinPointInfo.get("paramMap").toString());//请求参数
73                    String operRequParam = operLog.getOperRequParam();
74                    if(StrUtil.isNotEmpty(operRequParam)){
75                        ObjectMapper objectMapper = new ObjectMapper();
76                        RequestData requestData = objectMapper.readValue(operRequParam, RequestData.class);
77                        SubUserVO user = objectMapper.convertValue(requestData.getUser(), SubUserVO.class);
78                        operLog.setOperUserId(user.getId());
79                        operLog.setSysId(user.getSysId());
80                        operLog.setOperUserName(user.getName());
81                        operLogService.insertLog(operLog);
82                    }
83                }
84            }
85        } catch (Throwable throwable) {
86            throwable.printStackTrace();
87        }
88        return result;
89    }
90/** 91     * 转换request 请求参数 92     * 93     * @param paramMap request获取的参数数组 94     */
95    private Map<String, String> converMap(Map<String, String[]> paramMap) {
96        Map<String, String> rtnMap = new HashMap<String, String>();
97        for (String key : paramMap.keySet()) {
98            rtnMap.put(key, paramMap.get(key)[0]);
99        }
100        return rtnMap;
101    }
102
103    /**104     * 获取IP地址的方法105     * @param request   传一个request对象下来106     * @return107     */
108    public static String getIpAddr(HttpServletRequest request) {
109        String ipAddress = null;
110        try {
111            ipAddress = request.getHeader("x-forwarded-for");
112            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
113                ipAddress = request.getHeader("Proxy-Client-IP");
114            }
115            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
116                ipAddress = request.getHeader("WL-Proxy-Client-IP");
117            }
118            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
119                ipAddress = request.getRemoteAddr();
120                if (ipAddress.equals("127.0.0.1")) {
121                    // 根据网卡取本机配置的IP
122                    InetAddress inet = null;
123                    try {
124                        inet = InetAddress.getLocalHost();
125                    } catch (UnknownHostException e) {
126                        e.printStackTrace();
127                    }
128                    ipAddress = inet.getHostAddress();
129                }
130            }
131            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
132            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
133                // = 15
134                if (ipAddress.indexOf(",") > 0) {
135                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
136                }
137            }
138        } catch (Exception e) {
139            ipAddress="";
140        }
141        // ipAddress = this.getRequest().getRemoteAddr();
142
143        return ipAddress;
144    }
145
146
147    /**148     * 获得切入点方法信息149     * @Author xiao lei150     * @Date  2020/12/18 11:22151     * @param  * @param joinPoint152     * @return java.util.Map<java.lang.String,java.lang.Object>153     **/
154    private static Map<String, Object> getJoinPointInfoMap(JoinPoint joinPoint) {
155        Map<String,Object> joinPointInfo=new HashMap<>();
156        String classPath=joinPoint.getTarget().getClass().getName();
157        String methodName=joinPoint.getSignature().getName();
158        joinPointInfo.put("classPath",classPath);
159        Class> clazz=null;
160        CtMethod ctMethod=null;
161        LocalVariableAttribute attr=null;
162        int length=0;
163        int pos = 0;
164
165        try {
166            clazz = Class.forName(classPath);
167            String clazzName=clazz.getName();
168            ClassPool pool=ClassPool.getDefault();
169            ClassClassPath classClassPath=new ClassClassPath(clazz);
170            pool.insertClassPath(classClassPath);
171            CtClass ctClass=pool.get(clazzName);
172            ctMethod=ctClass.getDeclaredMethod(methodName);
173            MethodInfo methodInfo=ctMethod.getMethodInfo();
174            CodeAttribute codeAttribute=methodInfo.getCodeAttribute();
175            attr=(LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
176            if(attr==null){
177                return joinPointInfo;
178            }
179            length=ctMethod.getParameterTypes().length;
180            pos= Modifier.isStatic(ctMethod.getModifiers())?0:1;
181
182        } catch (ClassNotFoundException e) {
183            e.printStackTrace();
184        } catch (NotFoundException e) {
185            e.printStackTrace();
186        }
187        Map<String,Object> paramMap=new HashMap<>();
188        Object[] paramsArgsValues=joinPoint.getArgs();
189        String[] paramsArgsNames=new String[length];
190        for (int i=0;i191            paramsArgsNames[i]=attr.variableName(i+pos);
192            String paramsArgsName=attr.variableName(i+pos);
193            if(paramsArgsName.equalsIgnoreCase("request")||
194                    paramsArgsName.equalsIgnoreCase("response")||
195                    paramsArgsName.equalsIgnoreCase("session")
196            ){
197                break;
198            }
199            Object paramsArgsValue = paramsArgsValues[i];
200            paramMap.put(paramsArgsName,paramsArgsValue);
201            joinPointInfo.put("paramMap",JSON.toJSONString(paramsArgsValue));
202        }
203        return joinPointInfo;
204    }
205}
4.3 结果

在需要展示的service层给上自定义的注解信息,最终展示的结果如下:

551b8f164e06a5ccfab661b74a6d27f1.png
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值