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

2

9

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(...);
    }
}
Urinal answered 3/6, 2011 at 2:18 Comment(0)
L
6

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.

Lieberman answered 3/6, 2011 at 3:42 Comment(1)
@Op De Cirkel's answer does highlight the issue of making the logger static - in most cases it's fine, but if you're writing library code then you could consider making it non-static. You get a per-instantiation cost of making the call to Logger.getLogger but that's going to be negligible.Lieberman
C
0

They only benefit I see is that shorter log lines make code look clearer. But - in practice there is no difference at runtime

Croce answered 3/6, 2011 at 2:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.