Print Android instrumentation tests logs in the terminal/console

While debugging some Android instrumentation tests that were ran using adb shell am instrument, I needed to print some logs into the terminal/console to inspect the flow and resolve some issues.

Ever been coding away, trying to track down what’s happening under the hood, thinking Log.i/e/d or System.out would be your trusty sidekicks for logging to the terminal? If so, you’ve probably shared in the surprise that they don’t quite work as our developer hearts might hope, stubbornly refusing to print to the terminal console, haha.

Alright, so I had to find a solution for this so I can inspect my instrumentation tests and fix the issues I’ve had. Wondering over the internet and the documentation I’ve stumbled across the Instrumentation class, trying to figure it out and in the official docs I’ve found the sendStatus method.

fun logToConsole(stringToPrint: String) {
    val bundle = Bundle()
    bundle.putString(
        Instrumentation.REPORT_KEY_STREAMRESULT, stringToPrint
    )
    InstrumentationRegistry.getInstrumentation().sendStatus(0, bundle)
}

The ideea is to get the current Instrumentation instance. Then, use the sendStatus method to print your debug message/logs in the terminal.

Using the function above you can print the tests logs into the terminal and debug more easily issues or simply inspect tests logs on Android. Nothing complicated (once you see it).

Looking for some other Logs related article? Maybe you want to also read: “Logs – how to filter them in Android Studio

sponsored
Exit mobile version