Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I keep passing logger instance to different class

Tags:

java

logging

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; 
    }
}
like image 326
MooHa Avatar asked Feb 07 '14 15:02

MooHa


People also ask

Should a logger be static?

Loggers should be declared to be static and final. It is good programming practice to share a single logger object between all of the instances of a particular class and to use the same logger for the duration of the program.

Which logger is best for Java?

One of the most popular solutions for the Java world is the Apache Log4j 2 framework. Maintained by the Apache Foundation, Log4j 2 is an improvement on the original Log4j, which was the most popular logging framework in Java for many years.

Can we add logger in abstract class?

If you create the logger in the abstract class, the logs will all come out tagged as originating from AbstractFoo. If you want/need to see logs tagged with the child class from which the log occurred, create loggers for the children classes.

What is the purpose of creating a logger object as state?

A Logger object is used to log messages for a specific system or application component. Loggers are normally named, using a hierarchical dot-separated namespace. Logger names can be arbitrary strings, but they should normally be based on the package name or class name of the logged component, such as java.net or javax.


1 Answers

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

like image 80
radai Avatar answered Oct 13 '22 00:10

radai