<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
package swagger2.demo.config.my;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface MyLog {
String desc() default "";
}
package swagger2.demo.config.my;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
@Slf4j
public class MyAspect {
@Pointcut("@annotation(swagger2.demo.config.my.MyLog)")
public void myLog() {
}
@Before("myLog()")
public void doBefore(JoinPoint joinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
MyLog annotation = signature.getMethod().getAnnotation(MyLog.class);
String desc = annotation.desc();
log.info("接口描述是===[{}]",desc);
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
log.info("======================请求开始========================");
log.info("url====[{}]", request.getRequestURL().toString());
log.info("method=====[{}]", request.getMethod());
log.info("全路径======[{}]以及执行方法====[{}]", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
log.info("ip====[{}]", request.getRemoteAddr());
log.info("入参==[{}]",new ObjectMapper().writeValueAsString(joinPoint.getArgs()));
}
@After("myLog()")
public void doAfter() throws Throwable {
log.info("===================请求结束===============");
}
@Around("myLog()")
public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object proceed = proceedingJoinPoint.proceed();
log.info("输出参数==[{}]",new ObjectMapper().writeValueAsString(proceed));
log.info("执行耗时====》[{}]",System.currentTimeMillis()-startTime);
return proceed;
}
}
package swagger2.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import swagger2.demo.config.my.MyLog;
@RestController
public class tsetx {
@GetMapping("/get")
@MyLog(desc = "请求接口")
public String get() throws InterruptedException {
Thread.sleep(2000);
return "hello";
}
}
