ASP.net Custom Errors Loggin

孤街浪徒 提交于 2020-01-14 04:48:07

问题


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?


回答1:


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);
}



回答2:


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




回答3:


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; }
}


来源:https://stackoverflow.com/questions/4036436/asp-net-custom-errors-loggin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!