Skip to content

Instantly share code, notes, and snippets.

@xiaoshuai
Last active November 16, 2018 16:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiaoshuai/44b3359ce5723add1e41e2f2d9dfc884 to your computer and use it in GitHub Desktop.
Save xiaoshuai/44b3359ce5723add1e41e2f2d9dfc884 to your computer and use it in GitHub Desktop.
my slf4j via okhttp3.Interceptor
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
public class OkHttpChronos implements Interceptor {
private static Logger logger = LoggerFactory.getLogger(OkHttpChronos.class);
private Long costTime = 0L;
private Long startTime = 0L;
private Long endTime = 0L;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
String pathSegmentsToString = "";
if (pathSegmentsToString != null) {
try {
List<String> pathSegments = request.url().pathSegments();
StringBuilder accum = new StringBuilder();
for (int i = 0, size = pathSegments.size(); i < size; i++) {
accum.append('/');
accum.append(pathSegments.get(i));
}
pathSegmentsToString = accum.toString();
} catch (Exception exception) {
// do nth
}
}
Response response = null;
try {
startTime = System.currentTimeMillis();
response = chain.proceed(request);
endTime = System.currentTimeMillis();
costTime = endTime - startTime;
logger.info("[Chronos] OkHttp pathSegmentsToString={} startTime={} costTime={}ms.", pathSegmentsToString,
startTime, costTime);
Long seconds = costTime / 1000;
if (seconds > 12) {
logger.error("[Chronos] OkHttp costTime>12s pathSegmentsToString={} startTime={}.",
pathSegmentsToString, startTime);
} else if (seconds > 6) {
logger.error("[Chronos] OkHttp costTime>06s pathSegmentsToString={} startTime={}.",
pathSegmentsToString, startTime);
}
if (!response.isSuccessful()) {
logger.error("[Chronos] OkHttp httperror pathSegmentsToString={} startTime={}.",
pathSegmentsToString, startTime);
}
} catch (IOException e) {
logger.error("[Chronos] OkHttp httperror pathSegmentsToString={} startTime={}.",
pathSegmentsToString, startTime);
throw e;
}
return response;
}
}
@xiaoshuai
Copy link
Author

only focus on 6/12s consumption

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment