Flog

Summary

flog is a script to Follow the latest log matching the filename prefix supplied, outputting updates to it as they arrive.

Synopsis

flog filename-prefix

Description

This works like tail -f but switches automatically to the newest file whose name starts with the prefix supplied. I wrote this for when I need to watch the latest log in a series whose names contain a date/time-stamp or sequence number CGM.

#!/usr/bin/env tclsh

if {$argc != 1 } {
    puts "Usage: $argv0 <filename-prefix>"
    puts "- Follow LOG files matching prefix, outputting contents of newest as updated"
    exit
}

proc newest prefix {
    set lt 0
    set lf {}
    foreach f [glob -nocomplain -types {f r} -- $prefix*] {

        if {[catch {file mtime $f} t]} continue
        if {$t > $lt} {
            set lt $t
            set lf $f
        }
    }
    return $lf
}

set prefix [lindex $argv 0]

set nf [newest $prefix]
while 1 {

    while {$nf eq {}} {
        after 1000
        set nf [newest $prefix]
    }

    set cf $nf
    puts stderr "Following: $cf"
    set if [open $cf]

    while {$nf eq $cf} {
        if {[file size $cf] < [tell $if]} break
        puts -nonewline [read $if]
        after 1000
        set nf [newest $prefix]
    }
    puts -nonewline [read $if]
    close $if
}