I noticed some confusion initially with my question. I\'m not asking about how to configure a logger nor how to use a logger properly, but rather how to capture all of the infor
Why not keep a local copy/list of all messages that would have gone to the debug log if it was enabled, and pass that to the custom exception when you throw it? Something like:
static void logDebug(String message, List msgs) {
msgs.add(message);
log.debug(message);
}
//...
try {
List debugMsgs = new ArrayList();
String myValue = someObject.getValue();
logDebug("Value: " + myValue, debugMsgs);
doSomething(myValue);
int x = doSomething2();
logDebug("doSomething2() returned " + x, debugMsgs);
}
catch (BadThingsHappenException bthe) {
// at the point when the exception is caught,
// debugMsgs contains some or all of the messages
// which should have gone to the debug log
throw new UnhandledException(bthe, debugMsgs);
}
Your exception class can make use of this List
parameter when forming getMessage()
:
public class UnhandledException extends Exception {
private List debugMessages;
public UnhandledException(String message, List debugMessages) {
super(message);
this.debugMessages = debugMessages;
}
@Override
public String getMessage() {
//return concatentation of super.getMessage() and debugMessages
}
}
The usage of this would be tedious - as you'd have to declare the local variable in every single try/catch where you wanted this type of information - but it might be worth it if you have just a few critical sections of code in which you'd like to maintain this state information on an exception.