Log4J - 在调用 LogManager.getLogger() 时显式指定类名有什么意义吗?
我正在处理一些带有大量代码的遗留代码,就像
private final Logger logger = LogManager.getLogger(ThisClassName.class);
我想知道输入“ThisClassName.class”是否有任何优势,而据
LogManager.getLogger(getClass());
我所知,没有任何优势,但我想知道使用 getClass() 是否有任何负面影响。 谢谢。
I'm working on some legacy code with a lot of code like
private final Logger logger = LogManager.getLogger(ThisClassName.class);
I'm wondering if there is any advantage to typing out "ThisClassName.class" as opposed to
LogManager.getLogger(getClass());
As far as I can tell, there is none, but I'm wondering if there are any negative ramifications to using getClass(). Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您将
Logger
设置为static
,则无法使用getClass()
。If you're making the
Logger
static
, you can't usegetClass()
.此外,如果存在实际调用该方法的子类,则 getClass() 将掩盖实际的类。 例如,假设在类 A 的方法 X 中,您调用 log.debug() 并且类 B 扩展类 A,覆盖方法 X,但在某个时刻调用 super.X。 日志文件将显示 B 类,而不是 A 类。
Also, getClass() will obscure the actual class if there's a subclass that's actually invoking the method. For example, assume that in class A, method X, you call log.debug() and class B extends class A, overwriting method X, but calling super.X at some point. The log file will show class B, not class A.
getClass() 不适用于静态上下文。 ThisClassName.class 适用于静态变量和实例变量。
getClass() does not work from a static context. ThisClassName.class works for static and instance variables.
我通常会将
getClass()
版本与实例变量Logger
一起使用(您不会创建另一个记录器实例,而只是查找一个)。这样做的原因是,在类层次结构中,了解您正在处理的事物的实际类型可能很有用,即使日志记录是从超类的方法内发生的。
通常,简单的文本搜索将准确地告诉您正在调用的日志语句,因此我在实践中没有发现它令人困惑。
I would usually use the
getClass()
version with an instance-variableLogger
(you aren't creating another logger instance, merely looking one up).The reason for this is that in class hierarchies, it can be useful to know what the actual type is of thing you are dealing with, even if logging is occurring from within a method on the superclass.
Normally a simple textual search will give you exactly what log statement is being called anyway, so I haven't found it confusing in practice.
其他发帖者已经评论说,如果您想定义一个静态记录器,则 getClass 将不起作用 - 并且为每个实例定义一个记录器效率很低。
如果您希望在运行时推断正确的类,并且您至少使用 Java 5,请查看 log5j,它将 log4j 包装在 Java 5 API 中。
这可以让你写出像这样的东西:
甚至:
Other posters have already commented that getClass won't work if you want to define a
static
Logger - and defining one per-instance is inefficient.If you want the correct class inferred at run time, and you are using at least Java 5, take a look at log5j, which wraps log4j in a Java 5 API.
This lets you write things like:
and even: