How to add multiple lines of EventData to an EventLog in Windows?

Anoop picture Anoop · Oct 8, 2011 · Viewed 11.6k times · Source

I am able to currently create a Windows Event Log using the following code:

    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.

Answer

batbaatar picture batbaatar · Jul 16, 2015

One liner should be like this:

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

Here Application is event source, 123 is the event Id and 0 = NONE is event category. You may need to check the existence of the event source first.

This is how the event looks like:

 <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>