Can I create a "light" dependency on third party libraries like log4j in my own library?
I am maintaining a library for database access on http://jooq.sourceforge.net, and I would like to use log4j for logging. But logging is really a very optional part of my library. If log4j is not available in client code, then I won't do logging. So I created a logger proxy like this:
public final class JooqLogger {
// Initialise only once
private 开发者_开发知识库static boolean initialisationError = false;
// The log4j Logger reference
private Logger logger;
// Get the logger proxy for a class
public static JooqLogger getLogger(Class<?> clazz) {
JooqLogger result = new JooqLogger();
try {
result.logger = Logger.getLogger(clazz);
}
// Log4j is not found on the classpath, so ignore most of logging
catch (Throwable t) {
if (!initialisationError) {
initialisationError = true;
result.error("JooqLogger could not initialise log4j logger...");
}
}
return result;
}
// All methods from log4j Logger are available as well.
// They provide redirection and ignore all calls if log4j is not available.
public boolean isTraceEnabled() {
if (logger != null) {
return logger.isTraceEnabled();
}
else {
return false;
}
}
public void trace(Object message) {
if (logger != null) {
logger.trace(message);
}
}
// [... etc ...]
}
My questions are:
- Is this a good idea / a good practice? Or should I create a "hard" dependency on log4j?
- With the above solution, logging will not be as precise as if I were directly invoking log4j methods. For instance, the logged line number or .java file in the log files will always be the ones of JooqLogger, not of the caller. Is there a way to circumvent that problem?
Create an interface for it with a Null implementation, then allow the end developer/user/admin to substitute in a different implementation.
精彩评论