.NET拾憶:EventLog(Windows事件日志監控)


 

 操作Windows日志:EventLog

1:事件日志名(logName):“事件查看器”中的每一項,如“應用程序”、“Internet Explorer”、“安全性”和“系統”都是日志(嚴格地說是日志的顯示名字)

2:事件源:列表中的“來源”,創建時和事件日志相關聯;

3:事件類型:包括“信息”、“錯誤”等;

 

基本操作:

1:創建日志:我沒找到直接創建日志的方法,日志應該都是通過下面的創建事件源來間接創建;

2:創建事件源:靜態方法EventLog.CreateEventSource(string sourceName, string LogName); //參數分別表示事件源名和日志名

   功能說明:在某個事件日志中創建事件源,如果事件日志不存在,則自動創建;

3:刪除日志:靜態方法EventLog.Delete(string logName);

4:刪除事件源:靜態方法EventLog.DeleteEventSource(string sourceName);

5:判斷日志是否存在:靜態方法EventLog.Exists(string logName);

6:判斷事件源是否存在:靜態方法EventLog. SourceExists (string sourceName);

7:寫日志:使用EventLog類的實例調用方法WriteEntry(string logDesc, EventLogEntryType.Information); //或者EventLogEntryType.Error

 

測試

using System;
using System.Diagnostics;

namespace WindowsConsoleApp
{
    //測試
    public class EnventLogHelper
    {
        private EventLog log;

        public EnventLogHelper()
        {
            log = new EventLog();//默認寫應用程序日志
        }
        public EnventLogHelper(string name)
        {
            log = new EventLog(name);//指定寫入的分類,用戶自定義則新建分組。系統保留//"Application"應用程序, "Security"安全, "System"系統
            //或者可以用 log.Log = "Security";指定
        }



        public void WriteToApp()
        {
            try
            {

                log.Source = "我的應用程序";//日志來源
                log.WriteEntry("處理信息1", EventLogEntryType.Information);//日志類型
                log.WriteEntry("處理信息2", EventLogEntryType.Information);
                throw new System.IO.FileNotFoundException("readme.txt文件未找到");
            }
            catch (System.IO.FileNotFoundException exception)
            {
                log.WriteEntry(exception.Message, EventLogEntryType.Error);

            }
        }

        public void ReadLog()
        {
            EventLogEntryCollection eventLogEntryCollection = log.Entries;//獲取日志collection
            foreach (EventLogEntry entry in eventLogEntryCollection)
            {
                
                string info = string.Empty;

                info += "【類型】:" + entry.EntryType.ToString() + ";";
                info += "【日期】" + entry.TimeGenerated.ToLongDateString() + ";";
                info += "【時間】" + entry.TimeGenerated.ToLongTimeString() + ";";

                info += "【計算機】" + entry.MachineName + "【來源】" + entry.Source + "【詳細信息】" + entry.Message + "【】";
                //
                Console.WriteLine(info);

            }
        }


    }
}

 

查詢Windows日志:EventLogQuery與EventRecord

 

 

 

 監控Windows日志增量變化:EventLogWatcher

 

using System;
using System.Diagnostics.Eventing.Reader;

namespace WindowsConsoleApp
{
    class SubscribeToEventsExample
    {
        static void Main1(string[] args)
        {
            //監控類
            EventLogWatcher watcher = null;

            try
            {
                // Xpath語法篩選目標事件的發生
                EventLogQuery subscriptionQuery = new EventLogQuery(
                "Application", PathType.LogName, "*[System/Level=2] or *[System/Level=3]");

                watcher = new EventLogWatcher(subscriptionQuery);

                // 訂閱到事件發生時候,觸發事件
                watcher.EventRecordWritten +=
                    new EventHandler<EventRecordWrittenEventArgs>(
                        EventLogEventRead);

                //開始訂閱Windows日志
                watcher.Enabled = true;

                //如果不停止,監控類會不停查詢時間發生,直到Enable設置為false
                for (int i = 0; i < 5; i++)
                {
                    // Wait for events to occur. 
                    System.Threading.Thread.Sleep(1000);
                }


            }
            catch (EventLogReadingException e)
            {
                Console.WriteLine("Error reading the log: {0}", e.Message);
            }
            finally
            {
                // 停止監控
                watcher.Enabled = false;

                if (watcher != null)
                {
                    watcher.Dispose();
                }
            }
        }

        /// <summary>
        /// 事件觸發
        /// </summary>
        public static void EventLogEventRead(object obj, EventRecordWrittenEventArgs arg)
        {
            // Make sure there was no error reading the event.
            if (arg.EventRecord != null)
            {
                Console.WriteLine("Received event {0} from the subscription.",
                    arg.EventRecord.Id);
                Console.WriteLine("Description: {0}", arg.EventRecord.FormatDescription());
                
                //log.EventId = arg.EventRecord.Id;//系統日志分配的記錄ID
                //log.Source = arg.EventRecord.ProviderName;//來源
                //log.Level = (int)(arg.EventRecord.LevelDisplayName == "錯誤" ? WinLogLevelID.ERROR : WinLogLevelID.WARN);
                //log.TaskName = arg.EventRecord.TaskDisplayName ?? "無";
                //log.LogMessage = arg.EventRecord.FormatDescription();
                //log.TimeCreate = arg.EventRecord.TimeCreated ?? DateTime.Now;
            }
            else
            {
                Console.WriteLine("The event instance was null.");
            }
        }
    }
}

 

 

 監控訂閱:https://msdn.microsoft.com/en-us/library/bb671202(v=vs.90).aspx

 查詢規則: https://msdn.microsoft.com/en-us/library/bb399427.aspx

 

 

 

 

 

 

資源:

源碼:https://referencesource.microsoft.com/#System/services/monitoring/system/diagnosticts/EventLog.cs

EventLog:https://msdn.microsoft.com/zh-cn/library/system.diagnostics.eventlog(v=vs.110).aspx

EventQuery:

https://msdn.microsoft.com/en-us/library/bb671200.aspx

EventLogReader:

https://msdn.microsoft.com/zh-cn/library/system.diagnostics.eventing.reader.eventlogreader(v=vs.110).aspx

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM