C# 通过一次调用记录LogEventInfo和异常数据
我正在使用NLog记录应用程序中捕获的错误。我已经了解了如何捕获异常并使用Logger.ErrorException()记录它们,还了解了如何使用Logger.log(LogEventInfo)记录上下文事件信息。但我希望能够一次性记录所有这些信息,而不是每个异常都有两个日志条目,每个条目只有一半的数据。代码如下:C# 通过一次调用记录LogEventInfo和异常数据,c#,asp.net-mvc,visual-studio,error-handling,nlog,C#,Asp.net Mvc,Visual Studio,Error Handling,Nlog,我正在使用NLog记录应用程序中捕获的错误。我已经了解了如何捕获异常并使用Logger.ErrorException()记录它们,还了解了如何使用Logger.log(LogEventInfo)记录上下文事件信息。但我希望能够一次性记录所有这些信息,而不是每个异常都有两个日志条目,每个条目只有一半的数据。代码如下: Exception ex = Server.GetLastError(); Logger logger = LogManager.GetCurrent
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'!
我想要的只是每个捕获的异常都有一个日志条目,日志条目需要包括CustomerID和TargetSite事件信息
以下是我的nlog.config布局,以防有所帮助:
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}"
任何提示都将不胜感激!谢谢您只需将
异常
属性设置为LogEventInfo
对象上的异常:
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);