Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/282.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
c#从windows事件日志中实时读取_C#_Windows_Logging_Event Log - Fatal编程技术网

c#从windows事件日志中实时读取

c#从windows事件日志中实时读取,c#,windows,logging,event-log,C#,Windows,Logging,Event Log,我可以成功地从事件日志中读取事件。但是轮询所有事件的性能非常差。我想知道是否有一个事件或某事,我可以订阅以捕获“发生时”的日志条目 这可能吗 EventLog log = new EventLog("Security"); var entries = log.Entries.Cast<EventLogEntry>().Where(x => x.InstanceId == 4624).Select(x => new {

我可以成功地从事件日志中读取事件。但是轮询所有事件的性能非常差。我想知道是否有一个事件或某事,我可以订阅以捕获“发生时”的日志条目

这可能吗

EventLog log = new EventLog("Security");
        var entries = log.Entries.Cast<EventLogEntry>().Where(x => x.InstanceId == 4624).Select(x => new
        {
            x.MachineName,
            x.Site,
            x.Source,
            x.UserName,
            x.Message
        }).ToList();
        Console.WriteLine(entries[0].UserName);
EventLog log=neweventlog(“安全”);
var entries=log.entries.Cast()。其中(x=>x.InstanceId==4624)。选择(x=>new
{
x、 机械名称,
x、 地点,
x、 来源:,
x、 用户名,
x、 信息
}).ToList();
Console.WriteLine(条目[0]。用户名);
您可以为此目的使用。您可以订阅所需的日志过滤器,并在收到任何事件时实现要执行的处理程序函数

    public static void eventLogSubscription()
    {

        using (EventLog eventLog = new EventLog("Application"))
        {
            String path = Path.GetTempPath();
            eventLog.Source = "Event Log Reader Application";
            eventLog.WriteEvent(new EventInstance(1003, 0, EventLogEntryType.Information), new object[] { "The event log watcher has started" , path});
            //eventLog.WriteEntry(arg.EventRecord.ToXml(), EventLogEntryType.Information, 1001, 1);
            eventLog.Dispose();
        }
        EventLogWatcher watcher = null;
        try
        {
            string eventQueryString = "*[System/EventID=4688]" +
                                           "and " +
                                           "*[EventData[Data[@Name = 'NewProcessName'] = 'C:\\Windows\\explorer.exe']]"; 
        
            EventLogQuery eventQuery = new EventLogQuery(
                "Security", PathType.LogName, eventQueryString);

            watcher = new EventLogWatcher(eventQuery);
            watcher.EventRecordWritten +=
                new EventHandler<EventRecordWrittenEventArgs>(
                    handlerExplorerLaunch);
            watcher.Enabled = true;
     
        }
        catch (EventLogReadingException e)
        {
            Console.WriteLine("Error reading the log: {0}", e.Message);
        }
        Console.ReadKey();
    }

    public static void handlerExplorerLaunch(object obj,
        EventRecordWrittenEventArgs arg)
    {            if (arg.EventRecord != null)
        {
            
            using (EventLog eventLog = new EventLog("Application"))
            {
                eventLog.Source = "Event Log Reader Application";
                eventLog.WriteEvent(new EventInstance(1001, 0, EventLogEntryType.Information), new object[] {arg.EventRecord.FormatDescription() });
                //eventLog.WriteEntry(arg.EventRecord.ToXml(), EventLogEntryType.Information, 1001, 1);
                eventLog.Dispose();
            }
        }
        else
        {
            Console.WriteLine("The event instance was null.");

        }
    }
公共静态void eventLogSubscription()
{
使用(EventLog EventLog=new EventLog(“应用程序”))
{
String path=path.GetTempPath();
eventLog.Source=“事件日志读取器应用程序”;
eventLog.WriteEvent(新的EventInstance(1003,0,EventLogEntryType.Information),新对象[]{“事件日志观察程序已启动”,路径});
//WriteEntry(arg.EventRecord.ToXml(),EventLogEntryType.Information,1001,1);
eventLog.Dispose();
}
EventLogWatcher-watcher=null;
尝试
{
字符串eventQueryString=“*[System/EventID=4688]”+
“和”+
“*[EventData[Data[@Name='NewProcessName']='C:\\Windows\\explorer.exe']]”;
EventLogQuery eventQuery=新建EventLogQuery(
“安全性”、PathType.LogName、eventQueryString);
观察者=新的EventLogWatcher(eventQuery);
watcher.eventrecordwrited+=
新事件处理程序(
手推车;
watcher.Enabled=true;
}
捕获(EventLogReadingException e)
{
WriteLine(“读取日志时出错:{0}”,e.Message);
}
Console.ReadKey();
}
公共静态无效handlerExplorerLaunch(对象对象对象,
EventRecordWrittenEventTargets参数)
{if(arg.EventRecord!=null)
{
使用(EventLog EventLog=new EventLog(“应用程序”))
{
eventLog.Source=“事件日志读取器应用程序”;
WriteEvent(新的EventInstance(1001,0,EventLogEntryType.Information),新对象[]{arg.EventRecord.FormatDescription()});
//WriteEntry(arg.EventRecord.ToXml(),EventLogEntryType.Information,1001,1);
eventLog.Dispose();
}
}
其他的
{
WriteLine(“事件实例为null”);
}
}

我发现这样做更可靠

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

static void Main(string[] args)
{
    if (args is null) throw new ArgumentNullException(nameof(args));

    LoadEventLogs();

    Console.ReadKey();
}

private static void LoadEventLogs()
{
    EventLogSession session = new EventLogSession();

    EventLogQuery query = new EventLogQuery("Security", PathType.LogName, "*[System/EventID=4688]")
    {
        TolerateQueryErrors = true,
        Session = session
    };

    EventLogWatcher logWatcher = new EventLogWatcher(query);

    logWatcher.EventRecordWritten += new EventHandler<EventRecordWrittenEventArgs>(LogWatcher_EventRecordWritten);

    try
    {
        logWatcher.Enabled = true;
    }
    catch (EventLogException ex)
    {
        Console.WriteLine(ex.Message);
        Console.ReadLine();
    }
}

private static void LogWatcher_EventRecordWritten(object sender, EventRecordWrittenEventArgs e)
{
    var time = e.EventRecord.TimeCreated;
    var id = e.EventRecord.Id;
    var logname = e.EventRecord.LogName;
    var level = e.EventRecord.Level;
    var task = e.EventRecord.TaskDisplayName;
    var opCode = e.EventRecord.OpcodeDisplayName;
    var mname = e.EventRecord.MachineName;

    Console.WriteLine($@"{time}, {id}, {logname}, {level}, {task}, {opCode}, {mname}");
}
使用系统;
使用System.Diagnostics.Eventing.Reader;
静态void Main(字符串[]参数)
{
如果(args为null)抛出新ArgumentNullException(nameof(args));
LoadEventLogs();
Console.ReadKey();
}
私有静态void LoadEventLogs()
{
EventLogSession会话=新建EventLogSession();
EventLogQuery query=neweventlogquery(“Security”,PathType.LogName,“*[System/EventID=4688]”)
{
TolerateQueryErrors=true,
会话=会话
};
EventLogWatcher logWatcher=新的EventLogWatcher(查询);
logWatcher.EventRecordWrited+=新的事件处理程序(logWatcher\u EventRecordWrited);
尝试
{
logWatcher.Enabled=true;
}
捕获(EventLogException ex)
{
控制台写入线(例如消息);
Console.ReadLine();
}
}
私有静态void LogWatcher_eventrecordwrited(对象发送方,eventrecordwriteteneventargs e)
{
var time=e.EventRecord.TimeCreated;
var id=e.EventRecord.id;
var logname=e.EventRecord.logname;
变量级别=e.EventRecord.level;
var task=e.EventRecord.TaskDisplayName;
var opCode=e.EventRecord.OpcodeDisplayName;
var mname=e.EventRecord.MachineName;
WriteLine($@“{time},{id},{logname},{level},{task},{opCode},{mname}”);
}

订阅
eventwrited
事件并启用
EnableRaisingEvents
属性(都在
EventLog
上)。