gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:13:08 25 4
gpt4 key购买 nike

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:

最佳答案

更新

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

解决方案一:

为此,只需创建一个继承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() 返回许多其他信息,如果需要,也可以将其添加到输出中。

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

关于c# - 将捕获的 ASP.NET 异常写入 EventLog 而不会丢失详细信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38763488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com