将一个捕获的ASP.NET异常写入EventLog而不会丢失详细信息

时间:2016-08-04 09:26:47

标签: c# asp.net exception error-handling exception-handling

This article详细解释了如何将ASP.NET异常记录到Windows EventLog并向最终用户显示自定义错误页面。

但是,ASP.NET Web应用程序的标准事件记录机制自动包含许多本文未显示的有用信息。实现文章中的代码会导致错误事件中的细节/粒度丢失。

例如,对于自动未捕获的异常日志记录,您可以在标题下看到许多属性:事件信息,应用程序信息,进程信息,请求信息,线程信息,自定义事件详细信息。

如何实现对未捕获的异常中记录的所有相同信息的记录,并将我的自定义信息附加到自定义事件详细信息部分?最好的答案最好使用System.DiagnosticsSystem.Exception或类似的一些内置方法,即编写尽可能少的代码来编写包含上述所有部分的日志条目,并简单地附加任何自定义详细信息字符串。

如果可能,我还想将唯一的哈希事件ID(下面的示例b68b3934cbb0427e9497de40663c5225)返回给应用程序,以便在ErrorPage.aspx上显示

所需日志格式示例:

Event code: 3005 
Event message: An unhandled exception has occurred. 
Event time: 15/07/2016 15:44:01 
Event time (UTC): 15/07/2016 14:44:01 
Event ID: b68b3934cbb0427e9497de40663c5225 
Event sequence: 131 
Event occurrence: 2 
Event detail code: 0 

Application information: 
    Application domain: /LM/W3SVC/3/ROOT-1-131130657267252632 
    Trust level: Full 
    Application Virtual Path: / 
    Application Path: C:\WWW\nobulus\nobulusPMM\Application\PMM\ 
    Machine name: L-ADAM 

Process information: 
    Process ID: 47216 
    Process name: iisexpress.exe 
    Account name: L-ADAM\Adam 

Exception information: 
    Exception type: ApplicationException 
    Exception message: Error running stored procedure saveValidation: Procedure or function 'saveValidation' expects parameter '@ValidatedBy', which was not supplied.
   at PMM.Models.PMM_DB.runStoredProcedure(String StoredProcedureName, List`1 SQLParameters) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.cs:line 104
   at PMM.Models.PMM_DB.saveValidation(String PTLUniqueID, String ValidatedBy, DateTime ValidationDateTime, Nullable`1 ValidationCategoryID, String ValidationCategory,     String Comment, Nullable`1 ClockStartDate, Nullable`1 ClockStopDate, String StartRTTStatus, String StopRTTStatus, String LastRTTStatus, Boolean MergedPathway, String     MergedPathwayID, String ExtinctPathwayID, DataTable ChecklistResponses) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.cs:line 265
   at PMM.Validate.lnkSaveButton_Click(Object sender, EventArgs e) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Validate.aspx.cs:line 323
   at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
   at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)



Request information: 
    Request URL: http://localhost:6901/Validate?PTLUniqueID=RTT10487 
    Request path: /Validate 
    User host address: ::1 
    User: L-ADAM\Adam 
    Is authenticated: True 
    Authentication Type: Negotiate 
    Thread account name: L-ADAM\Adam 

Thread information: 
    Thread ID: 19 
    Thread account name: L-ADAM\Adam 
    Is impersonating: False 
    Stack trace:    at PMM.Models.PMM_DB.runStoredProcedure(String StoredProcedureName, List`1 SQLParameters) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.    cs:line 104
   at PMM.Models.PMM_DB.saveValidation(String PTLUniqueID, String ValidatedBy, DateTime ValidationDateTime, Nullable`1 ValidationCategoryID, String ValidationCategory,     String Comment, Nullable`1 ClockStartDate, Nullable`1 ClockStopDate, String StartRTTStatus, String StopRTTStatus, String LastRTTStatus, Boolean MergedPathway, String     MergedPathwayID, String ExtinctPathwayID, DataTable ChecklistResponses) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Models\PMM_DB.cs:line 265
   at PMM.Validate.lnkSaveButton_Click(Object sender, EventArgs e) in C:\WWW\nobulus\nobulusPMM\Application\PMM\Validate.aspx.cs:line 323
   at System.Web.UI.WebControls.LinkButton.OnClick(EventArgs e)
   at System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
   at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
   at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)


Custom event details: 

1 个答案:

答案 0 :(得分:4)

<强>更新

我实际上发现使用ILSpy并在ASP.NET内部WebErrorEvent使用的不同框架类中漫游,它们拥有受保护的方法来实现相同的行为。

解决方案1:

为此,只需创建一个继承WebErrorEvent的类,然后覆盖其constructor

public class CustomWebErrorEvent : WebErrorEvent
{
    public CustomWebErrorEvent(string message, EventSource source, int eventCode, Exception ex) : base(message, source, eventCode, ex)
    {
    }
}

然后在Global.asax的错误管理方法中使用它:

protected void Application_Error(Object sender, EventArgs e)
{
    // Log error to the Event Log
    Exception myError = null;
    if (HttpContext.Current.Server.GetLastError() != null)
    {
        var r = new CustomWebErrorEvent("error", null, 120, HttpContext.Current.Server.GetLastError());
    }
}

我很确定也有可能将ASPNET重载为仅提升自定义WebErrorEvent,但我还没有找到它。

我仍在尝试弄清楚如何向事件添加自定义信息,因为重写方法FormatCustomEventDetails未被调用Web管理错误事件。

解决方案2:

如果暂时不能添加自定义字段,你可以使用我编写的类似输出相同的方法:

// Log error to the Event Log
Exception myError = null;
if (HttpContext.Current.Server.GetLastError() != null)
{
    var request = HttpContext.Current.Request;
    myError = HttpContext.Current.Server.GetLastError();

    var dateAsBytes = System.Text.Encoding.UTF8.GetBytes(DateTime.Now.ToString("G"));
    var id = Convert.ToBase64String(System.Security.Cryptography.MD5.Create().ComputeHash(dateAsBytes));

    // Event info:
    var eventMessage = myError.Message;
    var currentTime = DateTime.Now.ToString("G");
    var currentTimeUTC = DateTime.UtcNow.ToString("G");

    // Application info:
    var appDomainName = AppDomain.CurrentDomain.FriendlyName;
    var appDomainTrustLevel = (AppDomain.CurrentDomain.IsFullyTrusted) ? "Full" : "Partial";
    var appVirtualPath = VirtualPathUtility.GetDirectory(request.Path);
    var appPath = request.PhysicalApplicationPath;
    var machineName = Environment.MachineName;

    // Process info:
    var process = Process.GetCurrentProcess();
    var processId = process.Id;
    var processName = process.ProcessName;
    var user = System.Security.Principal.WindowsIdentity.GetCurrent().User;
    var accountName = user.Translate(typeof(System.Security.Principal.NTAccount));

    // Exception info:
    var exceptionType = myError.GetType().FullName;
    var exceptionMessage = myError.Message;
    var exceptionStack = myError.StackTrace;

    // Request info:
    var url = request.Url.AbsoluteUri;
    var urlPath = request.Url.PathAndQuery;
    var remoteAddress = request.UserHostAddress;
    var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
    var isAuthenticated = HttpContext.Current.User.Identity.IsAuthenticated;
    var authenticationType = System.Security.Principal.WindowsIdentity.GetCurrent().AuthenticationType;

    // Thread info:
    var impersonationLevel = System.Security.Principal.WindowsIdentity.GetCurrent().ImpersonationLevel;
    var exceptionStack2 = myError.StackTrace;

    // TODO: aggregate all info as string before writting to EventLog.
}

我发现使用现有的.NET Apis几乎是输出中所有必需的字段,只需要知道在将其输出到EventLog之前将其聚合为字符串。

您可以看到我正在使用的某些对象(例如AppDomain.CurrentDomainHttpContext.Current.RequestProcess.GetCurrentProcess()会返回很多其他信息,这些信息也可能会添加到输出中需要的。

当然,这一切都可以在代码简洁的方法下完成。