Skip to content

Commit 16f12aa

Browse files
author
yuguo.dtpe
committed
feature: add logger interface slf4j
1 parent bfebca0 commit 16f12aa

File tree

6 files changed

+382
-11
lines changed

6 files changed

+382
-11
lines changed

pom.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@
4343
<common-lang-version>2.6</common-lang-version>
4444
<javax.annotation-version>1.3.2</javax.annotation-version>
4545
<javax.validation-version>2.0.1.Final</javax.validation-version>
46+
<org.slf4j.version>1.7.36</org.slf4j.version>
4647
</properties>
4748
<dependencyManagement>
4849
<dependencies>
@@ -91,6 +92,12 @@
9192
<artifactId>validation-api</artifactId>
9293
<version>${javax.validation-version}</version>
9394
</dependency>
95+
<!-- SDK 中提供日志接口 -->
96+
<dependency>
97+
<groupId>org.slf4j</groupId>
98+
<artifactId>slf4j-api</artifactId>
99+
<version>${org.slf4j.version}</version>
100+
</dependency>
94101
</dependencies>
95102
</dependencyManagement>
96103
<profiles>

volcengine-java-sdk-core/pom.xml

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,18 @@
66
<version>0.2.27</version>
77
<relativePath>../pom.xml</relativePath>
88
</parent>
9+
<build>
10+
<plugins>
11+
<plugin>
12+
<groupId>org.apache.maven.plugins</groupId>
13+
<artifactId>maven-compiler-plugin</artifactId>
14+
<configuration>
15+
<source>8</source>
16+
<target>8</target>
17+
</configuration>
18+
</plugin>
19+
</plugins>
20+
</build>
921
<modelVersion>4.0.0</modelVersion>
1022
<artifactId>volcengine-java-sdk-core</artifactId>
1123
<name>volcengine-java-sdk-core</name>
@@ -48,5 +60,10 @@
4860
<artifactId>javax.annotation-api</artifactId>
4961
<scope>compile</scope>
5062
</dependency>
63+
<!-- SDK 中提供日志接口 -->
64+
<dependency>
65+
<groupId>org.slf4j</groupId>
66+
<artifactId>slf4j-api</artifactId>
67+
</dependency>
5168
</dependencies>
5269
</project>

volcengine-java-sdk-core/src/main/java/com/volcengine/ApiClient.java

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@ public ApiClient() {
152152
ConnectionPool connectionPool = new ConnectionPool(maxIdleConns, keepAliveDurationMs);
153153
httpClient = new OkHttpClient();
154154
httpClient.setConnectionPool(connectionPool);
155+
httpClient.interceptors().add(new com.volcengine.interceptor.HttpLoggingInterceptor());
155156
verifyingSsl = true;
156157

157158
json = new JSON();
@@ -464,21 +465,11 @@ public boolean isDebugging() {
464465

465466
/**
466467
* Enable/disable debugging for this API client.
467-
*
468+
* @Deprecated
468469
* @param debugging To enable (true) or disable (false) debugging
469470
* @return ApiClient
470471
*/
471472
public ApiClient setDebugging(boolean debugging) {
472-
if (debugging != this.debugging) {
473-
if (debugging) {
474-
loggingInterceptor = new HttpLoggingInterceptor();
475-
loggingInterceptor.setLevel(Level.BODY);
476-
httpClient.interceptors().add(loggingInterceptor);
477-
} else {
478-
httpClient.interceptors().remove(loggingInterceptor);
479-
loggingInterceptor = null;
480-
}
481-
}
482473
this.debugging = debugging;
483474
return this;
484475
}
Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
package com.volcengine.interceptor;
2+
3+
import com.squareup.okhttp.Connection;
4+
import com.squareup.okhttp.Headers;
5+
import com.squareup.okhttp.Interceptor;
6+
import com.squareup.okhttp.MediaType;
7+
import com.squareup.okhttp.Protocol;
8+
import com.squareup.okhttp.Request;
9+
import com.squareup.okhttp.RequestBody;
10+
import com.squareup.okhttp.Response;
11+
import com.squareup.okhttp.ResponseBody;
12+
import com.squareup.okhttp.internal.http.HttpEngine;
13+
import java.io.IOException;
14+
import java.nio.charset.Charset;
15+
import java.util.concurrent.TimeUnit;
16+
import com.volcengine.utils.LoggerUtil;
17+
import okio.Buffer;
18+
import okio.BufferedSource;
19+
import static com.volcengine.utils.ConstantsUtil.NEW_LINE;
20+
21+
public final class HttpLoggingInterceptor implements Interceptor {
22+
23+
private static final LoggerUtil REQUEST_LOGGER = LoggerUtil.loggerFor("com.volcengine.request");
24+
private static final LoggerUtil REQUEST_ID_LOGGER = LoggerUtil.loggerFor("com.volcengine.request.requestId");
25+
private static final String HEAD_LOG_ID = "X-Tt-Logid";
26+
27+
private static final Charset UTF8 = Charset.forName("UTF-8");
28+
29+
public HttpLoggingInterceptor() {
30+
31+
}
32+
33+
@Override
34+
public Response intercept(Chain chain) throws IOException {
35+
// 打印请求的日志
36+
logRequestLog(chain);
37+
Request request = chain.request();
38+
long startNs = System.nanoTime();
39+
Response response = chain.proceed(request);
40+
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
41+
// 打印响应的日志
42+
logResponseLog(response, tookMs);
43+
return response;
44+
}
45+
46+
private void logResponseLog(Response response, long tookMs) throws IOException {
47+
Headers headers = response.headers();
48+
if (REQUEST_ID_LOGGER.isDebugEnabled()){
49+
String responseState = response.isSuccessful() ? "successful" : "failed";
50+
REQUEST_ID_LOGGER.debug("Received " + responseState + " response: " + response.code() + ", " + "RequestId: " + headers.get(HEAD_LOG_ID));
51+
}
52+
53+
if (REQUEST_LOGGER.isDebugEnabled() || REQUEST_LOGGER.isTraceEnabled()) {
54+
StringBuilder responseInfo = new StringBuilder();
55+
ResponseBody responseBody = response.body();
56+
responseInfo.append(NEW_LINE + "<-- " + protocol(response.protocol()) + ' ' + response.code() + ' '
57+
+ response.message() + " (" + tookMs + "ms"
58+
+ ", " + responseBody.contentLength() + "-byte body" + ')');
59+
60+
for (int i = 0, count = headers.size(); i < count; i++) {
61+
responseInfo.append(NEW_LINE + headers.name(i) + ": " + headers.value(i));
62+
}
63+
64+
if (!REQUEST_LOGGER.isTraceEnabled() || !HttpEngine.hasBody(response)) {
65+
responseInfo.append(NEW_LINE + "<-- END HTTP");
66+
} else if (bodyEncoded(response.headers())) {
67+
responseInfo.append(NEW_LINE + "<-- END HTTP (encoded body omitted)");
68+
} else {
69+
BufferedSource source = responseBody.source();
70+
source.request(Long.MAX_VALUE); // Buffer the entire body.
71+
Buffer buffer = source.buffer();
72+
73+
Charset charset = UTF8;
74+
MediaType contentType = responseBody.contentType();
75+
if (contentType != null) {
76+
charset = contentType.charset(UTF8);
77+
}
78+
79+
if (responseBody.contentLength() != 0) {
80+
responseInfo.append(NEW_LINE + "ResponseBody: ");
81+
responseInfo.append(buffer.clone().readString(charset));
82+
}
83+
84+
responseInfo.append(NEW_LINE + "<-- END HTTP (" + buffer.size() + "-byte body)");
85+
}
86+
REQUEST_LOGGER.debug(responseInfo::toString);
87+
REQUEST_LOGGER.trace(responseInfo::toString);
88+
}
89+
90+
}
91+
92+
private void logRequestLog(Chain chain) throws IOException {
93+
94+
REQUEST_ID_LOGGER.debug(()->{
95+
Request request = chain.request();
96+
Connection connection = chain.connection();
97+
Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
98+
return request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol);
99+
});
100+
101+
if (REQUEST_LOGGER.isDebugEnabled()){
102+
Request request = chain.request();
103+
RequestBody requestBody = request.body();
104+
boolean hasRequestBody = requestBody != null;
105+
Connection connection = chain.connection();
106+
Protocol protocol = connection != null ? connection.getProtocol() : Protocol.HTTP_1_1;
107+
StringBuilder requestLog = new StringBuilder();
108+
requestLog.append("--> " + request.method() + ' ' + request.httpUrl() + ' ' + protocol(protocol));
109+
if (hasRequestBody) {
110+
requestLog.append(" (" + requestBody.contentLength() + "-byte body)");
111+
}
112+
113+
if (hasRequestBody) {
114+
// Request body headers are only present when installed as a network interceptor. Force
115+
// them to be included (when available) so there values are known.
116+
if (requestBody.contentType() != null) {
117+
requestLog.append(NEW_LINE + "Content-Type: " + requestBody.contentType());
118+
}
119+
if (requestBody.contentLength() != -1) {
120+
requestLog.append(NEW_LINE + "Content-Length: " + requestBody.contentLength());
121+
}
122+
}
123+
124+
Headers headers = request.headers();
125+
for (int i = 0, count = headers.size(); i < count; i++) {
126+
String name = headers.name(i);
127+
// Skip headers from the request body as they are explicitly logged above.
128+
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
129+
requestLog.append(NEW_LINE + ": " + headers.value(i));
130+
}
131+
}
132+
133+
if (!hasRequestBody) {
134+
requestLog.append(NEW_LINE + "--> END " + request.method());
135+
} else if (bodyEncoded(request.headers())) {
136+
requestLog.append(NEW_LINE + "--> END " + request.method() + " (encoded body omitted)");
137+
} else {
138+
Buffer buffer = new Buffer();
139+
requestBody.writeTo(buffer);
140+
141+
Charset charset = UTF8;
142+
MediaType contentType = requestBody.contentType();
143+
if (contentType != null) {
144+
contentType.charset(UTF8);
145+
}
146+
147+
requestLog.append("");
148+
requestLog.append(buffer.readString(charset));
149+
150+
requestLog.append("--> END " + request.method()
151+
+ " (" + requestBody.contentLength() + "-byte body)");
152+
}
153+
REQUEST_LOGGER.debug(requestLog.toString());
154+
}
155+
}
156+
157+
private boolean bodyEncoded(Headers headers) {
158+
String contentEncoding = headers.get("Content-Encoding");
159+
return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
160+
}
161+
162+
private static String protocol(Protocol protocol) {
163+
return protocol == Protocol.HTTP_1_0 ? "HTTP/1.0" : "HTTP/1.1";
164+
}
165+
}
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
package com.volcengine.utils;
2+
3+
public class ConstantsUtil {
4+
public static final String NEW_LINE = System.lineSeparator();
5+
6+
}

0 commit comments

Comments
 (0)