NLog通过一次调用记录LogEventInfo和Exception数据

时间:2014-05-20 23:29:38

标签: c# asp.net-mvc visual-studio error-handling nlog

我正在使用NLog来记录我的应用程序中捕获的错误。我已经弄清楚如何捕获异常并使用Logger.ErrorException()记录它们,并且我已经想出如何使用Logger.Log(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";
        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}"

任何提示都将不胜感激!感谢

1 个答案:

答案 0 :(得分:10)

您只需要在Exception对象上将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);