March 19, 2011

Logging in EventLog

To log the Error in EventLog following is the code sample

EventLog1.cs

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Diagnostics;
using System.Text;
using System.Collections.Generic;
using System.Threading;
using System.IO;
using System.Globalization;


/// <summary>
/// Summary description for EventLog
/// </summary>
public class EventLog1
{

    public  void LogException(string ErrorDescription,String FunctionName)
    {


        // Log Category in the event logs


        string Log = "TestLog";


        // Check to see if the log for TestLog Category exists on the machine


        // If not, create it


        if ((!(EventLog.SourceExists(Log))))
        {


            EventLog.CreateEventSource(Log, Log);


        }


        // Now insert your exception information into the TestLog event log


        EventLog logEntry = new EventLog();


        logEntry.Source = Log;


        logEntry.WriteEntry(ErrorDescription + "in" + FunctionName, EventLogEntryType.Error);


    }
}


TestLog.aspx.cs
Use this from the code



using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class TestLog: System.Web.UI.Page
{
//Create object of the above class to use it

 EventLog1 evtlog = new EventLog1();

  protected void TestMethod(object sender, EventArgs e)
    {
       try
       {
           //code which can cause the error
       }
       catch (Exception ex)
       {
          evtlog.LogException(ex.Message, "TestMethod");
          
        }
    }
}

No comments:

Post a Comment