mercredi 30 janvier 2013

How to log directly into EventLog server (Observateurs d'événements)

Every application can write into the server event log diary thanks to a C# class called "System.Diagnostics.EventLog"

In order to log message you have to instanciate one object of this class and specify two important elements Source and Log

Log will define the category in which your message will appear, you can use 'Application' 'Security' 'Installation' and so on.

Source define the name of the application that log the message, you can use your application name for example.


And the C# code to log into the diary event :


private static string SourceLog = "MyApplicationName";
private static string LogApp = "Application";
private static System.Diagnostics.EventLog eventLogApplication;

/// <summary>
/// Log the message into the Windows event log diary
/// </summary>
/// <param name="message">Message</param>
static void Log( string message )
{
     Log( message, System.Diagnostics.EventLogEntryType.Information );
}

/// <summary>
/// Log the message into the Windows event log diary
/// </summary>
/// <param name="message">Message enregistré</param>
/// /// <param name="entryType">Entry type</param>
static void Log( string message, System.Diagnostics.EventLogEntryType entryType )
{
     try
     {
          //Initialisation
          if (!System.Diagnostics.EventLog.SourceExists(SourceLog))
         {
              System.Diagnostics.EventLog.CreateEventSource(SourceLog, LogApp);
         }
         if (eventLogApplication == null)
        {
             eventLogApplication = new System.Diagnostics.EventLog();
             ((System.ComponentModel.ISupportInitialize)(eventLogApplication)).BeginInit();
             eventLogApplication.Source = SourceLog;
              eventLogApplication.Log = LogApp;
        }

        //Writing
        eventLogApplication.WriteEntry(message, entryType);
   }
    catch (Exception e)
    {
        Log("Error Log : " + e.InnerException + " " + e.Message, EventLogEntryType.Error);
      }
}

Aucun commentaire :

Enregistrer un commentaire