I'm using NLog to log errors caught in my application. I've figured out how to catch exceptions and log them with Logger.ErrorException() and I've figured out how to log context event info with the Logger.Log(LogEventInfo). But I want to be able to log all this information in one go, rather than getting two log entries per exception, each of which only have half the data. Heres the code:
Exception ex = Server.GetLastError();
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace, "Hello from RunJob", logger.Name);
eventInfo.Properties["CustomerID"] = "someCustID";
eventInfo.Properties["TargetSite"] "someTargetSite";
logger.Log(eventInfo); //This results in a log entry which contains the values stored in 'CustomerID' and 'TargetSite', but not the details of the exception!
logger.ErrorException(ex.Data.ToString(), ex); //this results in a log entry which contains the exception details, but not the event info stored in 'CustomerID' and 'TargetSite'!
All I want is for one log entry per exception caught, and the log entry needs to include the CustomerID and TargetSite event info.
Here is my nlog.config layout, in case it helps:
Current User ID: ${event-context:CUID}${newline}
Target Site: ${event-context:TargetSite}${newline}
Exception Type: ${exception:format=Type}${newline}
Exception Message: ${exception:format=Message}${newline}
Stack Trace: ${exception:format=StackTrace}${newline}
Additional Info: ${message}${newline}"
Any tips would be much appreciated! Thanks
You just need to set the Exception
property to your exception on the LogEventInfo
object:
Exception ex = Server.GetLastError();
Logger logger = LogManager.GetCurrentClassLogger();
LogEventInfo eventInfo = new LogEventInfo(LogLevel.Trace,
"Hello from RunJob", logger.Name);
eventInfo.Properties["CustomerID"] = "someCustID";
eventInfo.Properties["TargetSite"] "someTargetSite";
eventInfo.Exception = ex; //set the exception for the eventInfo
logger.Log(eventInfo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With