前言
本文提供了一种记录接口访问日志的方法。大家可以自定义拓展记录信息
一、定义一个记录日志的注解
注解的作用可以粗略理解为标记注解的时候记录信息,在未来某个时候把注解上的信息取出来用
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
//忽略代码格式校验 抑制所有的警告
@SuppressWarnings("all")
//该注解用于【方法】
@Target(ElementType.METHOD)
//保留策略 相当于全过程保留
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggerInfo {
// 用来记录方法注释
String name();
// 用来记录方法类型
String type();
// 如果还有要加的大家自定义
// ...
}
二、定义拦截器
拦截器这里主要用到的是preHandle,在方法执行前取出Controlle访问的相关信息并进行记录
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Slf4j
public class LoggerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
if (handlerMethod.hasMethodAnnotation(LoggerInfo.class)) {
LoggerInfo annotation = handlerMethod.getMethod().getAnnotation(LoggerInfo.class);
log.error("接口地址:"+request.getRequestURI()+"。方法介绍:"+annotation.name()+"。方法类型:"+annotation.type());
// 大家在这里可以记录更多的信息,可以存到数据库中形成接口访问记录,登录日志其实同理,就是只针对登录接口进行拦截
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
三、把拦截器添加到容器中
别忘了加@Configuration
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class LoggerConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器 addPathPatterns 是拦截接口的地址 excludePathPatterns 是放行接口的地址
registry.addInterceptor(new LoggerInterceptor())
.addPathPatterns("/**")
.excludePathPatterns("/test");
}
}
四、在Controller的方法上添加@LoggerInfo的注解
在注解上加解释、类型等等
五、测试访问接口
总结
今天正好学到注解和拦截器,问ai说这种形式是比较常用的记录日志的方法,所以记录了一下,对大家有用的留个小手。