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标签了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值