I'm new to NLog and I've never used an advanced l开发者_运维知识库ogging library before. My question may seem stupid but I really want to know how and what's the best way to log custom exceptions with custom properties. Should I create a LayoutRenderer for each exception type or is there any better way to do this? Thanks
My first guess it that you do not want to write a custom LayoutRenderer for each exception type. The reason being that you probably want to define a single logging format for your log file. For example:
${date} | ${logger} | ${level} | ${message} | ${exception}
It would be very difficult to manage the formatting using many different LayoutRenderers for the exceptions. If you have a lot of custom LayoutRenderers, you might consider writing a single custom LayoutRenderer that can understand all of the custom exceptions that you have. Or, you might make a generic LayoutRenderer that can interpret any exception via reflection.
See this question and answers here on SO for some ideas about how to log custom exception information with NLog.
One of ideas presented is to write a custom LayoutRenderer that uses reflection to find the exception's properties and values and log them.
Another idea, that doesn't involve writing any extra code, is to try NLog's Exception renderer. One of its options is to use the ToString option (I think you specify it like this: ${exception:tostring}
. If your custom exceptions (and "normal" exceptions as well) provide enough information in their ToString
method, that might be sufficient.
精彩评论