Jimmy
Jimmy

Reputation: 145

In tcl, how to read a log file that is continuously updated?

I want to monitor a log file that is continuously updated by another program. I want to read the log file every 10 mins, how to realize it? And is it possible to just read updated contents every time?

Upvotes: 1

Views: 547

Answers (1)

Donal Fellows
Donal Fellows

Reputation: 137727

Assuming that the log file is only being appended to, you can simply save where you are before closing it and restore that location back when you reopen. Saving the location is done with chan tell and restoring the location is done with chan seek.

proc processLogLine {line} {
    # Write this yourself...
    puts "got log line '$line'"
}

proc readLogTail {logfile position} {
    # Read the tail of the log file from $position, noting where we got to
    set f [open $logfile]
    chan seek $f $position
    set tail [read $f]
    set newPosition [chan tell $f]
    close $f
    # If we read anything at all, handle the log lines within it
    if {$newPosition > $position} {
        foreach line [split $tail "\n"] {
            processLogLine $line
        }
    }
    return $newPosition
}

proc readLogEvery10Minutes {logfile {position 0}} {
    set newPosition [readLogTail $logfile $position]
    set tenMinutesInMillis [expr {10 * 60 * 1000}]
    after $tenMinutesInMillis [list readLogEvery10Minutes $logfile $newPosition]
}

readLogEvery10Minutes /tmp/example.log
vwait forever

Note the vwait forever at the end; that runs the event loop so that timer callbacks scheduled with after can actually be run. If you've already got an event loop going elsewhere (e.g., because this is a Tk application) then you don't need the vwait forever.

Upvotes: 3

Related Questions