Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging in "Java Library Code" libs for Android applications

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
}
like image 441
FrVaBe Avatar asked Feb 15 '11 09:02

FrVaBe


3 Answers

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

like image 143
Jörn Horstmann Avatar answered Oct 16 '22 09:10

Jörn Horstmann


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
like image 41
KaMyLL Avatar answered Oct 16 '22 09:10

KaMyLL


This works everywhere:

java.util.logging.Logger.getLogger("YOUR_TAG").log(java.util.logging.Level.INFO, "message");
like image 41
Moller40 Avatar answered Oct 16 '22 11:10

Moller40