记录器应该是私有静态还是非静态

编程入门 行业动态 更新时间:2024-10-19 22:24:43
本文介绍了记录器应该是私有静态还是非静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

记录器是否应声明为静态?通常我见过两种类型的记录器声明:

Should logger be declared static or not? Usually I've seen two types of declaration for a logger :

protected Log log = new Log4JLogger(aClass.class);

private static Log log = new Log4JLogger(aClass.class);

应该使用哪一个?什么是两者的专业和概念?

Which one should be used? what are the pro's and con's of both?

推荐答案

非静态表单的优点是你可以在(抽象)基类如下,不必担心将使用正确的类名:

The advantage of the non-static form is that you can declare it in an (abstract) base class like follows without worrying that the right classname will be used:

protected Log log = new Log4JLogger(getClass());

然而,它的缺点显然是将为该类的每个实例创建一个全新的记录器实例。这可能本身并不昂贵,但它增加了很大的开销。如果您想避免这种情况,您可以使用 static 表单。但它的缺点是你必须在每个单独的类中声明它并在每个类中注意在记录器构造期间使用了正确的类名,因为 getClass()不能在静态环境中使用。但是,在普通的IDE中,您可以为此创建自动完成模板。例如。 logger + ctrl + space 。

However its disadvantage is obviously that a whole new logger instance will be created for every instance of the class. This may not per se be expensive, but it adds a significant overhead. If you'd like to avoid this, you'd like to use the static form instead. But its disadvantage is in turn that you have to declare it in every individual class and take care in every class that the right classname is been used during logger's construction because getClass() cannot be used in static context. However, in the average IDE you can create an autocomplete template for this. E.g. logger + ctrl+space.

另一方面如果您通过工厂获得记录器,而工厂又可以缓存已经实例化的记录器,那么使用非静态表单将不会增加太多开销。例如,Log4j有一个 LogManager 用于此目的。

On the other hand, if you obtain the logger by a factory which in turn may cache the already-instantiated loggers, then using the non-static form won't add that much overhead. Log4j for example has a LogManager for this purpose.

protected Log log = LogManager.getLogger(getClass());

更多推荐

记录器应该是私有静态还是非静态

本文发布于:2023-11-15 21:27:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1598099.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:静态   记录器   是非   应该是

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!