English 中文(简体)
• 如何在Windows的一个活动记录仪上添加多条目的线?
原标题:How to add multiple lines of EventData to an EventLog in Windows?
  • 时间:2011-10-08 01:44:27
  •  标签:
  • c#
  • event-log

目前,我能够使用以下代码设立视窗活动记录:

    string sSource;
    string sLog;
    string sEvent;
    sSource = "Sample App";
    sLog = "Application";
    sEvent = "Sample Event";

    if (!EventLog.SourceExists(sSource))
        EventLog.CreateEventSource(sSource,sLog);

EventLog.WriteEntry(sSource, sEvent, EventLogEntryType.Warning, 11111);

This creates a log in the Application Log. I want to add more than one line of data to the event in the event log so that while debugging I can parse the log directly for the problems. Also, I looked at some of the other logs in the Application logs and they seem to have a binary data field in them. I was not able to figure out as to how to write such a field because the above piece of code only adds an EventData field.

问题回答

一个线人应当这样做:

EventLog.WriteEvent("Application", new EventInstance(123, 0, EventLogEntryType.Information), new object[] { "Entry1" , "Entry2" });

申请是事件源,123是事件Id,0 = 事件类别。 也许需要首先检查事件来源的存在。

活动如何看待:

 <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
  <Provider Name="Application" /> 
  <EventID Qualifiers="0">1001</EventID> 
  <Level>4</Level> 
  <Task>0</Task> 
  <Keywords>0x80000000000000</Keywords> 
  <TimeCreated SystemTime="2015-07-12T21:26:07.000000000Z" /> 
  <EventRecordID>86554</EventRecordID> 
  <Channel>Application</Channel> 
  <Computer>YOUR_COMPUTER</Computer> 
  <Security /> 
  </System>
  <EventData>
     <Data>Entry1</Data> 
     <Data>Entry2</Data> 
  </EventData>
 </Event>

我对Prathap Kudpu的回答略感困惑,因此,我改写。

{
    string sSource = "Application Name";
    string sLog = "Application";

    EventInstance eventInstance = new EventInstance(0, 0, EventLogEntryType.Error);

    List<string> sEvent = new List<string>();
    sEvent.Add("Message 1");
    sEvent.Add("Message 2");
    sEvent.Add("Message 3");

    // Check if Event Source was created (Possibly throw error if you are not running with high privilege)
    if (!EventLog.SourceExists(sSource))
        EventLog.CreateEventSource(sSource, sLog);            

    EventLog.WriteEvent(sSource, eventInstance, sEvent.ToArray());
}

Basically, You create a list of string with the "Lines" or data you Want, create an EventInstance object, and Write an Event instead of WriteEntry

结果:

<EventData>
  <Data>Message 1</Data> 
  <Data>Message 2</Data> 
  <Data>Message 3</Data> 
</EventData>

如果你只想一个简单的<代码><Data name=“param1”>data</Data>架构,但如果你想要一个更加复杂的有效载荷,例如像你那样,就会下降:

<Data Name="BugcheckCode">4522044</Data> 
<Data Name="BugcheckParameter1">0x74006e00650076</Data> 
<Data Name="BugcheckParameter2">0x61007400610044</Data> 
<Data Name="BugcheckParameter3">0x610044003c003e</Data> 
<Data Name="BugcheckParameter4">0x4e002000610074</Data> 
<Data Name="SleepInProgress">7143521</Data> 
<Data Name="PowerButtonTimestamp">18577494495789157</Data> 
<Data Name="BootAppStatus">6750325</Data> 
<Data Name="Checkpoint">99</Data> 
<Data Name="ConnectedStandbyInProgress">true</Data> 
<Data Name="SystemSleepTransitionsToOn">1795187456</Data> 
<Data Name="CsEntryScenarioInstanceId">0</Data> 
<Data Name="BugcheckInfoFromEFI">true</Data> 

我不认为可以使用<代码>。 活动记录仪。 页: 1 ...... 壳牌:

New-WinEvent -ProviderName Microsoft-Windows-Kernel-Power -Id $evtID -Version 5 -Payload "<EventData><Data Name=""BugcheckCode"">210</Data><Data Name=""BugcheckParameter1"">0xffffc080b5744760</Data><Data Name=""BugcheckParameter2"">0x2</Data><Data Name=""BugcheckParameter3"">0x0</Data><Data Name=""BugcheckParameter4"">0xfffff80261641530</Data><Data Name=""SleepInProgress"">0</Data><Data Name=""PowerButtonTimestamp"">0</Data><Data Name=""BootAppStatus"">0</Data><Data Name=""Checkpoint"">0</Data><Data Name=""ConnectedStandbyInProgress"">false</Data><Data Name=""SystemSleepTransitionsToOn"">0</Data><Data Name=""CsEntryScenarioInstanceId"">0</Data><Data Name=""BugcheckInfoFromEFI"">false</Data><Data Name=""CheckpointStatus"">0</Data></EventData>"

因此,我排除了这一用途的代价,并反映了该守则。 我最后用几类助手,使你能够通过你要求的任何有效载荷:

public class EventLogHelper
{
        /// <summary>
        /// Taken from the source code of Microsoft.PowerShell.Commands.NewWinEventCommand
        /// </summary>
        /// <param name="providerName">"Microsoft-Windows-Kernel-Power"</param>
        /// <param name="eventId">41</param>
        /// <param name="version">5</param>
        /// <param name="payLoad"></param>
        public static void AddEventToEventLog(string providerName, long eventId, int version, string payLoad = "")
        {
            using (ProviderMetadata providerMetaData = LoadProvider(providerName))
            {
                EventDescriptor eventDescriptor = LoadEventDescriptor(providerMetaData, eventId, Convert.ToByte(version));


                ProcessRecord(providerMetaData, eventDescriptor, payLoad);
            }
        }

        private static ProviderMetadata LoadProvider(string providerName)
        {
            using (EventLogSession eventLogSession = new EventLogSession())
            {
                IEnumerable<string> providers = eventLogSession.GetProviderNames().OrderBy(s => s);
                foreach (string providerName2 in providers)
                {
                    if (string.Equals(providerName2, providerName, StringComparison.OrdinalIgnoreCase))
                    {

                        return new ProviderMetadata(providerName2);

                    }
                }
            }

            throw new Exception("Failed to find Microsoft-Windows-Kernel-Power provider");
        }

        private static EventDescriptor LoadEventDescriptor(ProviderMetadata providerMetadata, long id, byte version)
        {

            EventMetadata eventMetadata = providerMetadata.Events.First(f => f.Id == id && f.Version == version);

            return CreateEventDescriptor(providerMetadata, eventMetadata);

        }

        private static EventDescriptor CreateEventDescriptor(ProviderMetadata providerMetaData, EventMetadata emd)
        {
            long num = 0L;
            foreach (EventKeyword keyword in emd.Keywords)
            {
                num |= keyword.Value;
            }
            byte b = 0;
            using (IEnumerator<EventLogLink> enumerator2 = providerMetaData.LogLinks.GetEnumerator())
            {
                while (enumerator2.MoveNext() && !string.Equals(enumerator2.Current.LogName, emd.LogLink.LogName, StringComparison.OrdinalIgnoreCase))
                {
                    b = (byte)(b + 1);
                }
            }

            int parsedId = (int)emd.Id;

            if (emd.Id > ushort.MaxValue)
                parsedId = (ushort)emd.Id;

            return new EventDescriptor(parsedId, emd.Version, b, (byte)emd.Level.Value, (byte)emd.Opcode.Value, emd.Task.Value, num);
        }

        private static void ProcessRecord(ProviderMetadata providerMetadata, EventDescriptor eventDescriptor, string payload)
        {
            using (EventProvider eventProvider = new EventProvider(providerMetadata.Id))
            {

                eventProvider.WriteEvent(ref eventDescriptor, payload);

            }
        }
}

之后,可以称为:

string payload = @"<EventData><Data Name=""BugcheckCode"">210</Data><Data Name=""BugcheckParameter1"">0xffffc080b5744760</Data><Data Name=""BugcheckParameter2"">0x2</Data><Data Name=""BugcheckParameter3"">0x0</Data><Data Name=""BugcheckParameter4"">0xfffff80261641530</Data><Data Name=""SleepInProgress"">0</Data><Data Name=""PowerButtonTimestamp"">0</Data><Data Name=""BootAppStatus"">0</Data><Data Name=""Checkpoint"">0</Data><Data Name=""ConnectedStandbyInProgress"">false</Data><Data Name=""SystemSleepTransitionsToOn"">0</Data><Data Name=""CsEntryScenarioInstanceId"">0</Data><Data Name=""BugcheckInfoFromEFI"">false</Data><Data Name=""CheckpointStatus"">0</Data></EventData>";
EventLogHelper.AddEventToEventLog("Microsoft-Windows-Kernel-Power", 41, 5, payload);

如果你想增加更多的内容,你就可以简单地增加一种活力。 NewLine

  [Extension()]
    [MethodImpl(MethodImplOptions.NoInlining)]
    public void WriteInfo(string info)
    {
        try
        {
            MethodBase callingMethod = new StackFrame(1, true).GetMethod();
            string typeCalling = callingMethod.DeclaringType.FullName;

            string baseStr = "TYPE: {0}{3} METHOD: {1}{3} DETAIL: {2}";
            baseStr = string.Format(baseStr, new object[] {
                                                        callingMethod,
                                                        typeCalling,
                                                        info,
                                                        Environment.NewLine
    });

            EventLog.WriteEntry("entryName", baseStr, EventLogEntryType.Information);
        }
        catch
        {
            Debugger.Break();

        }
    }

I tried using using EventLog.WriteEntry(). However I was not successful. I found a solution for this problem. We can use logger.WriteEvent()

//Object of eventinstance.

EventInstance eventInstance= new EventInstance(0, 0) {EntryType =       EventLogEntryType.Warning};
//Array of string.Event data node is generated based on the array size.

string [] eventLog = EventLogger.BuildEventLog("EventLogSamples.WriteEventSample2","test");

//Need to specify the source

EventLog log = new EventLog {Source = "source"};
log.WriteEvent(eventInstance, eventLog);

我成功地撰写了多场活动。 数据如下:

- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
  <Provider Name="test" /> 

  </System>
- <EventData>
  <Data>EventLogSamples.WriteEventSample2</Data> 
  <Data>test</Data> 
  </EventData>
  </Event>

Please let me know if you find any issues. PK (Prathap Kudupu)

简言之,在您的致辞中,有条不紊的陈词。





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签