One of the things I miss when testing on windows is the inability to tail the default OS log file to make sure things are behaving as they should. While looking for something completely different over the weekend, I stumbled upon Tim Golden’s WMI python module. One of the examples from Tim’s WMI Cookbook does just that.

With a bit of hacking, I’ve now got windows event viewer tailing script.

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"])
    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

      print "%s in %s log: %s" % (event.Type, event.Logfile, \\
                                  event.Message)

watcher = event_watcher()
watcher.start()

So some usage notes:

  • The event = my_watcher()

    blocks while waiting for the next event. Eventually I will fix this so the main thread can control it. But not now. If anyone knows how, the goal is to have KeyboardInterrupt shut down things cleanly.

  • Run this from a window you don’t mind losing as you stop it by closing it. (see the first point)
  • If you want to limit the amount of input you recieve, you can specify the type of message you want. For example: ``` my_watcher = c.watch_for(notification_type=”Creation”,
    wmi_class=”Win32_NTLogEvent”)
        
      would become
        
    

    my_watcher = c.watch_for(notification_type=”Creation”,
    wmi_class=”Win32_NTLogEvent”,
    Type=”information”) ```