2014-10-01 154 views
1

我想知道我們如何才能在中捕捉到事件#當創建系統事件日誌時。另外我想知道如果我只能從Windows事件日誌中獲取錯誤日誌使用C#。 我有下面的代碼,但它只是返回我所有的日誌。我只需要錯誤日誌:事件日誌(事件日誌創建事件)

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; 

      } 
+0

看一看在MSDN頁面 - > [鏈接](http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.entrywritten(V = VS.100)。 ASPX) – 2014-10-01 19:53:05

回答

1

您可以使用CreateEventSourceEventLog類的靜態方法來創建事件日誌像

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

EventLog類存在於System.Diagnostics命名空間。

您可以使用WriteEntry()方法寫入事件日誌。 EventLogEntryType枚舉可用於指定要記錄的事件的類型。下面

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

一個例子見How to write to an event log by using Visual C#

,如果你正在尋找只讀取ERROR級別的日誌,那麼你可以使用下面的代碼塊。您只需檢查事件日誌條目的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); 
      } 
     } 
    }