Is it possible to log properties of exception with NLog?
For example SocketException has properties such as ErrorCode, HResult, NativeErrorCode, etc that are specific to only this type of exceptions. It is possible to log them without explicitly logging (i.e without using Log(e.ErrorCode)) them and using just ErrorException from the code? The default Exception layout renderer just calls ToString on the exception.
I don’t know if it’s a very good idea, but you can write your own LayoutRenderer. To keep it simple I just wrote one that inherits from ExceptionLayoutRenderer and overrode the Append method.
The handling of the SocketException is not very sophisticated. I’m sure there is a better way, but it shows how you can do it.
To activate that you have to adjust your config like this:
Edit
Ok, I wasn’t aware that you want that feature for every exception that has it’s own properties. If there are only a few others you’re interested in, you can just add more if(exception is YourExceptionType) and adjust what properties you’re interested in.
A more generic approach is to use reflection to log all properties that are defined on the exception.
This adds every property that is declared on the exception type in alphabetical order to the log output.