AOP日志记录

定义方法

package com.mtadmin.aop;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

@Documented
@Retention(RUNTIME)
@Target(METHOD)
public @interface MtLog {

    /**
     * @default add update delete
     * @return
     */
    String type() default "";

}
package com.matai.mtadmin.aop;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.matai.mtadmin.bean.Log;
import com.matai.mtadmin.feign.IAuthFeign;
import com.matai.mtadmin.service.ILogService;
import com.matai.mtadmin.util.MapUtils;
import com.matai.mtcommon.constant.SystemConstant;
import org.aspectj.lang.JoinPoint;
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 org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Aspect
@Component
public class MtLogAspect {
    
    @Autowired
    private ILogService logService;

    @Autowired
    private IAuthFeign authFeign;
    
    @Pointcut("@annotation(com.mtadmin.aop.MtLog)")
    public void logPointCut() {
        
    }
    
    @AfterReturning("logPointCut()")
    public void saveLog(JoinPoint joinPoint) {
        
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        Object beanObj = joinPoint.getArgs()[0];

        String token = request.getHeader(SystemConstant.JWT_TOKEN_KEY);
        String userId = authFeign.getUserId(token);
        String ip = null;
        try {
            InetAddress address = InetAddress.getLocalHost();
            ip = address.getHostAddress();
        } catch (Exception e){
            e.printStackTrace();
        }
        
        Log log = new Log();
        
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        MtLog mtLog = method.getAnnotation(MtLog.class);

        if (mtLog != null){

            String type = mtLog.type();
            log.setRecOpType(type);

            String content = "";

            if("update".equals(type)){
                Map<String,Object> beanMap = JSONObject.parseObject(JSON.toJSONString(beanObj));

                String recObjId = (String) beanMap.get("recObjId");
                Object oldBean = MapUtils.getLogMap().get(recObjId);

                log.setRecOpObj(recObjId);

                Map<String, Map<String, Object>> stringMapMap = compareFields(oldBean, beanObj);

                log.setRecOpContent(stringMapMap.toString());

                MapUtils.getLogMap().remove(recObjId);

            } else if ("login".equals(type)) {
                log.setRecOpObj(userId);
                log.setRecOpContent("登录系统");
            } else {
                log.setRecOpContent(JSON.toJSON(beanObj).toString());
            }
        }   
        
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = method.getName();

        log.setRecUserId(userId);
        log.setRecIp(ip);
        log.setRecOpDate(new Date());
        log.setRecClass(className);
        log.setRecMethod(methodName);

        logService.addLog(log);
        
    }

    public static Map<String, Map<String,Object>> compareFields(Object oldObject, Object newObject) {
        Map<String, Map<String, Object>> map = null;

        try{
            /**
             * 只有两个对象都是同一类型的才有可比性
             */
            if (oldObject.getClass() == newObject.getClass()) {
                map = new HashMap<String, Map<String,Object>>();

                Class clazz = oldObject.getClass();
                //获取object的所有属性
                PropertyDescriptor[] pds = Introspector.getBeanInfo(clazz,Object.class).getPropertyDescriptors();

                for (PropertyDescriptor pd : pds) {
                    //遍历获取属性名
                    String name = pd.getName();

                    //获取属性的get方法
                    Method readMethod = pd.getReadMethod();

                    // 在oldObject上调用get方法等同于获得oldObject的属性值
                    Object oldValue = readMethod.invoke(oldObject);
                    // 在newObject上调用get方法等同于获得newObject的属性值
                    Object newValue = readMethod.invoke(newObject);

                    if(oldValue instanceof List){
                        continue;
                    }

                    if(newValue instanceof List){
                        continue;
                    }

                    if(oldValue instanceof Timestamp){
                        oldValue = new Date(((Timestamp) oldValue).getTime());
                    }

                    if(newValue instanceof Timestamp){
                        newValue = new Date(((Timestamp) newValue).getTime());
                    }

                    if(oldValue instanceof Date && newValue instanceof Date && !StringUtils.isEmpty(oldValue)){
                        if(!oldValue.equals(newValue)){
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd ");
                            Map<String,Object> valueMap = new HashMap<String,Object>();
                            valueMap.put("oldValue",formatter.format(oldValue));
                            valueMap.put("newValue",formatter.format(newValue));

                            map.put(name, valueMap);
                        }
                        continue;
                    }

                    if(StringUtils.isEmpty(oldValue) && StringUtils.isEmpty(newValue)){
                        continue;
                    }else if(StringUtils.isEmpty(oldValue) && !StringUtils.isEmpty(newValue)){
                        Map<String,Object> valueMap = new HashMap<String,Object>();
                        valueMap.put("oldValue",oldValue);
                        valueMap.put("newValue",newValue);

                        map.put(name, valueMap);
                        continue;
                    }

                    if (!oldValue.equals(newValue)) {// 比较这两个值是否相等,不等就可以放入map了
                        Map<String,Object> valueMap = new HashMap<String,Object>();
                        valueMap.put("oldValue",oldValue);
                        valueMap.put("newValue",newValue);

                        map.put(name, valueMap);
                    }
                }
            }
        }catch(Exception e){
            e.printStackTrace();
        }

        return map;
    }

}

在方法中注入


image.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容