Sping记录Http请求log

有时候我们要记录下所有的http请求信息(请求的方法,比如GET;请求的uri,比如/api/v1/users等信息),在spring框架下,很容易实现这个需求。

在spring框架下,用户可以自定义web请求处理前后的拦截器,其中HandlerInterceptor接口是我们可以利用的。这个接口定义了3个函数:我们只需要实现这3个接口,就可以拦截到所有的web请求信息。

具体做法:

  1. 编写HandlerInterceptor实现类,重写其中的方法,这里重写了方法postHandle,这个调用是在web请求成功处理后被调用。
public class PlatformRequestInterceptor implements HandlerInterceptor {
    @Autowired
    private PlatformAccessLogRepository repository;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //这里没有直接读取request对象,而是通过`ContentCachingRequestWrapper`类先进行一次缓存,原因参考参考文档[1]
        HttpServletRequest requestCacheWrapperObject
                = new ContentCachingRequestWrapper(request);
        requestCacheWrapperObject.getParameterMap();

        String uri = requestCacheWrapperObject.getRequestURI();
        if (!uri.equals("/error")) {
            String method = requestCacheWrapperObject.getMethod();
            String userName = "guest";
            if (requestCacheWrapperObject.getUserPrincipal() != null) {
                userName = requestCacheWrapperObject.getUserPrincipal().getName();
            }
            String remoteAddr = requestCacheWrapperObject.getRemoteAddr();
            PlatformAccessLog accessLog = new PlatformAccessLog();
            accessLog.setMethod(method);
            accessLog.setName(userName);
            accessLog.setPath(uri);
            accessLog.setTime(new Date());
            accessLog.setRemoteAddr(remoteAddr);
            repository.insert(accessLog);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }
}
  1. 注册上面写好的拦截器实现,重载WebMvcConfigurerAdapteraddInterceptors方法。
@Configuration
public class PlatformMVCConfig extends WebMvcConfigurerAdapter {
    @Autowired
    private HandlerInterceptor interceptor;

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

经过上面的操作,就可以把所有正常处理的http请求记录到mongodb中了。写入数据库的代码略。

参考文档

  1. Spring – Log Incoming Requests
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,273评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,005评论 6 342
  • spring官方文档:http://docs.spring.io/spring/docs/current/spri...
    牛马风情阅读 1,781评论 0 3
  • 大敌当前,我经常因为心悸而早上醒来~是件好事~问题是,当房友只需要很少时间温习都比我强~我发觉我的脑袋好想爆!而我...
    tonyoppa阅读 201评论 0 0
  • 今天宝贝给了我一个意外惊喜,我在画画,他自己去找来三角尺和量角器,我以为他要乱画,因为他没有用过,甚至都不知道这两...
    辣妈赵十八阅读 507评论 2 2