Why does EventRecord.FormatDescription() return null?
Asked Answered
C

2

10

When using System.Diagnostics.Eventing.Reader.EventLogQuery to read events from the Windows Event Log, the EventRecord.FormatDescription() method sometimes returns null. Why is this? In the Event Viewer there are messages on the events which return null.

Cookout answered 23/9, 2011 at 15:45 Comment(0)
C
25

This is due to a bug in the .NET framework.

Basically what you need to do to work around this bug is to set the CurrentCulture to "en-US".

Example:

var beforeCulture = Thread.CurrentThread.CurrentCulture;

try
{
  Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");

  using (var session = new EventLogSession(ipOrAddress, userDomain, username, password, SessionAuthentication.Default))
  {
    var query = new EventLogQuery("System", PathType.LogName, queryString)
      {
        ReverseDirection = true,
        Session = session
      };

    using (var reader = new EventLogReader(query))
    {
      for (var record = reader.ReadEvent(); record != null; record = reader.ReadEvent())
      {
        // Read event records
        string message = record.FormatDescription();
      }
    }
  }
}
finally
{
  Thread.CurrentThread.CurrentCulture = beforeCulture;
}

This workaround is was very hard to find, so I thought I would document it a place where it will be indexed by Google. I found it in an old MS Connect case, but it has been closed with a status of "wont fix".

UPDATE: The bug has been reported for .NET 4 as well and the status is "Sent to Engineering Team for consideration" and comment alluding that the bug might be fixed in the next major .NET framework release (v5).

Cookout answered 23/9, 2011 at 15:47 Comment(2)
the last Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); should be Thread.CurrentThread.CurrentCulture = beforeCulture; to recover the previous culture, right?Thermosetting
Still same issue on .NET 4.5 in 2014. However, looking at the source code for FormatDescription it seems to be the native call to EvtFormatMessage that performs the formatting. Because event log message can be localized there is probably some interplay between the current culture of the thread and the locale of the event source. However, from a .NET perspective behavior is just confusing.Seaman
S
1

so i've been struggling with this for a few days too. I couldn't get it to work by changing the culture. In the end, i just used the raw data in the Properties property of the event record. The message data is in there, it's just not pretty. (just about good enough for my audit needs though :-))

Stets answered 5/2, 2015 at 14:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.