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;

//--- 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

//--- 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);
// 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)

P.S:Please do not hesitate to share your comments.


Popular posts from this blog

Exception caught instantiating TERADATA report server extension SQL Reporting Services

Assembly Microsoft.Dynamics.Service.Plugins.dll can not be loaded. Dynamics CRM 365 Engine version 9 - CRM User creation error

Could not load file or assembly 'System.ServiceModel, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089'. The system cannot find the file specified at Configuration class initiation in CrmServiceHelper.cv