Channels ▼
RSS

Customizing Event Log Categories


.NET_template

One of my pet peeves in the .NET framework is the EventLog class. This class is sufficient for reading events from the event log, but it is very bad for generating events. The implementation in .NET 1.1 is just an interim attempt at trying to produce something acceptable. Going into the details could make this column very long; instead, I will focus on one topic—event log categories.

If you open the event log viewer (eventvwr.msc on XP), you'll see that one column is marked Category. Usually this column contains the string None, but sometimes you'll see a descriptive string (for example, on my machine MSDTC and Windows Update provide events that have categories). The descriptive string is usually associated with a single event log source, but the event log does provide some default categories. To generate an event with a category using the .NET EventLog class, you call one of the WriteEntry overloads that takes a 16-bit parameter; for example, this is one of the static methods:

int pointlessID = 0;
short catID = 1;
EventLog.WriteEntry("mySource", "The .NET EventLog is horrible",
   EventLogEntryType.Information, pointlessID, catID);

I deliberately use the name "pointlessID for the eventID parameter because with the implementation of the WriteEntry method on the EventLog class in v1.1, this parameter has lost much of its meaning. The final parameter of this method is the category ID; however, if you open the event log viewer, you'll see that the category column for this event will have the description "Devices. The reason is that the event log viewer cannot find the categories for this particular source and, hence, uses the default categories. These default categories are defined as follows:

0 None
1 Devices
2 Disk
3 Printers
4 Services
5 Shell
6 System Event
7 Network

If you create an event with a category higher than 7, then the category will be shown as a number in parenthesis, for example, (9).

So how do you provide your own categories? Well, it's surprisingly easy. The following key contains information about each of the sources that can generate events in the Application log.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application

You will find that when you run the code above, there will be a key for mySource. The WriteEntry method will have created this key for you and will have added a single value, EventMessageFile. This value gives the path to a (Win32) resource-only DLL that contains format strings-for a .NET source, this file will always be EventLogMessages.dll in the framework directory. This DLL contains 65,000 format strings that look like this:

%1

That is, no formatting is performed whatsoever. What's the point? I don't know; this is why I called the event ID "pointless-it is a complete mess. Back to categories. You can provide your own category descriptions if you provide a DLL with format strings and refer to this file in the CategoryMessageFile value. There is also a value called CategoryCount, which gives the number of categories defined in the resource file.

Here is a method that will add the necessary values to the registry:

static void CreateSource(string name, string msgFile, int count)
{
   if (!EventLog.SourceExists(name))
      EventLog.CreateEventSource(name, "Application");

   RegistryKey hklm = Registry.LocalMachine;
   string keyName = @"SYSTEM\CurrentControlSet\Services"
      + @"\EventLog\Application\"
      + name;
   RegistryPermission perm = new RegistryPermission(
      RegistryPermissionAccess.Create|RegistryPermissionAccess.Write, 
      @"HKEY_LOCAL_MACHINE\"+keyName);
   RegistryKey el = hklm.OpenSubKey(keyName, true);
   string file = Environment.CurrentDirectory + @"\" + msgFile;
   try
   {
      el.SetValue("CategoryMessageFile", file);
      el.SetValue("CategoryCount", count);
   }
   catch(Exception){}
}

Note that you must have the RegistryPermission to be able to write to the registry. You also need to open the key with write access, which is why I call OpenSubKey with true as the second parameter. I explicitly call CreateEventSource so that I know that the appropriate keys exist.

To create the resource file, you use the Win32 tool, mc.exe, which can be found in the Common7\Tools\Bin folder in the Visual Studio .NET folder. (This tool can also be found in the Platform SDK.) I won't go into the details of the format of the source files for this tool, but basically the entries look like this:

MessageId=0x1
Language=English
Category String
.

The first entry is the category ID, the second one is the localization, and after that is the actual string (in this case "Category String) followed by a period on a single line. Note that if the category ID is zero, then the category string will always be None, so in your message file you should use MessageId values of 1 or more.

The message compiler compiles this to a binary resource (.bin) file, and it also creates a resource script (.rc) that includes the binary resource as a resource of type 11 (RT_MESSAGETABLE). This should be compiled to a resource file (.res) with the message compiler rc.exe. This tool can be found in the same folder as the message compiler in the Platform SDK and in the VC7\bin folder. Finally, this resource should be added as a Win32 resource to a DLL. To do this you have two choices. If you have access to the Win32 linker (link.exe, in the VC7\bin folder), then you can create this file with the following:

link /dll /noentry /machine:X86 /out:msgs.dll msgs.res

This will create a DLL called msgs.dll that only contains the resource in msgs.res.

If you don't have access to the linker then you can use the .NET linker (al.exe) and use the /win32res switch. However, this tool mandates that you use /embed, /link, or provide a .NET module on the command line, so you have to provide a dummy .NET resource. For example:

echo dummy > dummy.txt
al /win32res:msgs.res /t:lib /out:msgs.dll /embed:dummy.txt,dummy
del dummy.txt

Note that when you have registered a category message file, you have to restart the event log viewer to pick up the changes. Additionally, note that you could also use this trick to replace the reference to the horrible EventLogMessages.dll with a path to a file that has real event log format strings, but to use these format messages you'll have to call the Win32 ReportEvent through p/invoke.

The download for this article gives an example of adding categories to your event messages.


Richard Grimes speaks at conferences and writes extensively on .NET, COM, and COM+. He is the author of Developing Applications with Visual Studio .NET (Addison-Wesley, 2002). If you have comments about this topic, Richard can be reached at richard@richardgrimes.com.


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.
 

Video