Complete Request and Response Body Logging in Retrofit-Android

Dec 02, 2025 · Programming · 9 views · 7.8

Keywords: Retrofit | Android | Logging | Network Requests | OkHttp

Abstract: This paper comprehensively examines techniques for logging complete request and response bodies in Retrofit-Android. By analyzing different logging mechanisms in Retrofit 1.x and 2.x versions, it focuses on the classic approach using setLogLevel(LogLevel.FULL) and setLog(new AndroidLog("YOUR_LOG_TAG")), supplemented by HttpLoggingInterceptor implementation based on OkHttp in Retrofit 2.x. Starting from practical development needs, the article provides complete code examples and configuration instructions to help developers achieve effective network request debugging and monitoring across different Retrofit versions.

Technical Evolution of Retrofit Logging

In the realm of Android network programming, Retrofit, as a type-safe HTTP client library developed by Square, has gained widespread popularity due to its clean API design and powerful functionality. However, in practical development, developers frequently face challenges in effectively logging network request and response bodies. Particularly when debugging complex API interactions, the ability to view complete request and response data is crucial for problem diagnosis.

Logging Mechanism in Retrofit 1.x

In Retrofit 1.x versions, the library provided built-in logging functionality. Developers could configure log levels and log output through RestAdapter.Builder. The core methods include:

RestAdapter adapter = new RestAdapter.Builder()
    .setEndpoint(baseUrl)
    .setLogLevel(LogLevel.FULL)
    .setLog(new RestAdapter.Log() {
        @Override
        public void log(String msg) {
            Log.i(TAG, msg);
        }
    })
    .build();

The LogLevel.FULL parameter ensures recording of complete request and response information, including request headers, request body, response headers, and response body. This method is straightforward but requires attention to version compatibility issues in practice. As mentioned in the Q&A data, some older versions might have incomplete logging functionality.

Architectural Changes in Retrofit 2.x

Retrofit 2.0 underwent significant architectural refactoring, with one of the major changes being the removal of built-in logging functionality. This decision was based on Jake Wharton's explanation: in Retrofit 1.x, the logged content represented "assumed values" that couldn't be guaranteed to exactly match the data actually sent to the server. The request body might be modified during transmission, causing discrepancies between log information and actual conditions.

Modern Solutions Based on OkHttp

Retrofit 2.x completely relies on OkHttp for network operations, therefore logging must be implemented through OkHttp's interceptor mechanism. OkHttp 2.6.0 and later versions provide specialized logging interceptors:

dependencies {
    implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
}

Example code for configuring HttpLoggingInterceptor:

HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);

OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
httpClient.addInterceptor(logging);

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(API_BASE_URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(httpClient.build())
    .build();

Fine-grained Control of Log Levels

HttpLoggingInterceptor provides four log levels to meet different scenario requirements:

In development environments, Level.BODY is recommended for the most detailed debugging information; in production environments, switching to Level.NONE or Level.BASIC is advised to avoid performance overhead and sensitive information leakage.

Best Practices and Considerations

1. Interceptor Order: The logging interceptor should be added as the last interceptor, ensuring it records all modifications made to the request by preceding interceptors.

2. Conditional Compilation: It's recommended to enable detailed logging only in debug builds:

if (BuildConfig.DEBUG) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    builder.addInterceptor(interceptor);
}

3. Performance Considerations: Logging large amounts of data may impact application performance, particularly in scenarios with frequent network requests. Appropriate log levels should be selected.

4. Security: Avoid logging request and response bodies containing sensitive information (such as authentication tokens, personal data) in production environments.

Advanced Customization Solutions

For situations requiring more complex log processing, developers can create custom OkHttp interceptors. For example, the UnauthorisedInterceptor mentioned in the Q&A data demonstrates how to trigger specific events based on HTTP status codes (such as 401 Unauthorized):

public class CustomLoggingInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        long startTime = System.nanoTime();
        
        // Log request information
        Log.d("Network", String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));
        
        Response response = chain.proceed(request);
        
        long endTime = System.nanoTime();
        Log.d("Network", String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (endTime - startTime) / 1e6d, response.headers()));
        
        return response;
    }
}

Version Compatibility Strategy

Considering different projects may use different Retrofit versions, the following compatibility strategy is recommended:

// Detect Retrofit version and select appropriate logging method
if (isRetrofit1x()) {
    // Use RestAdapter's setLogLevel method
} else {
    // Use OkHttp's HttpLoggingInterceptor
}

This strategy ensures code works correctly across different Retrofit versions while fully utilizing the best features of each version.

Conclusion

Retrofit's logging mechanism has evolved from built-in functionality to OkHttp interceptor-based implementation. For Retrofit 1.x, setLogLevel(LogLevel.FULL) combined with custom Log implementation is the most direct solution; for Retrofit 2.x, implementation through HttpLoggingInterceptor is required. Regardless of the method used, the key is selecting appropriate log levels based on actual requirements while balancing performance and security considerations. Through reasonable logging strategies, developers can significantly improve the efficiency and accuracy of network request debugging.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.