pom.xml
<!--aspect注解-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
</dependency>
<!--aspect注解-->
自定义注解
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 自定义日志注解 -- 使用在方法上
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomLogAnnotation {
}
切面
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
/**
* 自定义日志
*/
@Component
@Aspect
@Slf4j
public class LogAnnotationAspect {
@Pointcut("@annotation(com.example.goodscrawlerservice.annotation.CustomLogAnnotation)")
public void logAspect() {
}
@Before("logAspect()")
public void beforeLog(JoinPoint point) {
ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = requestAttributes.getRequest();
String methodName = point.getSignature().getName();
log.info("===============Method: " + methodName + "() begin===============");
//执行时间
LocalDateTime now = LocalDateTime.now();
log.info("===============Time: " + now + " ===============");
//请求URL
log.info("===============URL: " + request.getRequestURL() + " ===============");
//请求方式
log.info("===============Request Method: " + request.getMethod() + " ===============");
//controller 的请求全路径以及执行方法
log.info("===============Class Method: " + point.getSignature().getDeclaringTypeName() + "." + methodName);
//请求 IP
log.info("===============IP : " + request.getRemoteHost() + " ===============");
//请求参数
log.info("Request Args : " + JSON.toJSONString(point.getArgs()) + " ===============");
}
@After("logAspect()")
public void afterLog(JoinPoint point) {
String methodName = point.getSignature().getName();
log.info("===============Method: " + methodName + "() end===============");
}
}
控制层方法使用