3
votes

I'm writing a java library which will be used by some external web applications. Let's assume that each application can use different logging system, say App A uses slf4j over log4j and App B: uses log4j2 over logback (Log4j2 -> slf4j -> logback) or just plain logback.

Now I would like to use current logging framework to log some messages from the library.

  1. Which way I can detect logging system which is currently used by the client?
  2. How to dynamically log to detected logging system?

I did something like that before by detecting if particular classes (typical to slf4j) are on classpath and than used some "loggingService" which was logging directly to slf4j. I'm wondering if this is correct approach or how else this can be tackled?

1
I think your question goes into the "opinionated" area. "what is the best way" is way too unspecific. For one person, whatever works is "best", others might have much harder requirements. imho: your approach sounds OK to me. - GhostCat
@GhostCat: point taken. I rephrased question one. Thanks for your opinion. - walkeros
Log4J2 over Logback? You mean Log4J2 -> SLF4J -> Logback? - Kayaman
@Kayman: Yes this is what I meant...I'll fix that. - walkeros

1 Answers

6
votes

The normal way is to pick your logging API and have the application that uses your library provide an implementation for it (which can be just a bridge to whatever backend will actually be used).

For example, your library would build against slf4j-api. If the app wants to use Log4J, it would provide a) Log4J and b) a bridge from SLF4J to Log4J (so that you can log via SLF4J and it still ends up in Log4J).

Do not try to detect anything.

say App A uses slf4j over log4j and App B: uses log4j2 over logback

In the above example, App A is already set up to consume your library (because it provides slf4j-api), and App B is also ready (because it provides logback, which happens to also bring in slf4j-api). If App B used log4j2 over j.u.l, it would need to also pull in a bridge from sfl4j to j.u.l).

In general, there will be only one logging backend (decided and configured by the application), but there can be many logging API (so that all libraries that you need can have the one they like) that pipe into it.

The only reason code would ever want to detect and talk directly to the logging backend is if you need to programmatically configure it. Usually only application bootstrap code needs to do that (if at all). For the actual logging, you just talk to the API (of your choice).