简体   繁体   English

事件日志(事件日志创建事件)

[英]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. 我想知道在创建系统事件日志时如何在C#中捕获事件。 Also I would like to know if how can I get only ERROR LOGS from Windows event logs using C# . 我也想知道我如何才能使用C# 从Windows事件日志中仅获取错误日志 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静态方法创建事件日志,例如

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

EventLog class present in System.Diagnostics namespace. System.Diagnostics命名空间中存在EventLog类。

You can use WriteEntry() method to write to the event log. 您可以使用WriteEntry()方法写入事件日志。 EventLogEntryType enum can be used to specify the type of event you want to log. EventLogEntryType枚举可用于指定要记录的事件的类型。 An example below 下面的例子

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

See How to write to an event log by using Visual C# 请参阅如何使用Visual C#写入事件日志

if you are looking for reading only ERROR level log then you can use the below code block. 如果您只想读取ERROR级别的日志,则可以使用以下代码块。 You just need to check EntryType of the eventlog entry and then print/display accordingly. 您只需要检查EntryType条目的EntryType ,然后相应地打印/显示即可。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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