2

JDK11 introduced a new HTTP Client, with many features that lacks in traditional java.net.HttpURLConnection class. First question that I encountered with is how to properly enable logging in newly added HTTP Client?

Krzysztof Krasoń
  • 26,515
  • 16
  • 89
  • 115
Maxim Kirilov
  • 2,639
  • 24
  • 49
  • See https://stackoverflow.com/questions/53215038/how-to-log-request-response-using-java-net-http-httpclient/53231046#53231046 – daniel Feb 18 '19 at 14:49

1 Answers1

6

The client uses java.util.logging, the easiest way is to use SLF4J. See JUL to SLF4J Bridge for more information.

3 steps are required:

  1. Add jul-to-slf4j bridge to you classpath with runtime scope.
    Maven:

    <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>jul-to-slf4j</artifactId>
       <version>1.7.25</version>
       <scope>runtime</scope>
    </dependency>
    

Gradle:

`runtime group: 'org.slf4j', name: 'jul-to-slf4j', version: '1.7.25'`
  1. Add in logback.xml (logback-test.xml), don't forget to add a STDOUT appender (or change it accordingly)

    <contextListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
        <resetJUL>true</resetJUL>
    </contextListener>
    
    <logger name="jdk.internal.httpclient.debug" level="debug" additivity="false">
        <appender-ref ref="STDOUT" />
    </logger>
    
    <root level="DEBUG">
        <appender-ref ref="STDOUT"/>
    </root>
    
  2. Add in your code:

     static {
     SLF4JBridgeHandler.removeHandlersForRootLogger();
     SLF4JBridgeHandler.install();
     }
    

Alternatively, for educational purposes it is possible to add a system property:
-Djdk.httpclient.HttpClient.log=all which will enable all logging printing to the console.

simon04
  • 3,054
  • 29
  • 25
Maxim Kirilov
  • 2,639
  • 24
  • 49
  • thank you this worked for me, after following ALL steps :) – Mobigital Nov 13 '20 at 20:05
  • Thanks @Maxim for this answer. However, this does log a lot of information. Is there a way to log only httpclient.wire.content.wire logs using this approach? – Sooraj Apr 20 '22 at 10:23