操作Windows日志:EventLog
如果要在.NET Core控制台项目中使用EventLog(Windows事件日志监控),首先需要下载Nuget包:
此外执行程序要拥有管理员权限
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 Event
{
class Program
{
static void WriteError()
{
//检测Windows日志中是否存在事件源:My Application,如果不存在就创建事件源
if (!EventLog.SourceExists("My Application"))
{
EventLog.CreateEventSource("My Application", "Application");//创建事件源,事件源名:My Application,事件日志名:Application
} var log = new EventLog("Application")//创建日志到事件日志:Application
{
Source = "My Application"//指定日志的事件源:My Application
}; log.WriteEntry("Error", EventLogEntryType.Error);
} static void Main(string[] args)
{
WriteError(); Console.WriteLine("Press any key to quit!");
Console.ReadKey();
}
}
}
测试:
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日志增量变化: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 = ; i < ; i++)
{
// Wait for events to occur.
System.Threading.Thread.Sleep();
} }
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/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