记录器是否应该是私有静态的 [英] Should logger be private static or not

查看:36
本文介绍了记录器是否应该是私有静态的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

<前>私有静态日志日志 = new Log4JLogger(aClass.class);

应该使用哪个?两者的优缺点是什么?

解决方案

非静态形式的优点是您可以在如下所示的(抽象)基类中声明它,而不必担心会使用正确的类名:

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

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

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

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

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);

or

    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());

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.

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());

这篇关于记录器是否应该是私有静态的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆