The other day, there was a post on one of the mailing lists that I follow about accessing the Windows Event Logs. I thought that was an interesting topic, so I went looking for examples and found a pretty nice example on ActiveState. In this article, you’ll find out what I discovered.

It’s probably easiest to just jump right into the code. Note that the only thing other than Python that you will need is the PyWin32 package. Once you’ve got that, then you can follow along:

There are a couple potential caveats to this type of scripting. I tested this code as an Administrator on my PCs and as a Domain Administrator at work. I did not test it as any other type of user. So if you have problems getting this code to run, check your permissions. I tested this from Windows XP and Windows 7. The UAC doesn’t appear to block this activity on Windows 7, so that made it just as easy to use as XP did. However, Windows 7’s events had some unicode in the message portion of the code whereas XP did not. Watch out for that and handle it accordingly.

Anyway, let’s unpack this script and see how it works. First we have a number of imports. We use the codecs modules to encode the log file in utf-8 just in case there’s some sneaky unicode in the message. We use PyWin32’s win32evtlog module to open the event log and pull information out of it. According to the article I mentioned at the beginning, to get all the events from the log, you need to call win32evtlog.ReadEventLog repeatedly until it stops returning events. Thus, we use while loop. Inside the while loop, we use a for loop to iterate over the events and extract the event ID, record number, event message, event source and a few other tidbits. We log it and then we exit the for loop and the while loop calls the win32evtlog.ReadEventLog again.

We use the traceback module to print out any errors that occur during the script’s run. And that’s all there is to it!

Wrapping Up

As you can see, using the PyWin32 package is easy. If you get stuck, it has some great documentation. If that documentation isn’t good enough though, you can fall back on MSDN instead. PyWin32 is a light wrapper around Windows’ API, so using MSDN’s instructions is fairly simple. Anyway, I hope you learned a lot and will find it helpful.