I'm using Spring MVC ** I want to log the request URL and request parameters! ** ** That often happened, and each time I created a dedicated filter class,
Wouldn't it be happy if I left it in the article for myself?
I thought and described it. It's a completely personal note.
Java 8 (also works with 11)
Spring Boot 2.2.1
Spring MVC (version uses Boot rules)
Lombok (version uses Boot rules)
I have not tried it with Spring Web Flux.
package com.example.demo.filter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.Map;
@Slf4j
@Component
public class LoggingFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = ((HttpServletRequest)request);
String uri = httpReq.getRequestURI();
long start = System.currentTimeMillis();
log.info(String.format("Start processing. URI: %s", uri));
//Process the request parameter and output it as a one-line log
Map<String, String[]> params = httpReq.getParameterMap();
StringBuilder strParams = new StringBuilder("Request parameters: [");
boolean isFirstParam = true;
for (Map.Entry<String, String[]> param : params.entrySet()) {
if (isFirstParam) {
isFirstParam = false;
} else {
//Comma is added as a concatenator for the second and subsequent request parameters.
strParams.append(", ");
}
strParams.append(param.getKey()).append("=").append(Arrays.toString(param.getValue()));
}
strParams.append("]");
log.info(strParams.toString());
//Implementation of each process
chain.doFilter(request, response);
int status = ((HttpServletResponse) response).getStatus();
log.info(String.format("Processing Exit.Time required%d millis. STATUS=%d", System.currentTimeMillis() - start, status));
}
@Override
public void destroy() {
}
}
2019-11-14 11:54:40.297 INFO 2001 --- [nio-8080-exec-1] com.example.demo.filter.LoggingFilter :Start processing. URI: /demo/hello
2019-11-14 11:54:40.298 INFO 2001 --- [nio-8080-exec-1] com.example.demo.filter.LoggingFilter :Request parameters: [hoge=[1], fuga=[2]]
2019-11-14 11:54:40.327 INFO 2001 --- [nio-8080-exec-1] com.example.demo.filter.LoggingFilter :Processing Exit.Time required 30 millis. STATUS=200
The log format remains the Spring Boot standard. Personally, the log output is written in Japanese because it is easy to understand in Japanese. Sometimes I think it's better to do this a little more, but I often write in this style. It's not surprising that the extended For statement is a bit disgusting, but it's annoying and hasn't been revised.
Note that this Filter supports array parameters, but does not support attachments.
Recommended Posts