我有一个带有多个初始化程序的Spring web-mvc REST服务。
WebAppInitializer.java
@Order(1)
public class MyFiltersInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) {
FilterRegistration.Dynamic registration = servletContext.addFilter("myRequestFilter", DelegatingFilterProxy.class);
// register other filters and DispatcherServlet
}
}
SecurityWebAppInitializer.java
@Order(2)
public class MySecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer {
@Override
protected Set<SessionTrackingMode> getSessionTrackingModes() {
return EnumSet.of(SessionTrackingMode.COOKIE, SessionTrackingMode.URL);
}
}
如您所见,在所有自定义请求过滤器之后都添加了SecurityFilterChain
。我需要做的是记录每个请求,如果请求被授权,则包括User
记录
类似MyRequestFilter.java
:
@Slf4j
public class RequestFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(final HttpServletRequest request,
final HttpServletResponse response,
final FilterChain filterChain) throws ServletException, IOException {
MyUser user = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); //no auth yet
log.debug("request {} start, user {}", request, user);
filterChain.doFilter(request, response); //may return 401 or 403, what also need to be logged
log.debug("request {} end with response {}", request, response);
}
有一个想法,添加一个LogBodyHolder
,它会保留日志正文,直到完全传递SecurityChain
,然后调用log.debug
。但是有什么漂亮方法可以解决这个问题?
答案 0 :(得分:0)
您可以只创建一个Spring Bean,该Spring Bean扩展Spring提供的类AbstractRequestLoggingFilter
,然后覆盖beforeRequest()
和afterRequest()
方法以根据需要添加日志。