Writing a Log File

Author: Carl Sassenrath
Return to REBOL Cookbook

Applications, utilities, and net monitors often keep a log file that notes special events that have occurred. Here is a simple and fast logging function that I use quite often.

    log-data: func [file data] [
        data: append trim/lines reform [now remold data] newline
        attempt [write/append file data]

This function will accept any type of data for logging. The data will be molded into a single line string and appended to the end of the log file. For example, this code logs a string:

    log-data %log.txt "Opened"

If the data is a block, it will be evaluated first. This logs a string and a version number:

    log-data %log.txt ["version" system/version]

Now, look at the log.txt file to see what it did:

    print read %log.txt

Note that the log function also writes the log in REBOL readable format. This makes it easy to load and analyze using REBOL.


In the LOG-DATA function above the ATTEMPT is used to avoid a program blowout should the log file encounter an error during the WRITE. For example, if the log file is write protected or system is out of disk space, the error will be ignored.

2006 REBOL Technologies REBOL.com REBOL.net