c#
记录日志到Windows事件查看器
C#中操作Windows事件日志主要使用EventLog类,它的内部调用了ReadEventLogW和ReportEventW等win32 API函数。
EventLog类提供了实例化版本的方法和静态方法两种,类似于FileInfo和FIle类。
获取所有事件日志
var logs = EventLog.GetEventLogs();
foreach (var item in logs)
{
//输出事件日志的名字(显示名字[日志名字])
//日志名字是用于读取/写入时的名字
Console.WriteLine(item.LogDisplayName + $"[{item.Log}]");
}
写事件日志
//需要先注册一个来源,跟日志绑定
if(!EventLog.SourceExists("MyApplicationLogSource"))
{
EventLog.CreateEventSource("MyApplicationLogSource", "Application");
}
EventLog.WriteEntry("MyApplicationLogSource", "测试日志内容",EventLogEntryType.Warning,100010);