如何在 ASP.NET MVC 中使用 NLog 记录未处理的异常

How log an unhandled exception with NLog in ASP.NET MVC

在我的 ASP.NET MVC 项目中,我有一个带有 [LogErrors] 属性的操作,如下所示:

[LogErrors]
public ActionResult Index()
 {
    var i = 0;
    var c = 10 / i;
    return View();
 }

我在这个操作中没有使用 trycatch(将 10 乘以 0)时发生了一个未处理的异常,我必须记录这个异常错误 text 并且记录这个异常发生在哪个操作中带有 NLog 的文本文件。我制作了 [LogErrors] 如下:

 public class LogErrorsAttribute : FilterAttribute, IExceptionFilter
{
    void IExceptionFilter.OnException(ExceptionContext filterContext)
    {
        if (filterContext != null && filterContext.Exception != null)
        {
            string controller = filterContext.RouteData.Values["controller"].ToString();
            string action = filterContext.RouteData.Values["action"].ToString();
            string loggerName = string.Format("{0}Controller.{1}", controller, action);

            NLog.LogManager.GetLogger(loggerName).Error(string.Empty, filterContext.Exception);
        }
    }
}

我的NLog.config如下:

 <?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd" >
  <targets>
    <target name="file" xsi:type="File" fileName="C:\Logs${shortdate}.log"
       layout="
--------------------- ${level} (${longdate}) ----------------------${newline}
IP: ${aspnet-request-ip}${newline}
Call Site: ${callsite}${newline}
${level} message: ${message}${newline}
Id: ${activityid}${newline}
aspnet-sessionid: ${aspnet-sessionid}${newline}
aspnet-request-method: ${aspnet-request-method}${newline}
aspnet-request-host: ${aspnet-request-host}${newline}
aspnet-request-form: ${aspnet-request-form}${newline}
aspnet-request-cookie: ${aspnet-request-cookie}${newline}
aspnet-request: ${aspnet-request:serverVariable=HTTP_URL}${aspnet-request:queryString}${newline}
aspnet-mvc-controller: ${aspnet-mvc-controller}${newline}
aspnet-mvc-action: ${aspnet-mvc-action}${newline}
aspnet-appbasepath: ${aspnet-appbasepath}${newline}
              " encoding="UTF8"/>
  </targets>
  <rules>
    <logger name="*" minlevel="Trace" writeTo="file" />
  </rules>
</nlog>

如何修复我的配置以记录此异常错误文本并在文本文件中记录此异常发生在哪个操作中?我们将不胜感激!

您需要向 .Error 发送消息并将 Exception 作为第一个参数发送。

否则大致翻译成string.Format("", filterContext.Exception).

所以像这样:

NLog.LogManager.GetLogger(loggerName)
               .Error(filterContext.Exception, "Unhandled exception in controller");

如果这不起作用,请检查 NLog troubleshooting guide