我们正在尝试将我们的应用程序从slf4j迁移到log4j到log4j2(2.10.0)。 我们发现了一个问题:
1)我们致电
LOGGER.warn("Message: object value is {}", object)
来自A级
2)对象覆盖从其他B类调用静态方法的toString
方法
3)生成对象使用记录器的字符串表示的方法:
LOGGER.warn( "Used ObjectsToStringGenerator for class: {}", o.getClass() )
我们希望日志看起来像:
2018-02-05 06:07:25.233 [main] WARN MainClass - Message: object values is [object string]
2018-02-05 06:07:25.233 [main] WARN ExampleObject - Used ObjectsToStringGenerator for class: class ExampleObject
但我们得到了这个:
2018-02-05 15:01:43.359 [main] WARN MainClass - Used ObjectsToStringGenerator for class: class ExampleObject[object string]
2018-02-05 15:01:43.373 [main] WARN ObjectsToStringGenerator - ObjectsToStringGenerator for class: ExampleObject
如果我们明确调用toString
方法:
LOGGER.warn("Message: object value is {}", object.toString() )
一切都按预期工作,但当然,我们希望避免明确使用object.toString()
。
我们也尝试使用同步记录器/追加器,但我们收到了错误:
main ERROR Recursive call to appender CONSOLE.
以下示例代码/记录器配置:
MainClass.java:
public class MainClass
{
private static final Logger LOGGER = LogManager.getLogger( MainClass.class );
public static void main(String[] args) throws InterruptedException {
//...
LOGGER.warn( "Message: object value is {}", new ExampleObject() );
//...
}
}
ExampleObject.java:
public class ExampleObject
{
@Override
public String toString(){
return ObjectsToStringGenerator.getStringValue( this );
}
}
ObjectsToStringGenerator.java:
public class ObjectsToStringGenerator
{
private static final Logger LOGGER = LogManager.getLogger( ObjectsToStringGenerator.class );
public static String getStringValue(Object o){
LOGGER.warn( "Used ObjectsToStringGenerator for class: {}", o.getClass() );
return "[object string]";
}
}
配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %p %c{2} - %m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="CONSOLE" />
</Root>
</Loggers>
</Configuration>