我目前在我的 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);
}
}
如果在控制器操作期间发生未处理的异常,这非常有用。
至于 404 错误,我在 web.config 中设置了一个自定义错误,如下所示:
<customErrors mode="On">
<error statusCode="404" redirect="~/page-not-found"/>
</customErrors>
在处理“page-not-found”网址的控制器操作中,我记录了请求的原始网址:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult PageNotFound()
{
log.Warn("404 page not found - " + Utils.SafeString(Request.QueryString["aspxerrorpath"]));
return View();
}
这也有效。
我遇到的问题是如何记录 .aspx 页面本身上的错误。假设我在某个页面或某些内联代码上出现编译错误,会引发异常:
<% ThisIsNotAValidFunction(); %>
<% throw new Exception("help!"); %>
似乎 HandleError 属性正确地将其重新路由到 Shared 文件夹中的 Error.aspx 页面,但它绝对没有被我的 BaseController 的 OnActionExecuted 方法捕获。我在想我可以将日志代码放在 Error.aspx 页面本身上,但我不确定如何在该级别检索错误信息。
我会考虑通过插入 Elmah 来简化您的网络应用程序。
您将 Elmah 程序集添加到您的项目中,然后配置您的 web.config。然后它将记录在控制器或页面级别创建的异常。它可以配置为登录到各种不同的地方(如 SQL Server、电子邮件等)。它还提供了一个 Web 前端,以便您可以浏览异常日志。
这是我添加到我创建的任何 asp.net mvc 应用程序的第一件事。
我仍然使用 log4net,但我倾向于使用它来记录调试/信息,并将所有异常留给 Elmah。
您还可以在问题 How do you log errors (Exceptions) in your ASP.NET apps? 中找到更多信息。
您可以挂钩 Global.asax 中的 OnError 事件。
像这样的东西:
/// <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);
}
}
}
Server
将始终为非空值。
if (ex is HttpException && ((HttpException)ex).GetHttpCode() == 404) return;
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();
}
}
在 Global.asax RegisterGlobalFilters 中放置属性
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
// filters.Add(new HandleErrorAttribute());
filters.Add(new ErrorLoggerAttribute());
}
Error.aspx 视图的定义如下:
namespace MvcApplication1.Views.Shared
{
public partial class Error : ViewPage<HandleErrorInfo>
{
}
}
HandleErrorInfo 具有三个属性: string ActionName string ControllerName Exception Exception
您应该能够访问 HandleErrorInfo 并因此访问视图中的异常。
您可以尝试检查 HttpContext.Error,但我对此不确定。