Write to Event Log


In this article , I explain about how to write Event Log in System.Diagnostics.EventLog class.

System.Diagnostics.EventLog class lets write our application logs to the windows event log, rather than writing logs into the specific file, its easy, and also good in terms of performance, and multiple users environment.

Opening the windows event log:

Go to Run command and type “eventvwr”, then press the OK button, this will open the windows event log, [or] you can also use the control panel to open it. You can see number of event log already exists in the tree view, like “Application”, “security”, “System” etc. in the same manner we can also add our logs from our application.

The following class is used to communicating with windows event log.


public class MyProjectHelper
{
static EventLog EL;
static MyProjectHelper()
{
if (!EventLog.SourceExists("TestApplication"))
{
//Creating new Log, (it will appear as a tree node in windows event log)
EventLog.CreateEventSource("TestApplication", "NewLog");
EL = new EventLog();
EL.Source = "TestApplication";
}

}

public static void AddEvent(string Message)
{
//Log a information to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Information);
}

public static void AddException(string Message)
{
//Log a exception to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Error);
}
public static void AddWarning(string Message)
{
//Log a warning to the eventLog
EL.WriteEntry(Message, EventLogEntryType.Warning);
}
}



Using the MyProjectHelper class to write the event logs

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)
{
//Logging Event
MyProjectHelper.AddEvent("Project Statrted");

//Logging Warning
MyProjectHelper.AddWarning("Too Many users connected with database..");

//Logging Exception
MyProjectHelper.AddException("Exception while accessing DB");
}
}


Comments

No responses found. Be the first to comment...


  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: