December 23, 2013

How to redirect raw stream to logcat?

Sometimes there is necessary to redirect lot of data, such as xml-file or something else, to logcat output.

Especially useful to see HTTP traffic of your interaction with RESTful server (obviously in debug-mode only). Let's try to wrap and re-direct Java-stream to Android Logcat!



I propose you to discover two auxiliary classes: AndroidLogStream and AndroidLogPrintStream.

Class AndroidLogStream extends from java.io.OutputStream and override method write().

Inside this method we collect all content into internal buffer and wait for symbol of new line. After it will be detected - just push accumulated buffer to Log output:


In this way we are printing all stream's data to Logcat with specified TAG and Priority.

Another class AndroidLogPrintStream just wraps first one to PrintStream. After that we can use it via method println() or print exception's stack trace into it.

Let's compile and run example app on device. That app opens raw InputStream and just redirect it to Logcat via class AndroidLogStream:




Hope this post will be useful for someone like me. Source code of this solution is available on github.

No comments:

Post a Comment