Monday, January 14, 2013

Writing to the Windows Event Log


You can interact with event logs in an ASP.NET page by using the classes in the System.Diagnostics namespace. First, import the namespace at the beginning of your code-behind file:

using System.Diagnostics;

The following example rewrites the simple ErrorTest page to use event logging:

public partial class ErrorTestLog : Page
{
 protected void cmdCompute_Click(Object sender, EventArgs e)
 {
   try
 {

   decimal a, b, result;
   a = Decimal.Parse(txtA.Text);
   b = Decimal.Parse(txtB.Text);
   result = a / b;
   lblResult.Text = result.ToString();
   lblResult.ForeColor = System.Drawing.Color.Black;
 }
  catch (Exception err)
   {
     lblResult.Text = "<b>Message:</b> " + err.Message + "<br /><br />";
     lblResult.Text += "<b>Source:</b> " + err.Source + "<br /><br />";
     lblResult.Text += "<b>Stack Trace:</b> " + err.StackTrace;
     lblResult.ForeColor = System.Drawing.Color.Red;
     // Write the information to the event log.
    EventLog log = new EventLog();
    log.Source = "DivisionPage";
    log.WriteEntry(err.Message, EventLogEntryType.Error);
  }
 }
}

The event log record will now appear in the Event Viewer utility, Note that logging is intended for the system administrator or developer. It doesn’t replace the code you use to notify the user and explain that a problem has occurred.

No comments:
Write comments
Recommended Posts × +