在不丢失详细信息的情况下,将捕获的ASP.NET异常写入EventLog

本文关键字:NET ASP 异常 EventLog 详细信息 情况下 | 更新日期: 2023-09-27 18:00:59

本文详细解释了如何将ASP.NET异常记录到Windows事件日志中,并向最终用户显示自定义错误页面。

但是,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: 

在不丢失详细信息的情况下,将捕获的ASP.NET异常写入EventLog

更新

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

解决方案1:

为此,只需创建一个继承WebErrorEvent的类,然后覆盖其构造函数:

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,但我还没有找到它。

我仍在试图弄清楚如何将自定义信息添加到事件中,因为没有为Web托管错误事件调用FormatCustomEventDetails方法。

解决方案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.
}

我发现使用现有的.NETApis几乎可以获得输出中所有必需的字段,只需要在EventLog中输出之前将其聚合为字符串即可。

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

当然,为了代码简洁,这一切都可以用一个方法来封装。