Let's say I have some application code like this:
public void DoSomething()
{
if (SomethingBad)
throw new SomethingBadException("You did something bad");
// Keep going...
}
I'm using log4net, and ideally I'd like to log that exception, with the following caveats:
- I'd like to log the exception at this point, and not depend on the caller to log it
- I'd like to log the exception using a Logger owned by this class, so that the logger name is correct
- I don't want SomethingBadException to know about logging, as sometimes I want to log this particular exception type, and sometimes I don't. I also want to use the same pattern for built-in exception types, such as NotSupportedException
- I want to have a reusable pattern where the exception / logging statement is not too complex, as I'm going to have a lot of these. If this involves creating a utility class that does most of the work, this is fine.
- I'd like to log the exception including the call stack, which means that it has to be logged after it is thrown. Logging it after the exception is constructed, but before it is thrown, gives me an empty call stack in the log output.
I've been able to write some utility code that accomplishes most of those bullets, but the last one involving capturing the call stack is eluding me.
Is there any way to accomplish all of these? I'm willing to write custom log4net extensions. I'm also using Ninject's log4net extension to build loggers if that helps.
Am I barking up the wrong tree? Is there another approach entirely that gets me where I want to go?