开发者

ASP.net Custom Errors Loggin

I'm using the customErrors attribute of the web.config file to present custom errors pages:

<customErrors mode="On" defaultRedirect="/errorpage.aspx">
    <error statusCode="404" redirect="/404Page.aspx"/>
    <error statusCode="403" redirect="/403page.aspx"/>
</customErrors>

Nothing too fancy. Now what I want to do is log the error that occurs when any of these pages are loaded. I'm specifically interested in any exceptions, I don't really care what page the user was on when they got a 404.

I'd like to 开发者_如何转开发capture the exception and record it into a db Table. Will something like this work:

//errorpage.aspx
public void Page_Load(object sender,EventArgs e)
{
    Exception objErr = Server.GetLastError().GetBaseException();
    var err = new {Url = Request.Url.ToString(),
                   Message = objErr.Message,
                   Trace = objErr.StackTrace.ToString()};

    db.Errors.InsertOnSubmit(err);
    db.SubmitChanges();

    Server.ClearError();
}

Is there any other information that is worth capturing, or is generally captured on an error?


I think there are better ways to do this:

  1. Use ELMAH!
  2. Run your code in the Global.asax Application_Error event.

void Application_Error(object sender, EventArgs e)
{
   Exception ex = Server.GetLastError().GetBaseException();
   EventLog.WriteEntry("Test Web",
     "MESSAGE: " + ex.Message + 
     "\nSOURCE: " + ex.Source +
     "\nFORM: " + Request.Form.ToString() + 
     "\nQUERYSTRING: " + Request.QueryString.ToString() +
     "\nTARGETSITE: " + ex.TargetSite +
     "\nSTACKTRACE: " + ex.StackTrace, 
     EventLogEntryType.Error);
}


Rather than rolling your own, have you considered using something like Elmah, which can handle this all for you:

http://www.hanselman.com/blog/ELMAHErrorLoggingModulesAndHandlersForASPNETAndMVCToo.aspx


Why don't you simply use the application server log, what happed if the error/exception is due to the impossibility of accessing the data base. Here is how I log the errors in some web site:

public static void WriteException(Exception exception)
{
    EventLog eventLog = null;
    try
    {
        StringBuilder message = new StringBuilder();
        message.Append("[").Append(exception.Source).Append(" - ").Append(exception.GetType().FullName);
        message.Append("]").Append(@"\r\n").Append(exception.ToString());              

        eventLog = new EventLog();
        eventLog.Log = "LOG_FILE_NAME";
        eventLog.Source = "APP_IDENTIFIER";
        eventLog.WriteEntry(message.ToString(), EventLogEntryType.Warning);
    }
    catch (Exception ex) {/*DO-NOTHING*/ string msg = ex.Message; }
    finally { if (eventLog != null) { eventLog.Dispose(); } eventLog = null; }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜