Writing to the Windows EventLog

by Edward 22 October 2010 08:50

Writing to the Windows application log, can be a benefit for developers to troubleshoot applications. It's easier to write to the event log, then to a file or the database - but you should use the application log for logging problems, not for debugging or writing a lot of junk. The idea behind this is to notify administrators or other developers in case there were a failure.

It's important to know that you need administrative rights on the computer to create a new event source. If you are writing to an existing log with an existing log source, it should work. If you write to an event log, you must remember to specify or create an event Source. The Source registers your application with the event log as a valid source of entries.

Here is small sample of code to get you started.

First you need to add System.Diagnostics namespace on your Using Directives:

using System.Diagnostics;

Next, copy the following method to your code file, and call it from another method.

        /// <summary>
        /// Writes to the event log.
        /// </summary>
        /// <param name="sCallerName">Name of the caller.</param>
        /// <param name="sLogLine">The log line.</param>
        public static void WriteEventLog(string sCallerName, string sLogLine)
        {
            try
            {
                if (!EventLog.SourceExists(sCallerName))
                {
                    EventLog.CreateEventSource(sCallerName, "MyApp");
                }

                // Create an EventLog instance and assign its source.
                EventLog myLog = new EventLog();
                myLog.Source = sCallerName;

                // Write an informational entry to the event log.   
                myLog.WriteEntry("Writing to event log.", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Below is a screenshot of how this sample code will write to the eventlog.

Tags: , ,

ASP.NET | Other

Comments are closed

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net

Month List