Record ASP.NET caught exception in EventLog without loss of details

This article explains in detail how to register an ASP.NET exception in a Windows EventLog and display a user error page for the end user.

However, the standard event logging mechanism for an ASP.NET web application automatically includes a lot of useful information not shown in this article. The implementation of the code in the article leads to a loss of detail / detail in my Event error.

For example, when automatically catching uncaught exceptions, you can see many attributes under the headings: event information, application information, process information, request information, thread information, information about user events.

How can I implement logging of all information listed in an uncaught exception and add my user information to the "Custom event details" section? The best answer should preferably use some built-in methods System.Diagnosticsor System.Exceptionor similar, i.e. write as little code as possible to record a journal entry with all the sections mentioned above, and simply add any user data to the line.

If possible, I would also like to return the unique hash event id (example b68b3934cbb0427e9497de40663c5225below) back to the application to display on myErrorPage.aspx

An example of the required log format:

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: 
+4
1

UPDATE

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, .

, , 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.CurrentDomain, HttpContext.Current.Request Process.GetCurrentProcess()), , ​​ .

, , .

+4

Source: https://habr.com/ru/post/1650147/


All Articles