Skip to content Skip to sidebar Skip to footer

Httplogginginterceptor For Http Request & Response Logging

I'm using retrofit2 and I need to log all request and response. Request and response works perfectly, All I need is to log those request/response, I tried almost every solution, wh

Solution 1:

Try to use the OkHttpClient as follows:

private OkHttpClient createDefaultOkHttpClient() {
  HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
  interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
  returnnew OkHttpClient().newBuilder()
          .addInterceptor(interceptor)
          .build();
}

Then just set this to your retrofit builder:

RetrofitretrofitAsync=newRetrofit.Builder()
            .baseUrl(BASE_URL_APPS)
            .client(createDefaultOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(rxAdapter)
            .build();

Solution 2:

Make API call like this.

ApiFactory.java

publicclassApiFactory {

/**
 * Base URL for API calls
 */privatestatic final String BASE_URL = "";

publicApiFactory() {
}

privatestatic Retrofit provideRestAdapter() {

    returnnew Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(BaseApplication.getInstance().getOkHttpClient())
            .addConverterFactory(GsonConverterFactory.create())
            .addConverterFactory(ScalarsConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
}

publicstatic <S> S createService(Class<S> serviceClass) {
    return provideRestAdapter().create(serviceClass);
}

}

LoginService Interface

publicinterfaceLoginService {

/**
 * To Post FormUrlEncoded to web service
 *
 * @return Call Object of Type JsonObject
 */@FormUrlEncoded@POST("api/login")
Call<JsonObject> login(@Field("email") String email,
                       @Field("password") String password,
                       @Field("devicetype") String devicetype,
                       @Field("deviceid") String deviceid);

}

Make API call here

privatevoidemailLoginRequest() {
    LoginService loginService = ApiFactory.createService(LoginService.class);
    Call<JsonObject> call = loginService.login(edtEmail.getText().toString(),edtPassword.getText().toString(),mDeviceType,mDeviceToken);
    call.enqueue(new Callback<JsonObject>() {
        @Override
        publicvoidonResponse(Call<JsonObject> call, Response<JsonObject> response) {
            hideProgressDialog();
            if (response.isSuccessful()) {
                LOGD(TAG, "onResponse 0: " + response.body().toString());
                LoginResponse loginResponse = new Gson().fromJson(response.body().toString(), LoginResponse.class);

                System.out.println("+++ get message >> " + loginResponse.getMessage());
                int status = loginResponse.getStatus();

            }else {
                LOGD(TAG, "response fail 0: " + response.body());
            }
        }

        @Override
        publicvoidonFailure(Call<JsonObject> call, Throwable t) {
            hideProgressDialog();
            LOGD(TAG, "onFailure: " + t.getMessage());
        }
    });
}

LoginResponse Make changes as per yours.

publicclassLoginResponse {

@SerializedName("status")
@ExposeprivateInteger status;
@SerializedName("message")
@ExposeprivateString message;
@SerializedName("data")
@ExposeprivateData data;

/**
 * No args constructor for use in serialization
 *
 */publicLoginResponse() {

Sample response model
            //        {//            "status": 1,//                "data": {//            "user_id": "565464564",//                    "email": "email@email.com",//                    "fullname": "james",//                    "username": "james123",//                    "country": "54654654",//                    "city": "56546465546",//                    "token": "dfgdfgdfg545465465464564"//        },//            "message": "Login successfull"//        }
}

/**
 *
 * @parammessage
 * @paramstatus
 * @paramdata
 */publicLoginResponse(Integer status, String message, Data data) {
    this.status = status;
    this.message = message;
    this.data = data;
}

/**
 *
 * @return
 * The status
 */publicIntegergetStatus() {
    return status;
}

/**
 *
 * @paramstatus
 * The status
 */publicvoidsetStatus(Integer status) {
    this.status = status;
}

/**
 *
 * @return
 * The message
 */publicStringgetMessage() {
    return message;
}

/**
 *
 * @parammessage
 * The message
 */publicvoidsetMessage(String message) {
    this.message = message;
}

/**
 * @return The data
 */publicDatagetData() {
    return data;
}

/**
 * @param data The data
 */publicvoidsetData(Data data) {
    this.data = data;
}

publicclassData {

    @SerializedName("user_id")
    @ExposeprivateString userId;

    @SerializedName("email")
    @ExposeprivateString email;

    /**
     * No args constructor for use in serialization
     */publicData() {
    }

    /**
     * @paramemail
     * @paramuserId
     */publicData(String userId, String email) {
        this.userId = userId;
        this.email = email;
    }

    /**
     * @return The userId
     */publicStringgetUserId() {
        return userId;
    }

    /**
     * @param userId The user_id
     */publicvoidsetUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return The email
     */publicStringgetEmail() {
        return email;
    }

    /**
     * @param email The email
     */publicvoidsetEmail(String email) {
        this.email = email;
    }

}
}

Enjoy!

Solution 3:

I it would be better to add interceptors while creating client using Builder as below code. If you notice we add two interceptors - Network interceptor > addNetworkInterceptor - Interceptor > addInterceptor

The main difference is network interceptor only works when there is a real request (not loading from caching). Interceptor log data on both cases loading from network or cache.

Also make sure you are imorting the correct BuildConfig (sometimes autocompletion import it from one of your libraries, then it will be always false)

`OkHttpClient.BuilderclientBuilder=newOkHttpClient.Builder();
if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor.LoggernetworkLayerLogger=newHttpLoggingInterceptor.Logger() {
                @Overridepublicvoidlog(String message) {
                    LogUtils.d("NetworkLayer", message);
                }
            };

            HttpLoggingInterceptor.LoggerappLayerLogger=newHttpLoggingInterceptor.Logger() {
            @Overridepublicvoidlog(String message) {
                LogUtils.d("ApplicationLayer", message);
            }
        };
        HttpLoggingInterceptornetworkLogging=newHttpLoggingInterceptor(networkLayerLogger);
        HttpLoggingInterceptorappLogging=newHttpLoggingInterceptor(appLayerLogger);

        networkLogging.setLevel(HttpLoggingInterceptor.Level.HEADERS);
        appLogging.setLevel(HttpLoggingInterceptor.Level.BODY);

        clientBuilder.addNetworkInterceptor(networkLogging);
        clientBuilder.addInterceptor(appLogging);
    }

`

Post a Comment for "Httplogginginterceptor For Http Request & Response Logging"