Creating EventLog in C# | Windows EventViewer

In this article, learn creating EventLog in C#. In C#, the System.Diagnostics namespace of System.Runtime.dll has the EventLog class which can be used to write a application log entry into the windows event logs.


Creating EventLog in C# | Windows EventViewer :

The Windows Event Viewer shows a log of application and system messages, including errors, information messages, and warnings. It’s one of the most frequently used tool for troubleshooting all kinds of different Windows problems.
The following example demonstrates how to use the EventLog class to log the information, warning, and error messages into windows event logs.


Note: Always make sure that the application is in Administrator mode to log the messages in windows event logs. Otherwise, your application may encounter a security exception.

using System;
using System.IO;
using System.Text;
using System.Diagnostics;
namespace ConsoleApplication1
{
    public class Program
    {
        public static void Main()
        {
            // Create an EventLog instance and assign its source.
            EventLog myEventLog = new EventLog();
            
            // Assign the event source.
            myEventLog.Source = "MyEventSource";

            try
            {
                // Write an informational entry to the event log.
                myEventLog.WriteEntry("INFO: Calculating EMI Started.",EventLogEntryType.Information);

                int emi = GetEMI();

                if (emi <= 2000)
                {
                    // Write an warning entry to the event log.
                    myEventLog.WriteEntry("Warning: EMI is below 2000.", EventLogEntryType.Warning);
                }

                // Write an informational entry to the event log.
                myEventLog.WriteEntry("INFO: Calculating EMI Completed.", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                // Write error event log.
                myEventLog.WriteEntry("INFO: Calculating EMI Completed.", EventLogEntryType.Error);                
            }
        }

        public static int GetEMI()
        {
            var retVal = 2000;

            //Calculate EMI logic here; Assign calculated EMI value to retVal;

            return retVal;
        }
    }
}



After executing the above code, you can see the log messages logged in event log viewer.


- Article ends here -

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Simulating Blue Screen Of Death - BOSD error in C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo