I follow the advice to implement Android device (not application!) independent library code for my Android Apps in a seperate "Java Library Code" project. This makes testing easier for me as I can use the standard maven project layout, Spring test support and Continuous Build systems the way I am used to. I do not want to mix this inside my Android App project although this might be possible.
I now wonder how to implement logging in this library. As this library will be used on the Android device I would like to go with android.util.Log
. I added the followind dependency to my project to get the missing Android packages/classes and dependencies:
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>2.2.1</version>
<scope>provided</scope>
</dependency>
But this library just contains stub method (similar to the android.jar inside the android-sdk), thus using android.util.Log
results in
java.lang.RuntimeException: Stub!
when running my unit tests. How do I implement logging which works on the Android device but does not fail outside (I do not expect it to work, but it must not fail)?
Thanks for any advice
Klaus
For now I am going with the workaround to catch the exception outside android but hope there is a better solution.
try {
Log.d("me", "hello");
} catch (RuntimeException re) {
// ignore failure outside android
}
These two links to a mirror of the android open source project (1, 2) seem to suggest that that the default Handler of java.util.Logging on android delegates to android.util.Log, so in your library you should be able to just use java.util.logging apis.
I could not find any further documentation regarding this behaviour
You can use this snippet:
java.util.logging.Logger.getLogger("SOME_TAG").log(Level.INFO, "log message")
And it will look like this in android logger:
2019-03-12 14:14:20.143 31195-32138/your.package.name I/SOME_TAG: log message
This works everywhere:
java.util.logging.Logger.getLogger("YOUR_TAG").log(java.util.logging.Level.INFO, "message");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With