Click here to Skip to main content
15,883,883 members
Articles / General Programming / Tools
Tip/Trick

A C# implementation of the Tail -f command

Rate me:
Please Sign up or sign in to vote.
4.83/5 (5 votes)
4 Dec 2010CPOL2 min read 21.3K   5  
Tailf is a little utility that mimics the tail -f unix/linux command. Pratically, given a test file it displays the latest (n) lines and continues to dump any consequent file write. This is useful when we need to monitor textual log files. The utility is expecially designed to deal with log4net[^] rolling file appender, avoiding to lock the file so the roll-over happen without pains. The core part is a class ( Tail ) that can possibly be used in other applications in order to monitor file writes.

Using the code as a utility class is as simple as istantiating the main class:

C#
Tail tail = new Tail("filename", nOfLines);
    tail.LineFilter = "filter expr" //can be null or empty;
    tail.Changed += new EventHandler(tail_Changed);
    tail.Run();


The event handler receives the portion of text added or, at startup, the ending lines of the target file. In the startup phase, an event will be fired for each trailing line. A sample for the handler is the following:

C#
void tail_Changed(object sender, Tail.TailEventArgs e)
        {
            Console.Write(e.Line);
        }


An optional filter, written as a .NET regular expression[^] can be specified in order to filter all the lines that contains at least one match to that expression.

Using the utility is even easier since is a plain old command line:

tailf mylog.txt continuously dumps on the console the content of mylog.txt as soon as new lines are written into it.

tailf -n:15 mylog.txt continuously dumps on the console the content of mylog.txt as soon as new lines are written into it. At startup, the last 15 lines are dumped.

tailf mylog.txt -f:ERROR continuously dumps on the console the content of mylog.txt as soon as new lines are written into it. Just lines containing "ERROR" are shown.

tailf mylog.txt -f:"ERROR|WARN" continuously dumps on the console the content of mylog.txt as soon as new lines are written into it. Just lines containing "ERROR" or "WARN" are shown; double quotes are necessary since | is a special char in the command shell.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Italy Italy
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --