markhobson / spring-rest-template-logger

Spring RestTemplate customizer to log HTTP traffic.
Apache License 2.0
25 stars 10 forks source link

Support customisation of logged payload #6

Closed hdpe closed 6 years ago

hdpe commented 6 years ago

As discussed, it would be good to be able to customise the formatting of the request/response body before logging.

My particular use case is the need to obfuscate passwords sent in the request before writing to the log.

As a very first stab at this, how about allowing the LoggingInterceptor to be constructed with a LoggingFormatter, something like:

public interface LoggingFormatter {

    String formatRequest(HttpRequest request, byte[] body);

    String formatResponse(ClientHttpResponse response);
}

with a default implementation:

public class DefaultLoggingFormatter implements LoggingFormatter {

    @Override
    public String formatRequest(HttpRequest request, byte[] body) {
        // tmpl method to generate log line from URL, method, body...
    }

    @Override
    public String formatResponse(ClientHttpResponse response) {
        // tmpl method to generate log line from response status, body...
    }

    protected String formatBody(byte[] body, Charset charset) {
        return new String(body, charset);
    }

    protected Charset getCharset(HttpMessage message)
    {
        // ...
    }
}

This would support resolution of e.g. #2 as well. Then perhaps #1 via introducing something like a supports(MediaType) method to the formatter?

What do you think? Happy to prepare a PR following your feedback.

markhobson commented 6 years ago

I like it a lot! It certainly provides a good place to address the other issues as you say. Thanks Ryan :+1:

P.S. A pedant would say LogFormatter as it's not actually doing the logging.

markhobson commented 6 years ago

Thanks for the PR!

jmart1 commented 6 years ago

Do you know when this version will be published to Maven Central?

markhobson commented 6 years ago

@jmart1 I've just released 2.0.0, so it should be there shortly. Thanks for the reminder!

jmart1 commented 6 years ago

Yup its there. Thank you!!!