LogAspect类:
package com.sophomoreblog.blog.Aspect;/*
*@author 侯治聪
*@created 2020/10/3-16:31
*
*/
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.util.Arrays;
@Aspect //日志需要用到的切面
@Component//Spring boot 通过注解这个进行组件扫描
public class LogAspect {
//记录器
private final Logger logger= LoggerFactory.getLogger(this.getClass());
// @Poincut(excution())这个注解以拦截Web下面的类
//execution 可以进行相关的切入的地方
@Pointcut("execution(* com.sophomoreblog.blog.web.*.*(..))")
public void log(){
}
@Before("log()")//表示这个方法会在切面之前执行
//在切面之前做一些记录
public void doBefore(JoinPoint joinPoint){
ServletRequestAttributes attributes= (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=attributes.getRequest();
String url = request.getRequestURL().toString();
String ip = request.getRemoteAddr();
// joinPoint.getSignatrue.getDeclaringTypeName获取 到类名,joinPoint.getSignature().getName()获取到方法的名字
String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
Object[] args=joinPoint.getArgs();//获取请求的相关的参数
RequestLog requestLog=new RequestLog(url,ip,classMethod,args);
logger.info("Request: {}",requestLog);
logger.info("---------doBefore------");
}
@After("log()")
public void doafter(){
logger.info("--------doAfter----------");
}
// 方法返回的结果
@AfterReturning(returning = "result",pointcut = "log()")
public void doAfterReturn(Object result){
logger.info("result:{}",result);
}
private class RequestLog{
private String url;
private String ip;
private String classMethod;
private Object[] args;
public RequestLog(String url, String ip, String classMethod, Object[] args) {
this.url = url;
this.ip = ip;
this.classMethod = classMethod;
this.args = args;
}
@Override
public String toString() {
return "RequestLog{" +
"url='" + url + '\'' +
", ip='" + ip + '\'' +
", classMethod='" + classMethod + '\'' +
", args=" + Arrays.toString(args) +
'}';
}
}
public LogAspect() {
}
}