Friday, 5 December 2014

Create a Windows Event Log and Write Custom Message.



Here, I am posting this article about Windows event log API. When developers create a Windows based application, it may be an ActiveX component, any customized DLL library, a service application, etc.; it is a very common practice to write several types of information into the event log, which is generated by that particular application runtime so we can easily keep track of all the information.
For writing log in event log you can create a separate class for this.

Code is below:

/// <summary>
///  Method is used to create log.
/// </summary>
public bool CreateLog(string strLogName)
{
bool Result = false;

try
{
System.Diagnostics.EventLog.CreateEventSource(strLogName, strLogName);
System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog();

SQLEventLog.Source = strLogName;
SQLEventLog.Log = strLogName;

SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry("The " + strLogName + " was successfully initialize component.", EventLogEntryType.Information);

Result = true;
}
catch
{
Result = false;
}

return Result;
}


/// <summary>
/// Method is used to write event log.
/// </summary>
public void WriteToEventLog(string strLogName, string strSource, string strErrDetail)
{
System.Diagnostics.EventLog SQLEventLog = new System.Diagnostics.EventLog();

try
{
if (!System.Diagnostics.EventLog.SourceExists(strLogName)) this.CreateLog(strLogName);


SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry(Convert.ToString(strSource) + Convert.ToString(strErrDetail),
EventLogEntryType.Information);

}
catch (Exception ex)
{
SQLEventLog.Source = strLogName;
SQLEventLog.WriteEntry(Convert.ToString("INFORMATION: ") + Convert.ToString(ex.Message),
EventLogEntryType.Information);
}
finally
{
SQLEventLog.Dispose();
SQLEventLog = null;
}
}

For checking the Event Log please follow the below steps:

Go to Control Panel > Administrative Tools > Events Viewer > Search your Event Log name on left panel.

No comments:

Post a Comment