@Aspect
@Component
public class WebLogAspect {
Logger logger = LoggerFactory.getLogger(WebLogAspect.class);
@Around(value = "@annotation(org.springframework.web.bind.annotation.RequestMapping) || @annotation(org.springframework.web.bind.annotation.PostMapping)|| @annotation(org.springframework.web.bind.annotation.GetMapping)")
public Object logAroundController(ProceedingJoinPoint point) throws Throwable {
Object result = null;
try {
RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
request.getParameterMap();
//记录请求内容
logger.info("Url:"+request.getRequestURI().toString());
logger.info("HttpMethod:"+request.getMethod());
logger.info("Ip:"+request.getRemoteAddr());
logger.info("RequestParameter:"+ Arrays.toString(point.getArgs()));
logger.info("---------------------------------------------------");
//获取包名+类名 方法名
logger.info(point.getSignature().getDeclaringTypeName()+"."+point.getSignature().getName());
result = point.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return result;
}
}
面试解说:AOP实现日志记录创建一个配置类配置加上Configuration注解和Aspect注解接着配置切入点就是给哪些方法进行添加日志的功能,这里我使用的是环绕通知并且加入切入点RequestMapping或者GetMapping或者PostMapping都添加日志功能,这个意思就是方法上有这个三个注解其中一个都会加上日志功能,接着使用RequestContextHolder获取HttpServletRequset请求这样就可以从该对象获取参数以及ip等参数然后进行保存进日志当中