我目前在我的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“url的控制器操作中,我记录了请求的原始url:
[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属性正确地将其重新路由到共享文件夹中的Error.aspx页面,但它绝对不会被BaseController的OnActionExecuted方法捕获。我在想,也许我可以将日志记录代码放在Error.aspx页面本身上,但我不确定如何在该级别检索错误信息。
发布于 2011-09-15 05:50:38
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());
}https://stackoverflow.com/questions/569252
复制相似问题