Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use Logger.getLogger() every time I need it or create once per class

I am using Java util Logger. According to the documentation for Logger.getLogger method, it says, "Find or create a logger for a named subsystem. If a logger has already been created with the given name it is returned. Otherwise a new logger is created.". Would there still be any benefit in calling it only once per class?

Option 1:

public class Myclass 
    static Logger logger = Logger.getLogger(Myclass.class);

    public void method1() {
        logger.log(...);
    }

    public void method2() {
        logger.log(....);
    }
}

Option 2:

public class Myclass {
    public void method1() {
        Logger.getLogger(Myclass.class).log(...);
    }

    public void method2() {
        Logger.getLogger(Myclass.class).log(...);
    }
}
like image 795
powpow Avatar asked Jun 03 '11 02:06

powpow


People also ask

What does logger getLogger do?

getLogger. Find or create a logger for a named subsystem. If a logger has already been created with the given name it is returned. Otherwise a new logger is created.

How does LogManager getLogger work?

LogManager getLogger() method in Java with ExamplesIf it does not exists, then this method returns null. Parameters: This method accepts a parameter logger which is the name of the Logger to be get in this LogManager instance. Return Value: This method returns the name of this Logger in this LogManager if it exists.

What is the purpose of creating a logger object?

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

There are two not-very-important reasons why having a single static (probably final) instance is better than calling getLogger all the time.

  1. It makes the code slightly easier to read (in my opinion).
  2. There is a very small performance penalty you pay if you call Logger.getLogger all the time. It's not something to worry about unless you are calling it millions of times in a tight loop, but it's there.

That said, personal preference is vastly more important than either of these reasons. Option 1 is a common approach, but if you prefer option 2 then by all means use it. It's not going to hurt your code.

like image 119
Cameron Skinner Avatar answered Sep 23 '22 23:09

Cameron Skinner