Best practices for creating your own Windows Event Log

When using components as a monitor, logging your own Windows Event Logs can sometimes be advantageous. If you take a simple IF statement script, you have two possible outcomes: pass or fail. However, in some cases, a third outcome is required (ELSE). With the standard monitoring components, where you check for an exit code (0 or 1), the third outcome cannot be handled. Therefore, you need some way to create our own Windows events.

Creating your own Windows Event Log

The following PowerShell code can be used to create a new Windows Event Log:

$logFileExists = Get-EventLog -List | Where-Object { $_.LogDisplayName -eq "Datto" }

if (-not $logFileExists) {
	New-EventLog -LogName "Datto" -Source "DRMM"
	Write-EventLog -LogName "Datto" -Source "DRMM" -EntryType Information -EventId 1 -Message "Datto event log created by the DRMM Agent"
}

The preceding example first checks if a Windows Event Log called Datto exists and creates it if not. You can then log an event to confirm you can write to the new log.

Logging events

Now that you have your new event log, you can add the following PowerShell line to your custom components and component monitors:

Write-EventLog -logname Datto -source DRMM -entrytype Warning -eventid 2 -message "insert custom event message here"

NOTE  Select a unique event ID for each event message type you want to log.

NOTE  Replace insert custom event message here with the text to include in the Windows event message body (the payload).

Explanation of switches

  • -logname: The name of the Windows Event Log you wish to write to.
  • -source: A valid source for the new event. Sources are set up when you create the new event log.
  • -entrytype: Information, Warning, or Error.
  • -eventid: The custom event ID you wish to use.
  • -message: The event message text.

Using this method allows you to create custom events based on the success or failure of the component you are running. For example, you might choose to log custom events like this:

Script worked – log Event ID 1 – information event type
Script has warnings – log Event ID 2 – warning event type
Script failed – log Event ID 3 – error event type

Monitoring for custom events

Now that you are writing your own custom events, it is possible to use the standard Windows Event Log monitor to check for these events.