Create a simple AppleScript logging function

Dec 20, '04 08:55:00AM

Contributed by: leenoble_uk

As a sometime AppleScript user, I've generally used the display dialog function to display variables when developing. I'm not an AppleScript expert by any means, and it usually takes me a lot of trial and error to get things working the way I want. The problem with all those potential display dialogs is that they interrupt the flow of the script, and you have to go around commenting them out or removing them afterwards. Yes, I know about the Event log in the Script Editor, but it's not always terribly clear at which point in the script something occurred. It's also nice to have custom messages from time to time. My idea was instead of popping up a dialog box, I would write data to an external file.

First, I wanted to make an external AppleScript file for storing commonly used functions. I've never done this before, but eventually discovered how. First create a new AppleScript and add these four lines:

on log_event(themessage)
  set theLine to (do shell script ¬
   "date  +'%Y-%m-%d %H:%M:%S'" as string) ¬
   & " " & themessage
  do shell script "echo " & theLine & ¬
   " >> ~/Library/Logs/AppleScript-events.log"
end log_event
Save this as Common code.scpt in your user's Library -> Scripts folder. You can close that file now and forget about it. Next take any AppleScript you have developed, or start a new one, and add this line to the top of the script:
set commonScript to load script alias ¬
 ((path to library folder from user domain as string) ¬
 & "Scripts:Common code.scpt")
Now whenever you want to record an event, you just use the following line instead of display dialog:
log_event("Put your string here") of commonScript
Apart from stopping interruptions, this has the advantage that you needn't comment out these lines afterwards (as long as it's for your own use). This is also a good way to monitor scripts which you may have running automatically via cron. You can record both successes and failures in any script you like, so if something goes wrong in your absence, then you can look back at the log (saved in your user's Library/Logs folder, and called AppleScript-events.log), and find out where and when things went awry.

There might well be a built-in method for doing things like this, but like I said I'm a hit-and-miss AppleScript developer, and I'm not aware of anything myself. I stand to be corrected...

Comments (6)


Mac OS X Hints
http://hints.macworld.com/article.php?story=2004121710493371