Skip to content

Commit

Permalink
adding headers to log
Browse files Browse the repository at this point in the history
  • Loading branch information
minkowp committed May 10, 2019
1 parent 7de8a41 commit 5912b5d
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 16 deletions.
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>pl.piomin</groupId>
<artifactId>spring-boot-logging</artifactId>
<version>1.1.0.RELEASE</version>
<version>1.1-SNAPSHOT</version>

<properties>
<java.version>11</java.version>
Expand Down
50 changes: 35 additions & 15 deletions src/main/java/pl/piomin/logging/filter/SpringLoggingFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.ContentCachingResponseWrapper;
import pl.piomin.logging.util.UniqueIDGenerator;
import pl.piomin.logging.wrapper.SpringRequestWrapper;
import pl.piomin.logging.wrapper.SpringResponseWrapper;
Expand All @@ -15,6 +15,7 @@
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

import static net.logstash.logback.argument.StructuredArguments.value;

Expand All @@ -23,24 +24,43 @@ public class SpringLoggingFilter extends OncePerRequestFilter {
private static final Logger LOGGER = LoggerFactory.getLogger(SpringLoggingFilter.class);
private UniqueIDGenerator generator;

@Value("${spring.logging.ignorePatterns:#{null}}")
Optional<String> ignorePatterns;
@Value("${spring.logging.includeHeaders:false}")
boolean logHeaders;

public SpringLoggingFilter(UniqueIDGenerator generator) {
this.generator = generator;
}

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
generator.generateAndSetMDC(request);
final long startTime = System.currentTimeMillis();
final SpringRequestWrapper wrappedRequest = new SpringRequestWrapper(request);
LOGGER.info("Request: method={}, uri={}, payload={}", wrappedRequest.getMethod(),
wrappedRequest.getRequestURI(), IOUtils.toString(wrappedRequest.getInputStream(),
wrappedRequest.getCharacterEncoding()));
final SpringResponseWrapper wrappedResponse = new SpringResponseWrapper(response);
wrappedResponse.setHeader("X-Request-ID", MDC.get("X-Request-ID"));
wrappedResponse.setHeader("X-Correlation-ID", MDC.get("X-Correlation-ID"));
chain.doFilter(wrappedRequest, wrappedResponse);
final long duration = System.currentTimeMillis() - startTime;
LOGGER.info("Response({} ms): status={}, payload={}", value("X-Response-Time", duration),
value("X-Response-Status", wrappedResponse.getStatus()),
IOUtils.toString(wrappedResponse.getContentAsByteArray(), wrappedResponse.getCharacterEncoding()));
if (ignorePatterns.isPresent() && request.getRequestURI().matches(ignorePatterns.get())) {
chain.doFilter(request, response);
} else {
generator.generateAndSetMDC(request);
final long startTime = System.currentTimeMillis();
final SpringRequestWrapper wrappedRequest = new SpringRequestWrapper(request);
if (logHeaders)
LOGGER.info("Request: method={}, uri={}, payload={}, headers={}", wrappedRequest.getMethod(),
wrappedRequest.getRequestURI(), IOUtils.toString(wrappedRequest.getInputStream(),
wrappedRequest.getCharacterEncoding()), wrappedRequest.getAllHeaders());
else
LOGGER.info("Request: method={}, uri={}, payload={}", wrappedRequest.getMethod(),
wrappedRequest.getRequestURI(), IOUtils.toString(wrappedRequest.getInputStream(),
wrappedRequest.getCharacterEncoding()));
final SpringResponseWrapper wrappedResponse = new SpringResponseWrapper(response);
wrappedResponse.setHeader("X-Request-ID", MDC.get("X-Request-ID"));
wrappedResponse.setHeader("X-Correlation-ID", MDC.get("X-Correlation-ID"));
chain.doFilter(wrappedRequest, wrappedResponse);
final long duration = System.currentTimeMillis() - startTime;
if (logHeaders)
LOGGER.info("Response({} ms): status={}, payload={}, headers={}", value("X-Response-Time", duration),
value("X-Response-Status", wrappedResponse.getStatus()), IOUtils.toString(wrappedResponse.getContentAsByteArray(),
wrappedResponse.getCharacterEncoding()), wrappedResponse.getAllHeaders());
else
LOGGER.info("Response({} ms): status={}, payload={}", value("X-Response-Time", duration),
value("X-Response-Status", wrappedResponse.getStatus()),
IOUtils.toString(wrappedResponse.getContentAsByteArray(), wrappedResponse.getCharacterEncoding()));
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SpringRequestWrapper extends HttpServletRequestWrapper {

Expand Down Expand Up @@ -45,4 +47,10 @@ public int read() throws IOException {
}
};
}

public Map<String, String> getAllHeaders() {
final Map<String, String> headers = new HashMap<>();
getHeaderNames().asIterator().forEachRemaining(it -> headers.put(it, getHeader(it)));
return headers;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
Expand Down Expand Up @@ -65,4 +67,10 @@ public byte[] getContentAsByteArray() {
}
}

public Map<String, String> getAllHeaders() {
final Map<String, String> headers = new HashMap<>();
getHeaderNames().forEach(it -> headers.put(it, getHeader(it)));
return headers;
}

}

0 comments on commit 5912b5d

Please sign in to comment.