【发布时间】:2016-01-27 11:49:06
【问题描述】:
我想覆盖 log4j.Logger 类的 error(Object message, Throwable t) 来改变一些事情。
但是,当我扩展 MYLogger 扩展 Logger 时,它仍然没有调用我的 error(..) 方法的实现,而是调用了超类的方法。
这里是代码
public class MYLogger extends Logger {
private static final String FQCN = MYLogger.class.getName();
protected MYLogger(String name) {
super(name);
// TODO Auto-generated constructor stub
}
public void error(Object message, Throwable t,final String codeKey, final String messageKey) {
System.out.println("codeKey "+codeKey+" messageKey"+messageKey);
String fmessage=codeKey+":"+messageKey;
if (this.repository.isDisabled(40000))
return;
if (Level.ERROR.isGreaterOrEqual(getEffectiveLevel()))
forcedLog(FQCN, Level.ERROR, fmessage, null);
}
}
并从我试图调用我的错误实现的测试类(..)
public class TestLogger {
protected static final MYLogger LOG = (MYLogger) MYLogger.getLogger(TestLogger.class);
public static void main(String[] args) {
LOG.error("Testing log error");
}
}
【问题讨论】:
-
你能验证
getLogger返回的运行时类型是MYLogger吗? -
该行/语句导致线程“main”中的异常异常 java.lang.ExceptionInInitializerError 原因:java.lang.ClassCastException:org.apache.log4j.Logger 无法转换为 test.MYLogger在 test.TestLogger.
(TestLogger.java:9) -
就是这样。
getLogger给你一个Logger而不是MYLogger。不知道如何解决这个问题。我敢打赌,log4j 中一定有一些关于自定义 Loggers 的教程。 -
在这方面没有找到任何东西,如果你有一些指针,请告诉我们
-
也许这会有所帮助:jajakarta.org/log4j/jakarta-log4j-1.1.3/docs/deepExtension.html 顺便说一句:我们在谈论哪个版本的 log4j? log4j 还是 log4j2 ?在后一种情况下,您可以阅读以下内容:logging.apache.org/log4j/2.x/manual/extending.html