Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Logging exceptions to the windows eventviewer - Part 73

Suggested Videos
Part 70 - Error events
Part 71 - Custom errors
Part 72 - Windows event viewer

In this video we will discuss about logging exceptions to windows eventviewer. In the previous videos we discussed about, creating the custom event log and event source in windows event viewer. Please watch Windows Event Viewer - Part 72, before continuing with this session.



Create an asp.net web application project. Add WebForm1.aspx. Drag and drop girdview control. Copy and paste the following code.
//try
//{
    // DataSet is System.Data namespace
    DataSet ds = new DataSet();
    // This line throws FileNotFoundException
    ds.ReadXml(Server.MapPath("~/Data/Countries.xml"));

    GridView1.DataSource = ds;
    GridView1.DataBind();
//}
//catch (Exception ex)
//{
//    Logger.Log(ex);
//}



Add a webform with name - Errors.aspx. 
<div style="font-family: Arial">
    <table style="border:1px solid black">
        <tr>
            <td style="color:Red">
                <h2>Application Error</h2>
            </td>
        </tr>
        <tr>
            <td>
                <h3>
                    An unkown error has occured. We are aware of it and the IT team is currently working
                    on this issue. Sorry for the inconvinience caused.</h3>
            </td>
        </tr>
        <tr>
            <td>
                <h5>
                    If you need further assistance, please contact our helpdesk at helpdesk@companyhelpdesk.com
                </h5>
            </td>
        </tr>
    </table>
</div>

Add a class file with name Logger.cs
public class Logger
{
    public static void Log(Exception exception)
    {
        // Create an instance of StringBuilder. This class is in System.Text namespace
        StringBuilder sbExceptionMessage = new StringBuilder();
        sbExceptionMessage.Append("Exception Type" + Environment.NewLine);
        // Get the exception type
        sbExceptionMessage.Append(exception.GetType().Name);
        // Environment.NewLine writes new line character - \n
        sbExceptionMessage.Append(Environment.NewLine + Environment.NewLine);
        sbExceptionMessage.Append("Message" + Environment.NewLine);
        // Get the exception message
        sbExceptionMessage.Append(exception.Message + Environment.NewLine + Environment.NewLine);
        sbExceptionMessage.Append("Stack Trace" + Environment.NewLine);
        // Get the exception stack trace
        sbExceptionMessage.Append(exception.StackTrace + Environment.NewLine + Environment.NewLine);

        // Retrieve inner exception if any
        Exception innerException = exception.InnerException;
        // If inner exception exists
        while (innerException != null)
        {
            sbExceptionMessage.Append("Exception Type" + Environment.NewLine);
            sbExceptionMessage.Append(innerException.GetType().Name);
            sbExceptionMessage.Append(Environment.NewLine + Environment.NewLine);
            sbExceptionMessage.Append("Message" + Environment.NewLine);
            sbExceptionMessage.Append(innerException.Message + Environment.NewLine + Environment.NewLine);
            sbExceptionMessage.Append("Stack Trace" + Environment.NewLine);
            sbExceptionMessage.Append(innerException.StackTrace + Environment.NewLine + Environment.NewLine);

            // Retrieve inner exception if any
            innerException = innerException.InnerException;
        }

        // If the Event log source exists
        if (EventLog.SourceExists("PragimTech.com"))
        {
            // Create an instance of the eventlog
            EventLog log = new EventLog("PragimTech");
            // set the source for the eventlog
            log.Source = "PragimTech.com";
            // Write the exception details to the event log as an error
            log.WriteEntry(sbExceptionMessage.ToString(), EventLogEntryType.Error);
        }
    }
}

Copy and pste the following code, in Global.asax, in Application_Error() event handler
if (Server.GetLastError() != null)
{
    // Get and Log the exception
    Logger.Log(Server.GetLastError());
    // Clear the exception
    Server.ClearError();
    // Transfer the user to Errors.aspx page
    Server.Transfer("Errors.aspx");
}

Run the application. WebForm1.aspx throws an exception. Since this exception is not handled any where it gets propagated till the application level, and Application_Error() event handler will be executed. This should log the exception to the windows eventviewer.

4 comments:

  1. m gettng ths error :"The name 'Logger' does not exist in ths current context

    ReplyDelete
    Replies
    1. using System.Diagnostic
      namespace include at starting of page

      Delete
  2. How to add new data node with specific name under in XML in event Viewer

    ReplyDelete
  3. application_error not firing i.e. I see Error.aspx redirection but no log in event viewer. When I include log code by try catch I could see log in event viewer.

    ReplyDelete

It would be great if you can help share these free resources