zalando/logbook

Support for JSON body pretty-printing

hurr1canexd opened this issue · 0 comments

How to pretty-print JSON with different BodyFilters?

Detailed Description

Using Logbook version 2.14.0 I configured BodyFIlter like this:

@Bean
public BodyFilter bodyFilter() {
    return merge(new PrettyPrintingJsonBodyFilter(), replaceJsonStringProperty(Set.of("number"), "XXX"));
}

After I upgraded Logbook version to 3.9.0 I noticed that there is JacksonJsonFieldBodyFilter bean in LogbookAutoConfiguration class. It works after PrettyPrintingJsonBodyFilter and compresses json. I tried various ways to create BodyFilters bean, but don't find good one.

Context

I didn't find in the documentation how to achieve pretty printing of JSON using Logbook. It would be very useful for our cozy community.

Possible Implementation

The only but bad solution I found is just copy JacksonJsonFieldBodyFilter bean from LogbookAutoConfiguration class to my Logbook @Configuration class before PrettyPrintingJsonBodyFilter bean. So PrettyPrintingJsonBodyFilter injects into the Logbook constructor at the end of bodyFIlters list and works at the end of the BodyFilter chain.

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.zalando.logbook.BodyFilter;
import org.zalando.logbook.HttpLogWriter;
import org.zalando.logbook.autoconfigure.LogbookProperties;
import org.zalando.logbook.json.JacksonJsonFieldBodyFilter;
import org.zalando.logbook.json.PrettyPrintingJsonBodyFilter;

import java.util.List;

@Configuration
public class LogbookConfig {

    @Bean
    public HttpLogWriter writer(CustomLogbookLoggerProperties properties) {
        return new CustomHttpLogWriter(properties);
    }

    /**
     * It's just a copied implementation of {@link org.zalando.logbook.autoconfigure.LogbookAutoConfiguration#jsonBodyFieldsFilter()}.
     * We need it only to inject JacksonJsonFieldBodyFilter in List<BodyFilter> bodyFilters to
     * {@link org.zalando.logbook.autoconfigure.LogbookAutoConfiguration#logbook} before
     * {@link PrettyPrintingJsonBodyFilter}. So PrettyPrintingJsonBodyFilter works at the end of the filter chain
     */
    @Bean
    public JacksonJsonFieldBodyFilter jsonBodyFieldsFilter(LogbookProperties properties) {
        final LogbookProperties.Obfuscate obfuscate = properties.getObfuscate();
        final List<String> jsonBodyFields = obfuscate.getJsonBodyFields();

        return new JacksonJsonFieldBodyFilter(jsonBodyFields, obfuscate.getReplacement());
    }

    @Bean
    public BodyFilter prettyPrintingJsonBodyFilter() {
        return new PrettyPrintingJsonBodyFilter();
    }
}

Your Environment

Thanks in advance