Log Errors to Event Viewer C#

Use the following piece of code to log any error and/or information to Microsoft Windows Event Viewer. This is very useful when we need to store some information without doing extra efforts.


public static void LogError(string errorText)
        {
            string userName = string.Empty;
            if (HttpContext.Current != null)
            {
                userName = HttpContext.Current.User.Identity.Name;
                userName = userName.Remove(0, userName.IndexOf("\\") + 1);
            }

            StackTrace trace = new StackTrace();


            Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                if (!EventLog.SourceExists("MOE"))
                {
                    EventLog.CreateEventSource("MOE", "WebPart");

                }

                EventLog.WriteEntry("MOE", string.Format("User: {0} \nFile: {1} \nMethod: {2} \nLine #: {3} \nError: {4}", userName, trace.GetFrame(2).GetMethod().DeclaringType.Name, trace.GetFrame(2).GetMethod().Name, trace.GetFrame(2).GetFileLineNumber(), errorText), EventLogEntryType.Error);
            });

        }

You will have something like this;

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s