write Logs into Windows Event in C#
Here is the code you can use;
///
/// It manages logging policy.
/// use app.config of the dll to clarify debug.print logging will be used.
/// default value = true
///
/// caller Application Name
/// Log Name
/// localhost
/// use additional Debug.Print Logs, every time logging occur
public AdvanceLogging(string strSourceName, string strLogName, string strMachineName, bool useDebugPrint)
{
Microsoft.Win32.RegistryKey registrykeyLM = null;
Microsoft.Win32.RegistryKey registrykeyEventlog = null;
Microsoft.Win32.RegistryKey registrykeyKey = null;
try
{
//--- Check to see that event log name exists, if so...
if (System.Diagnostics.EventLog.Exists(StrLogName))
{
//--- Check to see if the source exists, if not...
if (!System.Diagnostics.EventLog.SourceExists(strSourceName))
{
//--- Create new source
System.Diagnostics.EventLog.CreateEventSource(strSourceName, StrLogName);
}
}
else //--- Log name does not exist
{
//--- Check to see if the source exists, if it exists but the log does not, delete source
if (System.Diagnostics.EventLog.SourceExists(StrSourceName))
{
//--- Delete source
System.Diagnostics.EventLog.DeleteEventSource(StrSourceName);
}
//--- Create new log and source
System.Diagnostics.EventLog.CreateEventSource(StrSourceName, StrLogName);
//--- Modify registry settings on local machine
registrykeyLM = Microsoft.Win32.Registry.LocalMachine;
registrykeyEventlog = registrykeyLM.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\EventLog\\" + _strLogName, true);
registrykeyEventlog.SetValue("Retention", 0);
}
}
catch (Exception exceptionGeneral)
{
throw new ArgumentException("Exception(CreateEventLog): ", exceptionGeneral.Message);
}
finally
{
// Close the registry keys.
if (registrykeyEventlog != null) registrykeyEventlog.Close();
if (registrykeyKey != null) registrykeyKey.Close();
if (registrykeyLM != null) registrykeyLM.Close();
}
EventLog _log = new EventLog(strLogName, strMachineName, strSourceName);
_log.WriteEntry(strMessage, EventLogEntryType.Waring);//type of Warning
//can be Information,Error
if (_useDebugPrint)
System.Diagnostics.Debug.Print(strMessage);
}
cheers,
P.S:Please do not hesitate to share your comments.
Comments
Post a Comment