Click here to Skip to main content
Click here to Skip to main content

A C# implementation of the Tail -f command

, 4 Dec 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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:
 
 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:
 
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)

Share

About the Author

No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.141216.1 | Last Updated 4 Dec 2010
Article Copyright 2010 by Felice Pollano
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid