The parameter is incorrect – at System.Diagnostics.EventLog.InternalWriteEvent

I’ve recently encountered this error in my error logging component. Naturally, an exception inside an exception handler is rarely a good thing and I was left scratching my head about what was going wrong.

There are numerous schools of thought in regards to what the best approach is to logging application errors. Consumer issues aside, when applications are administered by me or my team, I prefer using Windows event log or a file. In fact, I’ve written a general purpose library that allows an error, warning, or info to be logged in event log, text file, or displayed via user interface.

The error gracing the title of this post occurs during EventLog.WriteEntry function call. Actually, the exception is in the scope of the Win32Exception and this can occur during WriteEntry call on a couple of occasions. Most notably, when the Event Log is full (in this case, you cal Clear the log and try the re-write). However, this was not the case for me.

Another notable case for this exception is when the message exceeds the maximum message size, which is in the vicinity of 32000 odd bytes. The reason I am not specifying an exact number, is that apparently the actual maximum message size is tied to the length of the machine name and event log source that is writing the message.

Sadly, this too was not the cause of the error message.

Finally, after some frustration and trial and error I determined that the error occurred due to the name of the event log source. What’s frustrating is that the code below works just fine:

m_oEventLog = new EventLog();
if (!EventLog.SourceExists(m_strClientName))
      EventLog.CreateEventSource(m_strClientName, m_strLogName);
m_oEventLog.Source = m_strClientName;

So above we are checking if the Event Log source identified by m_strClientName already exists, and if not, we create it. So far so good.

Oddly, this seems to go without a hitch even when m_strClientName is invalid!. However, when a call comes in to actually write an entry:

m_oEventLog.WriteEntry(strEventLogString, MsgType);

The exception is thrown…

Turns out, that you cannot have certain characters as part of your m_strClientName.. Do not use quotes (‘) or less than/grater than symbols (‘>’/'<‘)…

i.e m_strClientName = “<Logger Test>” is NOT valid and will result in an exception…

Interestingly, if you look at the registry, the event source key is created just fine. It is only upon write that the call fails. I imagine there are other “special” characters that cause this error as well.

For now, file under WTF..

Cheers!