MooHa
MooHa

Reputation: 849

Should I keep passing logger instance to different class

I create a logger instance in my main method and set it up as a global variable. If I want to use the same log file to log messages, is it good practice to pass the same logger instance to different constructor of classes. How else can you do this instead of passing.

public static void main(String[] args) {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd-HH:mm:ss");
        Handler h = new FileHandler("../logs/MyLogFile_"
                + sdf.format(date) + ".log", true);
        h.setFormatter(new SingleLineFormatter());
        h.setLevel(Level.ALL);
        logger.setUseParentHandlers(false);
        logger.addHandler(h);
} 

public void go(XMLConfig config) throws Exception {      
    Controller.setGlobalErrorHandler(new ErrorHandler(logger));
} 

public class ErrorHandler implements FDSErrorHandler {

    private static Logger logger = Logger.getLogger("com.explore.lse");

    public ErrorHandler(Logger logger) {
        this.logger = logger; 
    }
}

Upvotes: 5

Views: 5475

Answers (1)

radai
radai

Reputation: 24192

no, it most definitely isnt :-)

the common pattern for using logging frameworks is have a private final static logger field in every class that prints out to log (assuming of course loggers for your framework of choice are thread-safe. most are):

public class MyClass {
   private final static Logger log = LoggerFactory.getLogger(MyClass.class); //or the equivalent for your logging framework

   //rest of the code
}

you can then control which classes (==loggers) go into what files using logging configuration (usually xml).

sometimes ("sometimes" being fairly rarely and mostly in use by frameworks) you'd use "topic names" instead of class names when retrieving loggers. so, for example:

public class SomeSecurityRelatedClass {

   public void authenticateUser(String username, String pass) {
      if (!passCorrect(...)) {
         LoggerFactory.getLogger("SECURITY").info("rejecting user .... //etc
      }
   }
}

and while im ranting, another common abuse of logger names is when people want to somehow "mark" specific processes in a concurrent environment (say, you want all the logging related to the same user's requests to go to the same file per-user). DO NOT abuse logger names for this. instead, familiarize yourself with the concept of MDCs. they are supported by at least log4j and slf4j/Logback and can be used to "tag" processes or add any other extra data you want to your logs

Upvotes: 14

Related Questions