springBoot Annotation 入参返回值日志打印

阅读更多

 

一、定义注解

package com.yare.annotation;
import java.lang.annotation.*;
/**
 * @author : zhangyan 2018/9/19
 * 日志注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
@Inherited
@Documented
public @interface Log {

    String logStr() default "";
}

 

2.定义切面,实现环绕通知

package com.yare.annotation;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.yare.exception.BusinessException;
import com.yare.exception.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author : zhangyan 2018/9/19
 */
@Component
@Aspect
@Slf4j
public class LogAspect {

    private final ObjectMapper mapper;
@Autowired
public LogAspect(ObjectMapper mapper) {
        this.mapper = mapper;
}

    @Pointcut(value = "execution(public * com.yare.controller.*.*(..))")
    public void recordLog() {
    }

    @Pointcut("@annotation(com.yare.annotation.Log)")
    private void cut() {
    }

    /**
     * 定制一个环绕通知
*
     * @param joinPoint
*/
@Around("cut()")
    public Object advice(ProceedingJoinPoint joinPoint) {
        try {
            StringBuffer param = new StringBuffer();
            for (Object object : joinPoint.getArgs()) {
                if (
                        object instanceof MultipartFile
                                || object instanceof HttpServletRequest
                                || object instanceof HttpServletResponse) {
                    continue;
}
                param.append(mapper.writeValueAsString(object))
                .append(",");
}
            log.info(joinPoint.getTarget().getClass().getName() + "." + joinPoint.getSignature().getName()
                    + ":parameter: " + param.toString() );
            final Object proceed = joinPoint.proceed();
log.info("RETURN"+proceed);
            return proceed;
} catch (Throwable e) {
            return new BusinessException(ResultCode.FAULT);
}
    }

    @Before("cut()")
    public void before() {
        log.info("已经记录下操作日志@Before 方法执行前");
}

    @After(value = "recordLog()")
    public void after() {
        log.info("已经记录下操作日志@After 方法执行后");
}

}

 

3. 在controller或者service的方法上就可以使用@Log标签了。

你可能感兴趣的:(annotation)