AndroidNetworking lib not logging anything

Viewed 629

I'm trying to reach an API with AndroidNetworking lib.

Here is how I initalized it:

public class TestLabApp extends Application {

@Override
public void onCreate() {
    super.onCreate();


    //For logging
    RealInterceptor realInterceptor = new RealInterceptor();
    realInterceptor.enableLoggingForBody(true);
    realInterceptor.enableLoggingForUrl(true);
    realInterceptor.enableLoggingForHeaders(true);
    realInterceptor.enableLoggingForHttpStatusCodes(true);
    realInterceptor.enableLoggingForExecutionTime(false);

    //Add logging to okHttpClient
    OkHttpClient okHttpClient = new OkHttpClient()
            .newBuilder()
            .addNetworkInterceptor(realInterceptor)
            .build();

    //Init AndroidNetworking lib with the okHttpClient (with aloggint interceptor)
    AndroidNetworking.initialize(getApplicationContext(), okHttpClient);

}
}

I've added this to the manifest too:

 <application
        android:name=".TestLabApp"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

This is my own interceptor, because the one in the doc's example is simply not part of the lib.

public class RealInterceptor implements Interceptor {

private boolean logUrl             = true;
private boolean logBody            = true;
private boolean logHeaders         = true;
private boolean logHttpStatusCodes = true;
private boolean logExecutionTime   = true;


public void enableLoggingForUrl(boolean logUrl) {
    this.logUrl = logUrl;
}

public void enableLoggingForHeaders(boolean logHeaders) {
    this.logHeaders = logHeaders;
}

public void enableLoggingForBody(boolean logBody) {
    this.logBody = logBody;
}

public void enableLoggingForHttpStatusCodes(boolean logHttpStatusCodes) {
    this.logHttpStatusCodes = logHttpStatusCodes;
}

public void enableLoggingForExecutionTime(boolean logExecutionTime) {
    this.logExecutionTime = logExecutionTime;
}


private void logInfo(Object o) {
    Log.i(getClass().getSimpleName(), o.toString());
}

private void logError(Object o) {
    Log.e(getClass().getSimpleName(), o.toString());
}

@Override
public Response intercept(Chain chain) throws IOException {

    StringBuilder sb = new StringBuilder();

    Request     request        = chain.request();
    RequestBody requestBody    = request.body();
    boolean     hasRequestBody = requestBody != null;


    if (logUrl) {
        sb.append("\nURL: " + request.url());
    }

    if (logBody) {
        if (hasRequestBody) {
            Buffer buffer = new Buffer();
            requestBody.writeTo(buffer);
            String bodyParams = buffer.readString(Charset.forName("UTF-8"));
            bodyParams = bodyParams.replace("&", "\nParam: ");

            sb.append("\nParam: " + bodyParams);
        } else {
            sb.append("\nParam: <No params>");
        }
    }


    if (logHeaders) {
        Headers headers    = request.headers();
        String  headersStr = "";
        for (int i = 0, count = headers.size(); i < count; i++) {
            headersStr += "\nHeader: " + headers.name(i) + ": " + headers.value(i);
        }
        sb.append(headersStr);
    }

    long     startNs = System.nanoTime();
    Response response;
    try {
        response = chain.proceed(request);

    } catch (Exception e) {
        throw e;
    }

    if (logHttpStatusCodes) {
        sb.append("\nHTTP Status code: " + response.code());
    }

    long tookSec = TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startNs);
    long tookMs  = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);

    if (logExecutionTime) {
        if (tookSec > 1) {
            sb.append("\nExecution time: " + tookSec + " sec");
        } else {
            sb.append("\nExecution time: " + tookMs + " ms");
        }
    }

    if (response.code() != 200) {
        logError(sb.toString());
    } else {
        logInfo(sb.toString());
    }


    return response;
}

}

How I'm trying to use it:

AndroidNetworking.post("http://myurlishere.hu/api/test-result/save")
                    .addBodyParameter("param_1", "12345")
                    .addBodyParameter("param_2", "abcdef")
                    .build()
                    .getAsJSONObject(new JSONObjectRequestListener() {
                        @Override
                        public void onResponse(JSONObject response) {
                            // do anything with response

                            Log.i("RESP___", response.toString());

                            codeTv.setText(getString(R.string.please_read_the_qr_code));

                            enableControls(true);
                            progressBar.setVisibility(View.INVISIBLE);
                            zBarScannerView.resumeCameraPreview(MainActivity.this);

                            Toast.makeText(MainActivity.this, "API done", Toast.LENGTH_SHORT).show();

                        }
                        @Override
                        public void onError(ANError error) {
                            // handle error

                            codeTv.setText(getString(R.string.please_read_the_qr_code));
                            enableControls(true);
                            progressBar.setVisibility(View.INVISIBLE);
                            zBarScannerView.resumeCameraPreview(MainActivity.this);


                            DialogHelper.showInfo(MainActivity.this, "Error: Body: "+error.getErrorBody()+", Response: "+error.getResponse()+", Detail: "+error.getErrorDetail()+", Code: "+error.getErrorCode());
                        }
                    });

The problem is:

I don't see ANY logs about what is happening. Why?

4 Answers

Your code looks fine, but I can suggest alternative solution for logging

Firstly it is not necessary to create your own logging, As already package okhttp3.logging Provides HttpLoggingInterceptor which does log all the values which you expected in your RealInterceptor.

Here is an alternative solution :

   val logging = HttpLoggingInterceptor()
            logging.level = HttpLoggingInterceptor.Level.BODY
            okHttpClientBuilder!!.addInterceptor(logging)

In your case :

  //Add logging to okHttpClient
    var okHttpClient = OkHttpClient()
                .newBuilder()
                .addNetworkInterceptor(logging)
                .build()

Hope this helps, in case release mode of the application you can disable logging by just adding condition:

    var okHttpClientBuilder = OkHttpClient()
                       .newBuilder()

     if (BuildConfig.DEBUG) {
            okHttpClientBuilder.addNetworkInterceptor(logging)
      }

     var okHttpClient = okHttpClientBuilder.build()

Network Interceptors

  • Able to operate on intermediate responses like redirects and retries.

  • Not invoked for cached responses that short-circuit the network.

  • Observe the data just as it will be transmitted over the network.

  • Access to the Connection that carries the request.

I think your request have a cache and NetworkInterceptor will not working. Try to use addInterceptor instead of addNetworkInterceptor. It will work fine.

I think you might be lacking a no-args constructor, as the new keyword requires it:

public RealInterceptor() {}

Try to add it and it should return an instance. But better switch to Retrofit2 from some obviously abandoned library with roughly 200 open issues; there you can use the same Interceptor.

I did not quite understood as to why you are implementing Interceptor and making your own implementation of the Interceptor? Like do you need some custom logging features that is not provided in the library itself?

If all you need is to log headers and/or body of the request/response, the README file mentions that you can do so by simply enabling Logging.

AndroidNetworking.enableLogging(); // simply enable logging
AndroidNetworking.enableLogging(LEVEL.HEADERS); // enabling logging with level

It seems there are different levels that you can provide:

public enum Level {
        /**
         * No logs.
         */
        NONE,
        /**
         * Logs request and response lines.
         * <p>
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/1.1 (3-byte body)
         *
         * <-- 200 OK (22ms, 6-byte body)
         * }</pre>
         */
        BASIC,
        /**
         * Logs request and response lines and their respective headers.
         * <p>
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         * <-- END HTTP
         * }</pre>
         */
        HEADERS,
        /**
         * Logs request and response lines and their respective headers and bodies (if present).
         * <p>
         * <p>Example:
         * <pre>{@code
         * --> POST /greeting http/1.1
         * Host: example.com
         * Content-Type: plain/text
         * Content-Length: 3
         *
         * Hi?
         * --> END POST
         *
         * <-- 200 OK (22ms)
         * Content-Type: plain/text
         * Content-Length: 6
         *
         * Hello!
         * <-- END HTTP
         * }</pre>
         */
        BODY
    }

Let me know if this works for you. Have a nice one :)

Related