IgorShare Thoughts and Ideas

Consulting and Training

Custom Event Log trace listener/writer

Posted by Igor Moochnick on 02/05/2008

Ever wanted to route a bunch of your trace events to an event log for IT administrator to see? In .NET you can do this without even changing a single line of your code. I’m sure a lot of you already seen the default event trace listener, but, if you used it you’ve noticed, it doesn’t allow you much control of how and where these events are landed. In my project I needed such control to tell what events, to what event log and with what event source they’ll find their way in. So, to do this, I needed a new EventLogListenerEx (see the code below). This new EventLogListenrEx can be put easily into your configuration by the standard means:

   1: <sharedListeners>
   2:   <add name="eventLogListener" type="Yosemite.Utilities.EventLogListenerEx,Yosemite.Utilities" 
   3:        initializeData="Log=Application;Source=MyServer">
   4:     <filter type="System.Diagnostics.EventTypeFilter" initializeData="Warning" />
   5:   </add>
   6: </sharedListeners>

 

Note the “initializeData” attribute – it allows you to control to what Log and with what Source the events will be routed. This new event listener will create a new event source on demand if it’ll not find one, but, of cause, it should have enough privileges to do so. BTW: you can always create a required event source when needed from a stand-alone command line tool where you can have as much privileges as needed.

Enjoy!

    public class EventLogListenerEx : TraceListener
    {
        private string _EventLogName = "Application";
        private string _EventLogSource = "Application";
        private string _EventLogType = "Information";
        private EventLog _eventLog;
        private EventLogEntryType _logType;

        public EventLogListenerEx(string logType)
            : base()
        {
            System.Diagnostics.Trace.WriteLine("Event log processing");

            try
            {
                string[] parts = logType.Split(';');

                foreach (string part in parts)
                {
                    string[] settings = part.Split('=');

                    if (settings[0].ToLower() == "log")
                    {
                        _EventLogName = settings[1];
                    }
                    else if (settings[0].ToLower() == "source")
                    {
                        _EventLogSource = settings[1];
                    }
                    else if (settings[0].ToLower() == "type")
                    {
                        _EventLogType = settings[1];
                    }
                }

                _eventLog = new EventLog(_EventLogName);
                bool bRet = false;
                try
                {
                    bRet = EventLog.SourceExists(_EventLogSource);
                }
                catch (SecurityException)
                {
                    System.Diagnostics.Trace.WriteLine("Not enough credentials to create an event source - switching to Application.");
                    bRet = true;
                    _EventLogSource = "Application";
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine("Unexpected exception while checking for an event source: " + ex.ToString());
                    bRet = true;
                    _EventLogSource = "Application";
                }
                if (! bRet)
                {
                    try
                    {
                        EventLog.CreateEventSource(_EventLogSource, _EventLogName);
                    }
                    catch (SecurityException)
                    {
                        System.Diagnostics.Trace.WriteLine("Not enough credentials to create an event source - switching to Application.");
                        _EventLogSource = "Application";
                    }
                    catch (Exception ex)
                    {
                        System.Diagnostics.Trace.WriteLine("Unexpected exception while creating an event source: " + ex.ToString());
                        _EventLogSource = "Application";
                    }
                }

                _eventLog.Source = _EventLogSource;
                _logType = (EventLogEntryType)Enum.Parse(typeof(EventLogEntryType), _EventLogType);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Trace.WriteLine(ex.ToString());

                throw;
            }
        }

        public override void Write(string message)
        {
            string str = message.Trim();

            // Just in case - we'll log the event if it's not a Trace header
            if (str[str.Length - 1] != ':')
            {
                WriteLine(str);
            }
        }

        public override void WriteLine(string message)
        {
            _eventLog.WriteEntry(message, _logType);
        }
    }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: