我正在使用带有Logback的SLF4J来记录错误消息。其中一个观察结果是,一些根本原因需要toString()
而不是getMessage()
。例如,如果异常被包装在另一个异常中,SLF4J会打印“#”;根本原因而不是toString()
中间接引用的异常消息。 Java util库日志很好。但是,我必须使用SLF4J-Logback。有没有什么方法可以覆盖SLF4J和logback的默认行为。
class TestException extends Exception
{
private String exceptionCode;
private String exceptionMessage;
@Override
public String toString()
{
return "TestException [exceptionCode=" + exceptionCode + ", exceptionMessage=" + exceptionMessage + "]";
}
}
try
{
TestException testException = new TestException();
testException.exceptionCode = "Test exception code";
testException.exceptionMessage = "Test exception message";
throw new IOException("Io message", testException);
}
catch (Exception e)
{
logger.error("Error message ", e);
java.util.logging.Logger.getAnonymousLogger().log(java.util.logging.Level.SEVERE, "Error message", e);
}
输出呈现:
// SLF4J logging
java.io.IOException: Io message
at test.Test.testMethod(Test.java:224)
at test.Test.main(Test.java:119)
Caused by: test.Test$1TestException: null
at test.Test.testMethod(Test.java:221)
... 1 common frames omitted
Nov 17, 2016 11:52:04 AM test.Test testMethod
// Java Util logging
SEVERE: Error message
java.io.IOException: Io message
at test.Test.testMethod(Test.java:224)
at test.Test.main(Test.java:119)
Caused by: TestException [exceptionCode=Test exception code, exceptionMessage=Test exception message]
at test.Test.testMethod(Test.java:221)
... 1 more