Spring Cloud Gateway with logs

lff l
1 min readMar 10, 2022

When using the Spring Cloud Gateway, I want to show the request/response details in logs. This thread helped a lot:

And the log is enabled by

@Bean
HttpClient httpClient() {
return HttpClient.create().wiretap("LoggingFilter", LogLevel.INFO, AdvancedByteBufFormat.TEXTUAL);
}

However I found an issue for this solution:

As the HttpClient instance is created manually instead of created automatically, the Default Setting will be applied and the httpClient settings in application.yaml will not be applied.

As a result, some important configures such as max-idle-time in application.yml will not be effective.

After some diggings and checking source code, I finally got the solution, list below:

@Component
public class Config {

private static Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

@Autowired
HttpClientProperties properties;

@Autowired
ServerProperties serverProperties;


@Bean
HttpClientFactory httpClientFactory() {
List<HttpClientCustomizer> list = new ArrayList<>();
list.add(httpClient -> {
logger.info("Applying Logging filter to {}", httpClient);
return httpClient.wiretap("LoggingFilter", LogLevel.INFO, AdvancedByteBufFormat.TEXTUAL);
});
HttpClientFactory factory = new HttpClientFactory(properties, serverProperties, list);
return factory;
}
}

The core idea is to init the http client by passing a HttpClientCustomizer, in which the logging is configured.

--

--