Thursday, March 11, 2010

How to Write to the Event Log using C#

 /// 
    ///  Logs a message to the eventlog and returns true if successful.
    /// 
    public static bool LogMessageToEventLog(string source, string logName, string message, EventLogEntryType eventType, int eventId)
    {
        //need to impersonate user in order to gain access to the EventLog.SourceExists method
        System.Security.Principal.WindowsImpersonationContext impersonationContext=null;
        try
        {
            //impersonate the current windows user -- assumes your application is using windows authentication
            impersonationContext = ((System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity).Impersonate();



            //First we need to make sure that this source doesnt exist yet
            if (!EventLog.SourceExists(source))
            {
                //Create our source by providing the source and the name of the
                //new log name
                EventLog.CreateEventSource(source, logName);

                //Due to latency we want to wait a bit for the source and
                //log to be created. So we will sleep for 3 seconds
                System.Threading.Thread.Sleep(3000);
            }

            //Now we need a new instance of the EventLog
            EventLog log = new EventLog();
            //Set the source we're writing to
            log.Source = source;

            //Now write an entry
            log.WriteEntry(message, eventType, eventId);
            Debug.Print(message);
            return true;
        }
        catch (Exception ex)
        {
            Debug.Print(ex.Message);
            return false;
        }
        finally {
            if (impersonationContext != null) impersonationContext.Undo();
        }


    }

No comments: