Which is the best way to declare logger variable i

2019-06-15 21:01发布

I just wantd to know which is the best way declare logger variable in java. Following are some declaration.

1> private static final Logger logger = Logger.getLogger(ServiceImpl.class);

2> private static Logger logger = Logger.getLogger(ServiceImpl.class);

3> private static final Logger LOGGER= Logger.getLogger(ServiceImpl.class);

4> private static Logger LOGGER= Logger.getLogger(ServiceImpl.class);

P.S I really appreciate if anybody knows another best alternative ways to declare looger variable.

标签: java logging
9条回答
聊天终结者
2楼-- · 2019-06-15 21:27

In my understanding of the java style guide, 'logger' is best. 'LOGGER' would be for a defined constant.

Furthermore, using 'final', should make it a bit faster.

Thus #1.

查看更多
Explosion°爆炸
3楼-- · 2019-06-15 21:28

First one is best.I prefer logger to be final and static....

查看更多
何必那么认真
4楼-- · 2019-06-15 21:29

I personally think private static final Logger LOGGER= Logger.getLogger(ServiceImpl.class); is the best way to go for semantic and performance reasons:

  • your Log belongs to the class not to various instances of it, for this reason you should make it static
  • it should be private because it's used internally by the class, it's not part of it's public API
  • making it final two makes sense, first of because this states that the refference will not change (which is the case here) and second because final intance variables (especially static ones) can be better optimised for speed by the compiler and the JIT (more details here)
  • naming it all upper-case is really just a nice convention, that's how static variables are declared in Java, it's not really a must but it makes the code more readable
查看更多
虎瘦雄心在
5楼-- · 2019-06-15 21:31

I would go with the first option but it is matter of personal choice I guess.

查看更多
狗以群分
6楼-- · 2019-06-15 21:36

I would recommend not to use such a variable in every class, but instead delegate this work to a static utility wrapper around slf4j, from jcabi-log:

Logger.debug(this, "some variable = %s", value);

Check this post as well: http://www.yegor256.com/2014/05/23/avoid-java-static-logger.html

查看更多
Animai°情兽
7楼-- · 2019-06-15 21:44

I vote for 3

 private static final Logger LOGGER = Logger.getLogger(ServiceImpl.class);

It's final since you don't change it and it's in uppercase since it's a constant.

查看更多
登录 后发表回答