Saturday, November 13, 2010

Write to the Windows Event Viewer

The Windows Event Log saves many information relevant to the system (e.g. the starting / stopping of clients, to name just one of many fields of application).
With C# we can easily add entries to this with the class System.Diagnostics.EventLog, for example to monitor the program flow. For that we have to first create a new source in the event log (if not already existing).
If there is not yet an entry of the application, so if we create a new source, we have to specify, to which category the program belongs to. For example there are the categories "Application", "Security", "Installation" etc.
The writing of the event is done via the function WriteEntry(). This expects the source as the first parameter, the category as second and optionally as the third the type of the event (e.g. warning, information, error ...)
For writing in the Event Log the programm will probably need administrative rights, how to do that you can read there.
The following code sample writes a short information text to the Windows Event Log (using System.Diagnostics; is required):

        private void Form1_Load(object sender, EventArgs e)
            string Source;
            string LogType;
            string LogEvent;

            Source = "Event Log C# Demo";
            LogType = "Application";
            LogEvent = "I like this blog.";

            if (!EventLog.SourceExists(Source))
                EventLog.CreateEventSource(Source, LogType);

            EventLog.WriteEntry(Source, LogEvent, EventLogEntryType.Information);

No comments:

Post a Comment