Search code examples
c#etwetw-eventsourcems-tracing-eventsource

How to store DateTime in EventSource via WriteEventCore


This is my current code:

[NonEvent]
    unsafe void InsertViaWriteEventCore(
        int eventId,
        DateTime startDateTime,
        DateTime endDateTime)
    {
        const int eventDataCount = 2;
        {
            EventData* data = stackalloc EventData[eventDataCount];
            data->DataPointer = (IntPtr)(&startDateTime);
            data->Size = sizeof(DateTime);
            data[1].DataPointer = (IntPtr)(&endDateTime);
            data[1].Size = sizeof(DateTime);

            WriteEventCore(eventId, eventDataCount, data);
        }
    }

But finally, in the events that are generated, i see "8/30/3617 5:00:00 PM" as startDateTime if i provide startDateTime as "8/30/2017 5:00:00 PM" to the method. It's always adding 1600 to the year.

I tried providing 8 as the size instead of sizeof(DateTime) and i still got the same result. I get the right date values if I change the dates to string and pass to writeeventcore as string as shown in the example here. What am i doing wrong here? What is the right way to pass DateTime via WriteEventCore?


Solution

  • When you use ‘EventData’ you have to use what ETW expects for a dateTime. This happens to be the windows FileTime format (which is a long that is the number of seconds from 1600)

    So to pass a DateTime to EventData, you have to do something like this.

    long startFileTime = startDateTime.ToFileTime();
    data->DataPointer = (IntPtr)(& startFileTime);
    data->Size = sizeof(long);