Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LoggerFactory.getLogger(ClassName.class) vs LoggerFactory.getLogger(this.getClass().getName())

I'm trying to improve my optimization skills in Java. In order to achieve that, I've got an old program I made and I'm trying my best to make it better. In this program I'm using SL4J for logging. To get the logger I did:

private static final Logger logger = LoggerFactory.getLogger(this.getClass().getName()); 

At the time I wrote the code, I thought this was the best option, because I remove a reference to the class name(which may be refactored). But now I'm not so sure anymore...

private static final Logger logger = LoggerFactory.getLogger(ClassName.class); 

On the other side, keeps the reference to the class name, but it removes one method call. This may not be a big improvement in performance for one class, but when you have lots of class, this may be something.

So my question is:

Which approach is better? Using the class name or getting it through reflection?

Please, motivate your answer with pro and cons. Thank you.

like image 594
Aurasphere Avatar asked Nov 18 '15 11:11

Aurasphere


People also ask

What does LoggerFactory getLogger do?

getLogger(java. lang. String): This method is used to find or create a logger with the name passed as parameter. It will create a new logger if logger does not exist with the passed name.

What is LoggerFactory Java?

The LoggerFactory is a utility class producing Loggers for various logging APIs, most notably for log4j, logback and JDK 1.4 logging. Other implementations such as NOPLogger and SimpleLogger are also supported.

What is LogManager getLogger?

The getLogger() method of java. util. logging. LogManager is used to get the specified Logger in this LogManager instance. This Logger must be a named Logger.


1 Answers

Late entry!

As I am likely to be searching for this in the future.

There is a way to create copy/paste friendly Logger instances (granted this is almost never a good reason to do something!) by using Java 7's MethodHandles class.

private static final Logger LOGGER = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); 
like image 188
Mark McLaren Avatar answered Sep 17 '22 03:09

Mark McLaren