Search code examples
javalogginglog4jthread-safetyjava.util.logging

java wrapper around log4j logger and java.util.logging


I am writing a library. The library can be used by applications that use log4j loggers and java.util.logging loggers.

So, I wrote a quick wrapper class, that encapsulates both loggers. I allow the application to set one or both loggers. And in my library I use the encapsulated class to print to either logger.

My question is, since many threads can simultaneously be using the same instance of the wrapper class to log messages using the class' methods (for example: fatal() below), what steps should be taken to make these methods thread safe?

public class MultiLogger {
    private static org.apache.log4j.Logger _log4jLogger = null;
    private static java.util.logging.Logger _javaUtilLogger = null;

    private MultiLogger () {
    }

    // log4j FATAL, log util SEVERE
    public void fatal (Object message) {
        if (_log4jLogger != null) {
            _log4jLogger.log("", Level.FATAL, message, null);
        }

        if (_javaUtilLogger != null) {
            _javaUtilLogger.severe((String) message);
        }
    }
    ...
}

Any other comments appreciated too.


Solution

  • See my comment:

    You should check out slf4j before you proceed with this library. It wraps all the major logging libraries and is very high quality.

    But I presume that your wrapper class will be used in the same manner as the loggers that it wraps. In that case, the wrapped classes should handle the synchronization for you.