Introduction

Java’s java.net.http.HttpClient (introduced in Java 11) provides a modern and standardized way to perform HTTP requests. Enabling detailed logging for this client offers invaluable insights when troubleshooting network issues, analyzing request/response behavior, and optimizing application performance.

To enable the log, add this JVM option -Djdk.httpclient.HttpClient.log=errors,requests when staring your application.

Code example

I use this library as a client to call OpenAI API, the library uses httpclient for making http request.

HttpClient httpClient = HttpClient.newBuilder()
    .connectTimeout(Duration.ofSeconds(20))
    .executor(Executors.newFixedThreadPool(3))
    .build();
OpenAI openAI = OpenAI.newBuilder(System.getenv("OPENAI_API_KEY"))
    .httpClient(httpClient)
    .build();

ChatClient chatClient = openAI.chatClient();
CreateChatCompletionRequest request = CreateChatCompletionRequest.newBuilder()
    .model(OpenAIModel.GPT_3_5_TURBO)
    .message(ChatMessage.userMessage("Who won the world series in 2020?"))
    .build();
CompletableFuture<ChatCompletion> chatCompletion = chatClient.createChatCompletionAsync(request);
chatCompletion.thenAccept(System.out::println);

Now, check the log. You can see the output as bellow.

2024-05-06 14:55:18.048  INFO  [task-1] jdk.httpclient.HttpClient                : REQUEST: https://api.openai.com/v1/chat/completions POST
2024-05-06 14:55:19.222  INFO  [task-2] jdk.httpclient.HttpClient                : RESPONSE: (POST https://api.openai.com/v1/chat/completions) 200 HTTP_2 Local port:  53495