Windows event log custom source tips

Good-old Windows event logs are a great location to write events for automation tools and scripts. It may not be flashy, but it provides key functionality for service engineering teams:

  • It’s easy to register custom sources for your applications.
  • It has configurable log size and rollover options so you don’t need to worry about handling log file cleanup.
  • Log forwarding tools make it easy to examine or monitor logs in a central location.
  • Supports task/automation triggers.

Below are a few tips for registering custom sources.

Tip 1: Register sources early, if possible

From the MSDN doc on CreateEventSource():

Create the new event source during the installation of your application. This allows time for the operating system to refresh its list of registered event sources and their configuration. If the operating system has not refreshed its list of event sources, and you attempt to write an event with the new source, the write operation will fail.

I have seen a handful of cases where a custom log was not immediately available to write to. This is an odd timing thing and is pretty difficult to reproduce. Most of the time it just works immediately. Have a backup plan to handle this edge case.

Tip 2: C#/.NET or PowerShell code can quickly setup a custom source

Functionally, it doesn’t matter which one you choose. Under the hood, the PowerShell code just calls .NET function anyway. Examples:

// void return
System.Diagnostics.EventLog.CreateEventSource("CoolCustomSource", "Application");
# void return
New-EventLog -LogName Application -Source "CoolCustomSource"

Tip 3: Use .NET to check if a custom source already exists.

Problem: PowerShell doesn’t have a Test-EventLogSourceExists (or similar) cmdlet. To make matters slightly worse, if you run this:

New-EventLog -LogName Application -Source "CoolCustomSource"
Get-EventLog -LogName Application -Source "CoolCustomSource"

The above code throws an exception that the source doesn’t exist, even though you just created it. The reason is that no events have been written using the source yet.

Instead, you have to call the .NET method directly to check if the source exists.

// returns bool
# returns bool

One thought on “Windows event log custom source tips

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s