An OkHttp interceptor which logs HTTP request and response data to an slf4j logger.
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new HttpLoggingInterceptor())
.build();
You can change the log level at any time on your corresponding logging configuration. For example, in log4j you'll use:
log4j.logger.okhttp3.logging.wire=DEBUG
The interceptor logs based from the following rules:
DEBUG
- request and response lines and their respective headers and bodiesINFO
- request and response lines and their respective headersERROR
/WARN
- none
To log to a custom location, pass a Logger
instance to the constructor.
private static final Logger yourLogger = LoggerFactory.getLogger( YourClass.class );
...
HttpLoggingInterceptor logging = new HttpLoggingInterceptor( yourLogger );
Don't forget to update your logging properties as well!
Warning: The logs generated by this interceptor when using the DEBUG
or INFO
levels has the potential to leak sensitive information such as "Authorization" or "Cookie" headers and the contents of request and response bodies. This data should only be logged in a controlled way or in a non-production environment.
At DEBUG
level, the interceptor by default loads the entire response body prior logging. This ensures that the ResponseBody
is kept readable after the interceptor is finished. On cases where the expected content is huge, you can limit the size through one of it's constructor arguments:
new HttpLoggingInterceptor( yourLogger, 4096L );
Get via Maven:
<dependencies>
<dependency>
<groupId>com.github.devcsrj</groupId>
<artifactId>slf4j-okhttp3-logging-interceptor</artifactId>
<version>1.0.1</version>
</dependency>
...
</dependencies>
or via Gradle
dependencies {
compile 'com.github.devcsrj:slf4j-okhttp3-logging-interceptor:1.0.1'
}