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

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

问题描述

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

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

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

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