One of a tester’s key tools is the ‘tail’ command, especially when coupled with a -f which means that it will continually display the appended contents of a file providing a realtime view of a log for instance. Unfortunately this functionality does not exist for the windows logging system, Event Viewer. The consistency oracle says that are application should log to this system so we are out of luck when it comes to realtime views of logs without constantly refreshing the pane (which is pain).

This script illustrates how to tail the event log by using Python’s ability to tap into COM. A very handy thing indeed.

import wmi, sys, threading, pythoncom

class event_watcher(threading.Thread):
  def __init__(self):
    threading.Thread.__init__(self)

  def run(self):
    pythoncom.CoInitialize()
    c = wmi.WMI(privileges=["Security"])
    # If you want to limit the types of entries, add the 'Type=' argument
    # 'Type' can be Error, Warning, Information
    my_watcher = c.watch_for(notification_type="Creation", wmi_class="Win32_NTLogEvent")

    while True:
      event = my_watcher()

      # to see the full event log entry, uncomment below
      #print event

      # some handy information which could then be redirected to a
      # file and be easily parsed.
      print "%s in %s log: %s" %  (event.Type, event.Logfile, event.Message)

watcher = event_watcher()
watcher.start()

COM is massively powerful on windows-based systems, but it does add a platform dependency to your code. To be extra safe, I should have checked that it was on windows and failed gracefully, or just fall back to that platform’s tail but I trusted myself to not run it on a non-windows machine. Your audience will of course differ.

My original write-up of this recipe is here.