문제

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:

  1. Is this a good idea / a good practice? Or should I create a "hard" dependency on log4j?
  2. 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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top