OkLog


Source link: https://github.com/simonpercic/OkLog

OkLog

Network logging interceptor for OkHttp. Logs an URL link with encoded network call data for every OkHttp call.

!!! Important - Update notice

ResponseEcho (the server-side component of OkLog) was available at responseecho-simonpercic.rhcloud.com, which will no longer be available.
It is now available at oklog.responseecho.com.

To prevent OkLog-generated URLs from breaking, update your version of OkLog to 2.2.0 or newer OR call setBaseUrl with the new URL:

setBaseUrl("http://oklog.responseecho.com")

Why?

This inconvenience is due to RedHat sunsetting OpenShift v2, where ResponseEcho was hosted. Now it's hosted on Heroku. The new custom domain will prevent these inconveniences to happen in the future.

What about existing URLs?

All the existing URLs generated by OkLog will still continue to work, as long as you change the host from responseecho-simonpercic.rhcloud.com to oklog.responseecho.com.

Motivation

Debugging Android responses should be easier. Even with Retrofit logging enabled, copying multi-line responses from logcat is cumbersome and annoying.

OkLog writes a clickable link to the (Android) log with the OkHttp's response info as params. Clicking on the link in logcat opens your browser with the detailed response info.

Example response info

See an example in action.

How does it work?

OkLog intercepts responses from OkHttp, it then gzips and Base64 encodes the network response & the detailed response info and generates an url link with the encoded data as params. It then logs the url using:

  • Timber OR
  • Android's built-in logger (if your project does not include Timber) OR
  • Java's Logger (if used in a pure-Java/Kotlin project) OR
  • your custom logger

That url points to a hosted instance of the ResponseEcho web app that does the exact opposite, i.e. Base64 decodes and unpacks the url params and displays the response info for easier debugging.

Usage

OkLog for OkHttp (use for Retrofit 1.x)

Add using Gradle:

compile 'com.github.simonpercic:oklog:2.3.0'

OR (for a pure-Java/Kotlin project, without dependencies on Android)

compile 'com.github.simonpercic:oklog-java:2.3.0'

usage:

// create an instance of OkLogInterceptor using a builder() OkLogInterceptor okLogInterceptor = OkLogInterceptor.builder().build();
  // create an instance of OkHttpClient OkHttpClient okHttpClient = new OkHttpClient();
  // add OkLogInterceptor to OkHttpClient interceptors List<Interceptor> clientInterceptors = okHttpClient.interceptors();
 Collections.addAll(clientInterceptors, okLogInterceptor);
// use with Retrofit Client okClient = new OkClient(okHttpClient);
  new RestAdapter.Builder()
  .setEndpoint(endpoint)
  .setClient(okClient)
  ...
  .build();

OkLog3 for OkHttp3 (use for Retrofit 2.x)

Add using Gradle:

compile 'com.github.simonpercic:oklog3:2.3.0'

OR (for a pure-Java/Kotlin project, without dependencies on Android)

compile 'com.github.simonpercic:oklog3-java:2.3.0'

usage:

// create an instance of OkLogInterceptor using a builder() OkLogInterceptor okLogInterceptor = OkLogInterceptor.builder().build();
  // create an instance of OkHttpClient builder OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
  // add OkLogInterceptor to OkHttpClient's application interceptors okHttpBuilder.addInterceptor(okLogInterceptor);
  // build OkHttpClient okHttpClient = okHttpBuilder.build();
// use with Retrofit2 new Retrofit.Builder()
  .baseUrl(baseUrl)
  .client(okHttpClient)
  ...
  .build();

Builder options

  • setBaseUrl(String url) Set the base url to prefix the logs with. Useful if you're self-hosting ResponseEcho. Defaults to a hosted Heroku instance at: ' http://oklog.responseecho.com'

  • setLogInterceptor(LogInterceptor logInterceptor) Set a custom log interceptor to do your own logging. See LogInterceptor for details.

  • setLogger(Logger logger) Set a custom Logger to do your own logging. See Logger for details.

  • ignoreTimber(boolean ignoreTimber) Pass 'true' to ignore Timber for logging, even if it is present. Since Timber is an optional dependency, OkLog will use it only if it's included it in your app's dependencies. If not, it will fallback to using Android's built-in Log methods.

Additional log data options

method description included by default
withRequestBody(boolean) Include request body ? true
withRequestMethod(boolean) Include request method ? true
withRequestUrl(boolean) Include request url ? true
withProtocol(boolean) Include protocol ? false
withRequestContentType(boolean) Include request content type ? false
withRequestContentLength(boolean) Include request content length ? true
withRequestBodyState(boolean) Include request body state ? true
withRequestHeaders(boolean) Include request headers ? false
withRequestFailedState(boolean) Include request failed state ? true
withResponseCode(boolean) Include response code ? true
withResponseMessage(boolean) Include response message ? true
withResponseUrl(boolean) Include response url ? false
withResponseDuration(boolean) Include response duration ? true
withResponseSize(boolean) Include response size ? true
withResponseBodyState(boolean) Include response body state ? true
withResponseHeaders(boolean) Include response headers ? false
  • withNoLogData() Don't include any additional log data from the options.

  • withAllLogData() Include all additional log data from the options.

  • shortenInfoUrl(boolean) Shorten info url on the server-side, defaults to false.

Android and Java/Kotlin support

There are two variants of OkLog:

  • OkLog & OkLog3: for Android projects
  • OkLog-Java & OkLog3-Java: for pure Java/Kotlin projects (without Android dependencies)

The full variants matrix:

x Android pure Java/Kotlin (no-Android)
OkHttp (Retrofit 1.x) oklog oklog-java
OkHttp3 (Retrofit 2.x) oklog3 oklog3-java

Known limitations

OkLog for Android writes logs to Android's logging system, which has a limited line length (~4000 chars).

Even though the generated urls are gzipped and Base64 encoded, they might still be longer than the log line limit on very large http responses.

Unfortunately, there is no workaround with the current system. Nevertheless, everything should work fine for the majority of cases.

This library optionally uses Timber for the actual logging, which splits lines that are too long, so you can see if a response was longer than the limit.

ProGuard

ProGuard configuration is already bundled with OkLog/3, so you can safely use it with ProGuard.

Privacy

OkLog in combination with ResponseEcho are able to work by encoding request and response data in the URL path and query parameters.
Consequently, this data might be intercepted on the network.

The hosted instance of ResponseEcho that OkLog points to by default is accessible over plain HTTP (not HTTPS).

If you're concerned about your request and response data being intercepted, I strongly suggest you self-host ResponseEcho and set OkLog to point to your hosted instance (either locally or on your own server).

Url shortening

When using the url-shortening option (either via an option in OkLog or by using the shorten button on the response info page), the response info is shortened using the goo.gl url shortener service via their REST API, see: UrlShortenerManager.java.

Since the request and response data is included in the URL itself, shortening it using an external service consequently means that data is stored by the url shortening service provider.

If you're concerned about your request and response data being stored by the shortening service, I strongly suggest you don't shorten the url.

Google Analytics

Google Analytics is used in ResponseEcho to track its popularity and usage.
There are two analytics methods included:

  • using the Google Analytics API, when showing the plain response data, see: GoogleAnalyticsManager.java.
  • using the Google Analytics Web tracking via JavaScript, when showing the response info, see: base_head.html.

In either of these methods, NO response data is included in the analytics tracking.

Change Log

See CHANGELOG.md

License

Open source, distributed under the MIT License. See LICENSE for details.

Resources

Flatten json response with this simple library (for those who uses Gson for json deserialization).

ScriptJava is a simple command line utility that helps to evaluate simple Java statements at runtime (aka scripting). It may be used for educational purposes or just for fun of it as long as it offers a simple Java playground.

A clone of ActionBarTabs for Android which is compatible with Toolbar.

Material letter icon with colorful background. It also supports images usage for user contacts.

A simple implementation of a custom layout which solves the issues of grouping a child view with its tailing views.

Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes