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

I am trying to improve my optimization skills in Java. To achieve this, I have an old program that I created, and I try my best to make it better. In this program, I use SL4J for logging. To get a registrar, I did:

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

At the time I wrote the code, I thought it was the best option because I am removing the reference to the class name (which can be reorganized). But now I'm not sure anymore ...

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

On the other hand, a reference to the class name is saved, but it removes one method call. This may not be a big performance improvement for one class, but when you have many classes, it may be something.

So my question is:

Which approach is better? Use class name or get it through reflection?

Please motivate your answer pro and contra. Thanks.

+4
source share
6 answers

I will share my opinion. I would say that this is so that you should not worry in terms of performance. There are probably parts in the code that can be optimized much more than this thing :)

Now about your question. Check out the LoggerFactory code

Note that it getLogger(Class<?> name)simply calls the overloaded method:

Logger logger = getLogger(clazz.getName());

And does some extra calculations. So the method with the string is obviously a little faster.

Logger , :

public class SomeClass {
   private static final Logger LOG =   LoggerFactory.getLogger(SomeClass.class);
}

this.getClass(), this ( ).

ClassName.getClass() , . , .

, , 3 . , "DB" , -, database.log, .

, :

public class SomeClass {
   private static final Logger LOG =   LoggerFactory.getLogger("DB");
}

,

+4

, ,

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

,

protected final Logger log = LoggerFactory.getLogger(getClass());

. .

+3

Logger logger = LoggerFactory.getLogger(ClassName.class);

this.getClass() 

, . ,

+2

, , :

    public static org.slf4j.Logger getLogger() {
        final Throwable t = new Throwable();
        t.fillInStackTrace();
        return LoggerFactory.getLogger(t.getStackTrace()[1].getClassName());
    }

:

private static final Logger LOG = TheClassContainingTheMethod.getLogger();

.

0

private static final Logger log = LoggerFactory.getLogger(ClassName.class);
-1

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

}
// logic
try
{
// todo
}

catch (NullPointerException e) {
        logger.error("Error:-" + e.getMessage());
          return ResponseUtil.errorResponse(e.getMessage());
        }

        catch (Exception e) {
            logger.error("Error:-" + e.getMessage());
            return ResponseUtil.errorResponse(e.getMessage());
        }
-2
source

Source: https://habr.com/ru/post/1616360/


All Articles