Skip to content

Commit

Permalink
Log network and unexpected exceptions if logging is enabled.
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeWharton committed Jul 17, 2013
1 parent b54de2e commit ba551e6
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions retrofit/src/main/java/retrofit/RestAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
package retrofit;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
Expand Down Expand Up @@ -121,7 +123,11 @@ public enum LogLevel {
/** Log the basic information along with request and response headers. */
HEADERS,
/** Log the headers, body, and metadata for both requests and responses. */
FULL
FULL;

public boolean log() {
return this != NONE;
}
}

private final Server server;
Expand Down Expand Up @@ -247,7 +253,7 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) {
Thread.currentThread().setName(THREAD_PREFIX + url.substring(serverUrl.length()));
}

if (logLevel.ordinal() > LogLevel.NONE.ordinal()) {
if (logLevel.log()) {
// Log the request data.
request = logAndReplaceRequest(request);
}
Expand All @@ -268,7 +274,7 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) {
profiler.afterCall(requestInfo, elapsedTime, statusCode, profilerObject);
}

if (logLevel.ordinal() > LogLevel.NONE.ordinal()) {
if (logLevel.log()) {
// Log the response data.
response = logAndReplaceResponse(url, response, elapsedTime);
}
Expand Down Expand Up @@ -310,8 +316,14 @@ private Object invokeRequest(RestMethodInfo methodDetails, Object[] args) {
} catch (RetrofitError e) {
throw e; // Pass through our own errors.
} catch (IOException e) {
if (logLevel.log()) {
logException(e, url);
}
throw RetrofitError.networkError(url, e);
} catch (Throwable t) {
if (logLevel.log()) {
logException(t, url);
}
throw RetrofitError.unexpectedError(url, t);
} finally {
if (!methodDetails.isSynchronous) {
Expand Down Expand Up @@ -414,6 +426,15 @@ private Response logAndReplaceResponse(String url, Response response, long elaps
return response;
}

/** Log an exception that occurred during the processing of a request or response. */
private void logException(Throwable t, String url) {
log.log(String.format("---- ERROR %s", url));
StringWriter sw = new StringWriter();
t.printStackTrace(new PrintWriter(sw));
log.log(sw.toString());
log.log("---- END ERROR");
}

private static Profiler.RequestInformation getRequestInfo(String serverUrl,
RestMethodInfo methodDetails, Request request) {
long contentLength = 0;
Expand Down

0 comments on commit ba551e6

Please sign in to comment.