1
votes

I would like to know if how can we catch the event in C# when a system event log is created. Also I would like to know if how can I get only ERROR LOGS from Windows event logs using C#. I have the following code but it just returns me all logs. I just need ERROR logs:

System.Diagnostics.EventLog eventLog1 = new System.Diagnostics.EventLog("Application", Environment.MachineName);

            int i = 0;
            foreach (System.Diagnostics.EventLogEntry entry in eventLog1.Entries)
            {
                Label1.Text += "Log is : " + entry.Message + Environment.NewLine;

            }
1
Take a look at the MSDN page -> link - Martin E

1 Answers

1
votes

You can use CreateEventSource static method of EventLog class to create event log like

EventLog.CreateEventSource("MyApp","Application");

EventLog class present in System.Diagnostics namespace.

You can use WriteEntry() method to write to the event log. EventLogEntryType enum can be used to specify the type of event you want to log. An example below

EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning,  234);

See How to write to an event log by using Visual C#

if you are looking for reading only ERROR level log then you can use the below code block. You just need to check EntryType of the eventlog entry and then print/display accordingly.

    static void Main(string[] args)
    {
        EventLog el = new EventLog("Application", "MY-PC");
        foreach (EventLogEntry entry in el.Entries)
        {
            if (entry.EntryType == EventLogEntryType.Error)
            {
                Console.WriteLine(entry.Message);
            }
        }
    }