Posts Tagged ‘logging’

Append Data Records to a Log File

How to store information to a log file.

Let’s say you want to keep a log of data or events in a file:

log-file: %log.txt

You can use this super-efficient method (and it’s worth remembering):

write/append log-file append mold/only data newline

What makes this efficient is that you are not reading the entire log file first, you are just appending a record (a line) to it.

Here the data can be a block of information or just a word or string. The mold converts anything to a REBOL-readable string with the /only removes the outermost brackets “[]”.  We then append a newline (line terminator) to it.

Many programmers create a function called log (as in the verb “to log”) that writes out log events this way. Here is one that also adds a time-stamp to the start of each line:

log: func [data] [
    write/append log-file rejoin [now " - " mold/only reduce data newline]

The reduce evaluates the data block in order to get the actual contents of variables.

You can now just write:

log "some event"


log ["some event" 1234]

Here’s how log might appear in a program that logs user account actions:

;The variables:
user: "Bob"
pass: "password"
action: 'new-user
account: 1234
log [user pass action account website]

If you open the log file using an editor, you’ll now see:

22-Sep-2010/9:32:54-4:00 - "Bob" "password" new-user 1234

In REBOL 3, if you want to shorten up the time-stamp a bit, you can use now/utc to just store the universal time. If you want to hide the password, there are a few ways to do so, but we’ll explain that later.

Reading and processing a log file is the subject of another blog, but here are a few hints, in case you’re interested:

log-lines: read/lines log-file  ; a block of lines (strings)
foreach line log-lines [probe load line]

And, here’s another:

log-data: load log-file ; a continues block
parse log-data [
    some [copy line [skip [to date! | to end]] (probe line)]
Categories: Storing Data Tags: , , ,