使用 getSimpleName() 与 getName() 获取记录器
我见过使用 log4j
的代码,它使用通过 getSimpleName 显式传递的前一个 api 获取给定
Logger
的
static public Logger getLogger(String name)
logger
static public Logger getLogger(Class clazz)
(),而后者在传递的 Class
上使用 getName()
。这两者有区别吗?如果我在 log4j.properties 文件中配置各种包以不同级别进行日志记录,会产生影响吗?
I've seen code that uses log4j
, which acquires logger
for a given Logger
using
static public Logger getLogger(String name)
and
static public Logger getLogger(Class clazz)
with the former api passed explicitly with getSimpleName()
, while the latter uses getName()
on the passed Class
. Is there a difference between these two? Would it affect if I configure various packages to log at different level in log4j.properties file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,存在巨大差异。
我从不使用
simpleName
作为Logger
实例,因为它会删除包名称。除了在两个不同的包中存在相同的类名时出现问题(导致两个类获得相同的记录器实例)之外,您还失去了控制记录器继承的能力。
例如,对于两个记录器:
在属性中,我可以有:
Yes there is a huge difference.
I never use
simpleName
forLogger
instance as it strips down the package name.Apart from having problems when same class name exists in two different packages (leading to both classes getting the same logger instance), you lose the ability to control logger inheritance.
e.g. for two loggers:
in properties, i can just have:
例如,我的类 ShapeDemo.java 位于 com.test 包中,我编写了如下代码。
这将输出以下内容
E.g. My class ShapeDemo.java resides in com.test package, and I have written code like below.
This will output following
使用 this.getClass().getName();
返回:alin.iwin.flickrbrowser.GetRawData
同时
private String LOG_TAG = this.getClass().getSimpleName();
仅返回:GetRawData。
Using of this.getClass().getName();
Returns : alin.iwin.flickrbrowser.GetRawData
Meanwhile
private String LOG_TAG = this.getClass().getSimpleName();
Return only : GetRawData.
我更喜欢使用全名(Class.getName())。当包被正确组织时,这允许调整 log4j 来处理来自 java 包树的不同部分的不同日志消息。
例如,您可以轻松配置以“com.mycompany.infra”开头的包中的所有类以使用特定的附加程序,并仅记录 WARN 或更高级别的消息。
I prefer using the full name (Class.getName()). When packages are organized correctly, this allows tuning log4j to handle differently log messages originating from different parts of the java packages tree.
For example, you can easily configure all classes in packages starting with "com.mycompany.infra" to use a specific appender, and log only messages of level WARN or above.
如果不同包中有许多具有相同
simpleName
的类,您可能会感到困惑。拥有许多同名的记录器应该不是问题,否则可能会造成混乱。You might get confused if you have many classes with the same
simpleName
in different packages. Having many loggers with the same name should not be a problem otherwise - just could be confusing.