LoggerFactory.getLogger(ClassName.class) vs Logger

2019-03-19 07:01发布

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.

7条回答
可以哭但决不认输i
2楼-- · 2019-03-19 07:49

If you don't want to write the class name every time you declare a logger, you can use the following utility method:

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

The method can be used tis way:

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

With such an approach, the logger declaration is always the same for all the classes.

查看更多
登录 后发表回答