Wednesday, April 29, 2009

tail -F in PHP

I'm currently writing a PHP script that pushes live log data to the front-end UI. I'm using a streaming Comet model such that my back-end would update the front-end's screen every time the log file is updated.

Unix has a nifty utility called 'tail' that can continuously monitor a file for updates and display them to standard output (which is the usually the monitor). By capturing tail's output via popen(), I was able to make a log file viewer with just a few lines:

exec("/usr/bin/killall tail");
// execute myapp in the background and redirect all of its output to logfile
exec("/usr/local/bin/myapp > /var/log/mylogfile.log 2>&1 &");

$handle = popen("/usr/bin/tail -F /var/log/mylogfile.log 2>&1", 'r');
while(1) {
$buffer = fgets($handle);

if (trim($buffer) == '-- ok') { // this string signifies end of execution
exec("/usr/bin/killall tail");
} else {
echo trim($buffer);
// if you're using Comet, push output to the stream here

Very cool...

1 comment:

Alex Gilmor said...

Thanks a lot!!!
This way it finally works without ajax, which I would have hated to use in my current task.