spring Aspect 切面日志

当有版本冲突的时候,例如下图,可以适当调整hibernate-validator的版本号4.2.0.Final,低版本可能不依赖Jboss-common

1,注解

 

import java.lang.annotation.Documented;  
import java.lang.annotation.ElementType;  
import java.lang.annotation.Retention;  
import java.lang.annotation.RetentionPolicy;  
import java.lang.annotation.Target;  
   
 @Target({ElementType.METHOD, ElementType.TYPE })  
 @Retention(RetentionPolicy.RUNTIME)  
 @Documented  
 public @interface AspectJAOP {  
    
     boolean logInput() default true;
     
     boolean logOutput() default true;
     
 }  


2,切面

 

import com.alibaba.fastjson.JSON;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

@Aspect
public class AspectLog {

    Logger logger = LoggerFactory.getLogger(AspectLog.class);
    private static final Validator validator;
    static {
        ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
        validator = vf.getValidator();
    }

    @Pointcut("@annotation(com.home.common.annotation.AspectJAOP)")
    public void aroundByAnnotation() {
    }

    @Around("aroundByAnnotation() && @annotation(loggingAOP)")
    private Object around(ProceedingJoinPoint joinPoint, LoggingAOP loggingAOP) throws Throwable {

        long start = System.currentTimeMillis();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String className = signature.getDeclaringType().getName();
        Method method = signature.getMethod();
        Object[] args = joinPoint.getArgs();

        if (!CollectionUtils.isEmpty(checkInput(args))) {
            return checkInput(args);
        }

        StringBuilder sb = new StringBuilder();
        sb.append("Cost ").append(System.currentTimeMillis() - start + "ms,");

        if (loggingAOP.logInput()) {
            sb.append(" Request:{");
            for (int i = 0; i < args.length; i++) {
                sb.append((args[i]));
                if (i < args.length - 1) {
                    sb.append(",");
                }

            }
            sb.append("}");
        }
        Object returnedObj = joinPoint.proceed();
        if (loggingAOP.logOutput()) {
            sb.append(" Response:{").append(returnedObj).append("}");
        }
        LoggerFactory.getLogger(className).info("{}.{}:{}", signature.getDeclaringType().getSimpleName(), method.getName(), sb.toString());
        return returnedObj;
    }

    private Map<String, String> checkInput(Object[] args) {
        // 只校验方法的第一个参数
        Map<String, String> commonResonse = new HashMap<String, String>();
        if (args != null && args.length > 0) {
            if (args[0] == null) {
                commonResonse.put("code", "9999");
                commonResonse.put("msg", "参数不合法[null]");
                logger.info("Resonse={}", JSON.toJSONString(commonResonse));
                return commonResonse;
            }
            List<String> errors = violation(args[0]);
            if (errors.size() > 0) {
                commonResonse.put("code", "9999");
                commonResonse.put("msg", StringUtils.join(errors, ", "));
                logger.info("Resonse={}", JSON.toJSONString(commonResonse));
                return commonResonse;
            }
        }
        return commonResonse;
    }

    public static List<String> violation(Object object) {
        List<String> msgs = new ArrayList<String>();
        Set<ConstraintViolation<Object>> set = validator.validate(object);
        if (set != null && !set.isEmpty()) {
            for (ConstraintViolation<Object> cvo : set) {
                msgs.add(cvo.getMessage());
            }
        }
        return msgs;
    }
}

 

 

 

 

 

 

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值