asp.net-mvc 在 ASP.NET MVC 中记录错误
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/569252/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Logging errors in ASP.NET MVC
提问by Kevin Pang
I'm currently using log4net in my ASP.NET MVC application to log exceptions. The way I'm doing this is by having all my controllers inherit from a BaseController class. In the BaseController's OnActionExecuting event, I log any exceptions that may have occurred:
我目前在我的 ASP.NET MVC 应用程序中使用 log4net 来记录异常。我这样做的方法是让我所有的控制器都继承自 BaseController 类。在 BaseController 的 OnActionExecuting 事件中,我记录了可能发生的任何异常:
protected override void OnActionExecuted(ActionExecutedContext filterContext)
{
// Log any exceptions
ILog log = LogManager.GetLogger(filterContext.Controller.GetType());
if (filterContext.Exception != null)
{
log.Error("Unhandled exception: " + filterContext.Exception.Message +
". Stack trace: " + filterContext.Exception.StackTrace,
filterContext.Exception);
}
}
This works great if an unhandled exception occurred during a controller action.
如果在控制器操作期间发生未处理的异常,这非常有效。
As for 404 errors, I have a custom error set up in my web.config like so:
至于 404 错误,我在 web.config 中设置了一个自定义错误,如下所示:
<customErrors mode="On">
<error statusCode="404" redirect="~/page-not-found"/>
</customErrors>
And in the controller action that handles the "page-not-found" url, I log the original url being requested:
在处理“页面未找到”网址的控制器操作中,我记录了所请求的原始网址:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult PageNotFound()
{
log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));
return View();
}
And this also works.
这也有效。
The problem that I'm having is how to log errors that are on the .aspx pages themselves. Let's say I have a compilation error on one of the pages or some inline code that will throw an exception:
我遇到的问题是如何记录 .aspx 页面本身的错误。假设我在其中一个页面或一些将引发异常的内联代码上出现编译错误:
<% ThisIsNotAValidFunction(); %>
<% throw new Exception("help!"); %>
It appears that the HandleError attribute is correctly rerouting this to my Error.aspx page in the Shared folder, but it is definitely not being caught by my BaseController's OnActionExecuted method. I was thinking I could maybe put the logging code on the Error.aspx page itself, but I'm unsure of how to retrieve the error information at that level.
看起来 HandleError 属性正确地将其重新路由到 Shared 文件夹中的 Error.aspx 页面,但它绝对没有被我的 BaseController 的 OnActionExecuted 方法捕获。我想我可以将日志代码放在 Error.aspx 页面本身上,但我不确定如何检索该级别的错误信息。
采纳答案by Andrew Rimmer
I would consider simplifying your web application by plugging in Elmah.
我会考虑通过插入Elmah 来简化您的 Web 应用程序。
You add the Elmah assembly to your project and then configure your web.config. It will then log exceptions created at controller or page level. It can be configured to log to various different places (like SQL Server, Email etc). It also provides a web frontend, so that you can browse through the log of exceptions.
您将 Elmah 程序集添加到您的项目,然后配置您的 web.config。然后它将记录在控制器或页面级别创建的异常。它可以配置为登录到各种不同的地方(如 SQL Server、电子邮件等)。它还提供了一个 Web 前端,以便您可以浏览异常日志。
Its the first thing I add to any asp.net mvc app I create.
这是我添加到我创建的任何 asp.net mvc 应用程序的第一件事。
I still use log4net, but I tend to use it for logging debug/info, and leave all exceptions to Elmah.
我仍然使用 log4net,但我倾向于使用它来记录调试/信息,并将所有例外情况留给 Elmah。
You can also find more information in the question How do you log errors (Exceptions) in your ASP.NET apps?.
您还可以在问题如何在 ASP.NET 应用程序中记录错误(异常)中找到更多信息。.
回答by Chuck Conway
You can hook into the OnError event in the Global.asax.
您可以挂钩 Global.asax 中的 OnError 事件。
Something like this:
像这样的东西:
/// <summary>
/// Handles the Error event of the Application control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Application_Error(object sender, EventArgs e)
{
if (Server != null)
{
Exception ex = Server.GetLastError();
if (Response.StatusCode != 404 )
{
Logging.Error("Caught in Global.asax", ex);
}
}
}
回答by Mark
MVC3
Create Attribute that inherits from HandleErrorInfoAttribute and includes your choice of logging
MVC3
创建从 HandleErrorInfoAttribute 继承的属性并包括您选择的日志记录
public class ErrorLoggerAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
LogError(filterContext);
base.OnException(filterContext);
}
public void LogError(ExceptionContext filterContext)
{
// You could use any logging approach here
StringBuilder builder = new StringBuilder();
builder
.AppendLine("----------")
.AppendLine(DateTime.Now.ToString())
.AppendFormat("Source:\t{0}", filterContext.Exception.Source)
.AppendLine()
.AppendFormat("Target:\t{0}", filterContext.Exception.TargetSite)
.AppendLine()
.AppendFormat("Type:\t{0}", filterContext.Exception.GetType().Name)
.AppendLine()
.AppendFormat("Message:\t{0}", filterContext.Exception.Message)
.AppendLine()
.AppendFormat("Stack:\t{0}", filterContext.Exception.StackTrace)
.AppendLine();
string filePath = filterContext.HttpContext.Server.MapPath("~/App_Data/Error.log");
using(StreamWriter writer = File.AppendText(filePath))
{
writer.Write(builder.ToString());
writer.Flush();
}
}
Place attribute in Global.asax RegisterGlobalFilters
在 Global.asax RegisterGlobalFilters 中放置属性
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// filters.Add(new HandleErrorAttribute());
filters.Add(new ErrorLoggerAttribute());
}
回答by Kieron
回答by Praveen Angyan
The Error.aspx view is defined like this:
Error.aspx 视图定义如下:
namespace MvcApplication1.Views.Shared
{
public partial class Error : ViewPage<HandleErrorInfo>
{
}
}
The HandleErrorInfo has three properties: string ActionName string ControllerName Exception Exception
HandleErrorInfo 具有三个属性: string ActionName string ControllerName Exception Exception
You should be able to access HandleErrorInfo and therefore the Exception within the view.
您应该能够访问 HandleErrorInfo 并因此访问视图中的异常。
回答by Mike Chaliy
You can try to examine HttpContext.Error, but I am not sure on this.
您可以尝试检查 HttpContext.Error,但我不确定这一点。

