I want this library I’m working on to have logging support, but Android and SE have their own ways of logging. In SE you can use System.out.println methods or the java.util.logging.Logger class. Android uses android.util.Log to log on logcat. At first I used reflection to check if android was usable, then reflectively call the log methods in Log.class; but that wasn’t a good idea.
My solution is to have the developers using my library handle logs themselves. There will be a Handler interface they set and has an onLog method
public void onLog(int level, String tag, String msg);
The library will call the onLog method on the handlers in my custom Logger class. Is it a good idea to have developers handle the logs instead of the library itself? Seems to be the best solution so far and if I document it good then it should’t be an issue.
I agree with you that logging should be delegated to clients, and your homegrown approach is indeed sensible.
IMO, the SLF4J facade would be ideal for your situation. Your library would include the
slf4j-apijar and contain SLF4J logging statements. If clients wanted logging, they’d just drop in a logging backend (and an optional config file) into their application’s classpath to capture/view your log statements.The advantages to this approach are that it grants clients the most control with zero coding required to get logging; and that it allows the client to choose among many available backends.
I would use
logbackas the backend for J2SE apps andlogback-androidfor Android.