【问题标题】:How log an unhandled exception with NLog in ASP.NET MVC如何在 ASP.NET MVC 中使用 NLog 记录未处理的异常
【发布时间】:2020-02-04 19:15:18
【问题描述】:

在我的 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>

如何修复我的配置以记录此异常错误文本,并在文本文件中记录此异常发生在哪个操作中?任何帮助都会得到帮助!

【问题讨论】:

  • 对不起。我stydie了这个页面,它对我不起作用。

标签: c# asp.net-mvc exception nlog


【解决方案1】:

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

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

所以是这样的:

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

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

【讨论】:

  • 好的,谢谢。我还有另一个问题,我需要准确记录错误异常文本以及我遇到此错误的操作。我应该在 NLog.config 中写什么?你能帮帮我吗?
  • 我在 NLog 中使用了 "exception: ${exception:format=tostring}${newline}" 但它给了我一个太长的日志,我不需要所有这些。
  • 是的,完全正确。谢谢。
猜你喜欢
  • 2010-10-23
  • 2017-11-22
  • 2011-05-03
  • 1970-01-01
  • 1970-01-01
  • 2010-11-05
  • 1970-01-01
  • 2017-10-08
  • 1970-01-01
相关资源
最近更新 更多