I am using SLF4J with Logback to log error messages. One of the observations was that for some of the root causes it is required toString()instead getMessage(). For example, if an exception is wrapped under a different one, SLF4J prints "null" in the root cause instead of an exception message that indirectly refers to toString(). Java uses library journals in order. However, I have to use SLF4J-Logback. Is there a way that overrides the default behavior of SLF4J and 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);
}
The result is presented:
// 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
source
share