zoukankan      html  css  js  c++  java
  • .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

  • 相关阅读:
    dedecms文章标题是在哪个数据库表?要批量替换关键词
    dedecms首页调用的简介一直修改不了是自动文章摘要在作怪
    如何进行微信营销?玩转微信公众平台营销理论手册
    用了那么久居然没发现firefox快捷键有如此多
    保护隐私:清除cookie、禁用cookie确保安全【分享给身边的朋友吧】
    如何更改firefox默认搜索引擎?一步搞定!
    微信红包中使用的技术:AA收款+随机算法
    马年添加一下马蹄印记统计(网站统计)
    今天上完就放假了,马年见
    三种dedecms调用相关文章的方法
  • 原文地址:https://www.cnblogs.com/xmai/p/6857379.html
Copyright © 2011-2022 走看看