本文介绍如何自定义注解,实现在注解的位置打印接口调用日志。
主要使用到AOP面向切面编程的原理,令注解处为切点,建立切面,打印日志。
@MyAnnotation
import java.lang.annotation.*;
/**
* @author Admin
*/
@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface MyAnnotation {
}
LogInfo.class
import com.gcp.basicproject.util.ToolsUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
/**
* @author Admin
*/
@Aspect
@Component
@Slf4j
public class LogInfo {
@Pointcut("@annotation(com.example.annotation.anno.MyAnnotation)")
public void MyAnnotation(){};
@Before("MyAnnotation()")
public void getAnnotation(JoinPoint joinPoint){
RequestAttributes requestAttribute = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes)requestAttribute).getRequest();
log.info("----------------------------------------------------------接口调用发起----------------------------------------------------------");
log.info("接收到请求,请求方式={},请求地址={},请求IP={},请求方法名称={},请求参数={}",request.getMethod(),request.getRequestURL().toString(),
ToolsUtil.getServerIp(),joinPoint.getSignature().getName(), Arrays.toString(joinPoint.getArgs()));
}
@AfterReturning(returning = "o",pointcut = "MyAnnotation()")
public void afterAnnotation(Object o){
log.info("调用结束,返回结果为{}",o);
log.info("----------------------------------------------------------接口调用结束----------------------------------------------------------");
}
/**
* 该切面发生异常信息时进行拦截
* @param joinPoint
* @param e
*/
@AfterThrowing(pointcut = "MyAnnotation()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
String methodName = joinPoint.getSignature().getName();
List<Object> args = Arrays.asList(joinPoint.getArgs());
System.out.println("调用失败,连接点方法为:" + methodName + ",参数为:" + args + ",异常为:" + e);
log.info("----------------------------------------------------------接口调用结束----------------------------------------------------------");
}
}
测试代码
import com.example.annotation.anno.MyAnnotation;
import com.example.annotation.anno.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author Admin
*/
@RequestMapping("/annotation")
@RestController
@Slf4j
public class MyController {
@GetMapping("/get")
@MyAnnotation
public String get(User user){
return "hello";
}
}