简体   繁体   English

如何使用 C# 从应用程序和服务 windows 事件源读取事件?

[英]How to read events from a Application and Services windows event source using C#?

I am trying to read windows event logs for: "Microsoft-Windows-Sysmon/Operational" I tried:我正在尝试阅读 windows 事件日志:“Microsoft-Windows-Sysmon/Operational” 我试过:

string eventLogName = "Microsoft-Windows-Sysmon/Operational";

            EventLog eventLog = new EventLog();
            eventLog.Log = eventLogName;

            foreach (EventLogEntry log in eventLog.Entries)
            {
                Console.WriteLine("{0}\n", log.Message);
            }

However, I get:但是,我得到:

System.InvalidOperationException: 'The event log 'Microsoft-Windows-Sysmon/Operational' on computer '.' System.InvalidOperationException:“计算机上的事件日志“Microsoft-Windows-Sysmon/Operational”。 does not exist.'*不存在。'*

I found a solution here It is using System.Diagnostics.Eventing.Reader namespace.我在这里找到了一个解决方案它使用 System.Diagnostics.Eventing.Reader 命名空间。 However, I cannot seem to get this anywhere in my system or in the package manager.但是,我似乎无法在我的系统或 package 管理器中的任何地方得到这个。

Also, since many are claiming that the name of the log may be incorrect.此外,由于许多人声称日志的名称可能不正确。 Following is the screenshot of it:以下是它的截图: 在此处输入图像描述

Are you sure you are using the correct naming semantics.您确定您使用的是正确的命名语义吗? This is the error you get if a log source has been created with that name on that machine.如果在该机器上使用该名称创建了日志源,则会出现此错误。 As alternative you can use System.Management and query directly.作为替代方案,您可以直接use System.Management和查询。

Below is a function I have used in the past...NOTE: ServerLogEntry is an object from my application domain.下面是我过去使用过的 function...注意: ServerLogEntry是来自我的应用程序域的 object。

public List<ServerLogEntry> GetLastestServerLogEntries(int number)
{
    string logSource = this.GetEventLogSourceName();
    string Query = String.Format("SELECT * FROM Win32_NTLogEvent WHERE Logfile = 'Application' AND SourceName='{0}'", logSource);

    List<ServerLogEntry> logs = new List<ServerLogEntry>();

    ManagementObjectSearcher mos = new ManagementObjectSearcher(Query);

    foreach (ManagementObject mo in mos.Get().Take(number).ToList())
    {
        ServerLogEntry log = new ServerLogEntry();
        log.Category = Convert.ToInt32(mo["Category"]);
        log.CategoryString = SafeString(mo["CategoryString"]);
        log.ComputerName = SafeString(mo["ComputerName"]);
        log.EventCode = Convert.ToInt32(mo["EventCode"]);
        log.EventIdentifier = Convert.ToInt32(mo["EventIdentifier"]);
        log.EventType = Convert.ToInt32(mo["EventType"]);
        log.EventTypeName = this.ConvertLogEventType(log.EventType);
        log.LogFile = SafeString(mo["LogFile"]);
        log.Message = SafeString(mo["Message"]);
        log.RecordNumber = Convert.ToInt32(mo["RecordNumber"]);
        log.SourceName = SafeString(mo["SourceName"]);
        log.TimeGenerated = this.ConvertLogDateTime(SafeString(mo["TimeGenerated"]));
        log.TimeWritten = this.ConvertLogDateTime(SafeString(mo["TimeWritten"]));
        log.Type = SafeString(mo["Type"]);
        log.User = SafeString(mo["User"]);
        logs.Add(log);
    }
    return logs.OrderByDescending(p => p.TimeGenerated).ToList();
}

private string SafeString(object propertyValue)
{
    return (propertyValue != null) ? propertyValue.ToString() : "";
}

private string ConvertLogEventType(int eventType)
{
    switch (eventType)
    {
        case 1: return "Error";
        case 2: return "Warning";
        case 3: return "Information";    
        case 4: return "Security Audit Success";
        case 5: return "Security Audit Failure";
        default: return "Unknown";
    }        
}

private DateTime ConvertLogDateTime(string entryTimeGeneratedString)
{
    //TimeGenerated, for example: 20071107135007.000000-300
    //
    //                            yyyy mm dd hh mm ss.milisec 
    //                            0123 45 67 89 01 23
    // convert to new DateTime(yyyy,month,day,hour,minute,seconds)

    return new DateTime(Convert.ToInt32(entryTimeGeneratedString.Substring(0, 4)),
                        Convert.ToInt32(entryTimeGeneratedString.Substring(4, 2)),
                        Convert.ToInt32(entryTimeGeneratedString.Substring(6, 2)),
                        Convert.ToInt32(entryTimeGeneratedString.Substring(8, 2)),
                        Convert.ToInt32(entryTimeGeneratedString.Substring(10, 2)),
                        Convert.ToInt32(entryTimeGeneratedString.Substring(12, 2)));
}

Here is the native structure returned -->这是返回的本机结构 -->

/*class Win32_NTLogEvent
{
    uint16   Category;
    string   CategoryString;
    string   ComputerName;
    uint8    Data[];
    uint16   EventCode;
    uint32   EventIdentifier;
    uint8    EventType;
    string   InsertionStrings[];
    string   Logfile;
    string   Message;
    uint32   RecordNumber;
    string   SourceName;
    datetime TimeGenerated;
    datetime TimeWritten;
    string   Type;
    string   User;
};*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用C#和Windows服务创建无敌Windows应用程序 - How to create invincible windows application using c# and windows services 如何使用Windows服务弹出应用程序C# - How to pop up application using windows services c# 如何从源视图(aspx)中的C#按钮添加事件处理程序 - How to add an event handler for events from button in C# from source view (aspx) C#:如何在Windows应用程序中从Web浏览器读取数据 - C#: How to read data from webbrowser in a windows application 如何从c#中的windows表单应用程序中读取xml文件 - How to read xml file from windows form application in c# 如何使用C#在Windows应用程序中的SessionSwitch事件中调用方法? - How do I call a method from SessionSwitch event in windows application using c#? 如何使用C#4.0从Windows应用程序的客户端中读取服务器中的文本文件 - how to read text file in server from client in windows application using C# 4.0 如何使用 Windows Application Driver / C# 从 TreeItem / DataItem 读取值? - How to read the value from a TreeItem / DataItem using Windows Application Driver / C#? 如何使用c#监控windows服务 - How to monitor windows services using c# 在 C# windows 服务中使用异步事件处理程序 - Using async event handlers in C# windows services
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM