During development on a large existing codebase I’ve started to capture variable values in my Exception logging. For example:
public int Foo(int a, int b)
{
int returnInt;
try{
returnInt = bar(a) * b;
}
catch (Exception ex){
ex.Message += "a: {0}, b: {1}", a, b;
logger.log(ex);
}
return returnInt;
}
While I’m not asking about this specific pseudocode I wondered if there were any valid reasons to not do this?
To me it would seem that logging instance variables in addition to the more general error message and stack trace is a positive thing. However I’ve never seen it done elsewhere.
2
Conceptually, exceptions are to deal with “exceptional/unexpected” behavior of your application. If you want to log information, you should use a proper logging framework.
It’s also much cleaner to see something like
...
} catch (Exception ex){
logger.error(String.format("something went wrong with information %s %s", "infoA", "infoB"));
throw ex;
}
5
I’m not a security expert, but the only reason I can think of would be for security.
It may NOT be a good idea to log the variables when the values contains sensitive or personal user’s information. For example the user’s name, address, SSN, credit card, etc… I would try to log the transaction id or order id as a reference whenever possible.
Another situation would be the table definition or a SQL statement, which would disclose your architecture and design.
Sometimes it’s hard not to implement some of these when they are the key value in determining the problem, so I think, it’s a balance between support and security.
I take the “log anything and everything”* approach to logging because otherwise the one thing that you don’t log will inevitably be the thing that you need to know when the exception occurs.
*of course as Bri points out I avoid logging passwords, (some) personal details, and payment details. Some personal information may be useful to log (name and email address) to help identify the person and potentially contact them about the error that occurred but there may be legal issues with this depending on your location.