简体   繁体   中英

Event Log(Event log created event)

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;

            }

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);
            }
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM