springboot自定义日志注解并拦截

在我们的项目中,很多时候我们需要对一些接口和方法进行日志的拦截,方便后续的日志的排查和分析,如果直接使用拦截器来进行拦截,那么需要操作的逻辑就会复杂很多,接口的路径我们需要一个一个的配置,如果不写死在代码中,也需要在数据库中一个一个的配置,这样不仅会影响效率,同时也可能没有考虑周全;为此,想到通过自定义注解来解决这一问题,我们只需要在需要的方法上加上注解,就可以拦截该方法的信息,话不多说,开始:

我们注册自定义拦截器,并继承WebMvcConfigurerAdapter

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 注册自定义的拦截器
 */
@Configuration
@EnableWebMvc
@ComponentScan
public class InterceptorRegister extends WebMvcConfigurerAdapter {

    @Bean
    public LoggerInterceptor loggerInterceptor() {
        return new LoggerInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggerInterceptor());
    }
}

定义日志注解

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LoggerAnnotation {

    String description() default "";

    String module() default "";


}

这里我们定义了两个属性,分别用来记录该方法对应的模块和对应的描述,方便后面数据库持久化查询和问题排查。

通过拦截器的方式实现自定义的日志记录
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;


/**
 * 通过拦截器的方式实现自定义的日志记录
 */
public class LoggerInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(LoggerInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //获取当前方法上的指定注解
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);
        //判断当前注解是否存在
        if (loggerAnnotation != null) {
            loggerAnnotation.description();
            long startTime = System.currentTimeMillis();
            request.setAttribute("startTime", startTime);
            logger.info("进入" + method.getName() + "方法的时间是:" + startTime);
            logger.info("描述为:" + loggerAnnotation.description());
            logger.info("功能模块为:" + loggerAnnotation.module());


        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //获取当前方法上的指定注解
        LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);
        //判断当前注解是否存在
        if (loggerAnnotation != null) {
            long endTime = System.currentTimeMillis();
            long startTime = (Long) request.getAttribute("startTime");
            long periodTime = endTime - startTime;
            logger.info("离开" + method.getName() + "方法的时间是:" + endTime);
            logger.info("在" + method.getName() + "方法的时长是:" + periodTime);
        }
    }
}
//获取当前方法上的指定注解
LoggerAnnotation loggerAnnotation = method.getAnnotation(LoggerAnnotation.class);

获取自定义注解中两个属性的值

logger.info("描述为:" + loggerAnnotation.description());
logger.info("功能模块为:" + loggerAnnotation.module());

控制层需要获取日志的方法上加上这个注解

@LoggerAnnotation(description = "无返回值异步", module = "异步模块")

效果如下:

 

 

备注:这里的自定义注解,本次只是用了方法,所以目前该注解只支持在方法上,有需要的可以根据自己的业务进行改造

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值