Logging Events in WSH
(Page 1 of 4 )
As you advance in your abilities to work with WSH you will find yourself writing more detailed and intricate code. Many of these scripts will be system administration scripts designed to run in the background. Thus, it can be very useful for your script to generate an event log.
Logging can be a highly detailed process. You may want to log the events that occur as your script runs; you may also want to log any errors that are encountered. These topics stretch far beyond the scope of a single article or series so I’ll only be giving you some basic techniques. It will be up to you to develop them for use in your own situation and for your own scripting style.
The most common method of logging is to a plain text file so we will be concentrating on that. The techniques would be similar if you wanted to log to a different type of file or even to a database. For lack of space, I’m not going into detail on how to manage the log file. Please take the time to read my “Reading Text Files in WSH” and “Writing Text Files in WSH” articles for more information.
The code samples in this article use predefined subroutines that I have created and made available for download. You can use or modify these scripts any way you like. Once you modify them to your liking, I suggest packaging them as a class so that you can reuse them in all of your scripts.
Basically, we need to accomplish a few basic steps in our script:
- Identify an action taking place.
- Determine if that action results in an error. If so,
- Make an entry for that error in our log file.
Each event will appear on its own line in our log file. A simple logging script might look like this:
Const logfile = "C:log.txt"
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objLog = objFso.CreateTextFile(logfile, True)
objLog.WriteLine "Logging Started "
objLog.WriteLine "Logging Ended "
In this example, all we’ve done is created a text file and written a few lines to it. This isn’t doing much good at this point. Trust me, it will all come together. The log.txt will look something like this.
Logging Started
Logging Ended
Okay, so this log file is a bit vague. We need to add some more information to this log if it’s going to be at all useful.
Next: Providing the Right Information >>
More Windows Scripting Articles
More By Nilpo/Developer Shed Staff Writer