Friday, April 07, 2006

 

A better Log function

Yesterday, I posted a function for creating a log file. In testing that function, I used another function called log to write messages to the log file. This morning, I've created a slightly more flexible version of that function. In this version, the date-stamping is optional and the header message is passed as a parameter to the function.

This log function writes messages to the designated text file (File object: aFile). If the file in question does not yet exist, it is created and if requested by the header (string) and incDate (boolean) arguments, the log file is date-stamped and a header is posted.
function log(aFile, message, header, incDate) {
  var today = new Date();
  if (!aFile.exists) {
    // make new log file
    aFile.open("w");
    if (incDate) {
      aFile.write(String(today));
    }
    if (header != null) {
      aFile.write(header);
    }
    aFile.close();
  }
  aFile.open("e");
  aFile.seek(0,2);
  aFile.write("\n" + message);
  aFile.close();
}
Note that if the first call includes neither a header nor a request to stamp the file with the date, the generated text file will start with a blank line. One approach for dealing with this would be to not include the "\n" before each message, leaving it to the user to include them. I'll see how I get on with it in its current form. So far, I've always wanted a header and date-stamp, so it has been something of a non-issue.

Once log has been called the first time to kick things off, the third and fourth arguments can be ignored; indeed, they are ignored by the function, so there's no point in including them. If you want to time-stamp the messages, you can include the time string in the message parameter.

At the end of a script that created a log file, I have something like this:
if (logFile.exists) {
  logFile.execute();
} else {
  errorExit("Script ended with no log file.");
}
This causes the log file to be displayed in the editor of your choice (that which you have associated with .txt files) if it was created by running the script, or you get the alert message (provided by the errorExit() function I've posted previously).

Comments: Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?