ColorizeTail

Tail avec coloration en PHP.

<?php
 
// -----------------------
// Test 1, colorize.php
// Colorisation de stdin
// Bol
//
// exemple
// tail  -f mylog.log | php -q colorize.php
//
// auteur: Bol <Bol.ML@wanadoo.fr>
 
/* ======== Code ANSI ========
0       Reset all attributes
1       Bright
2       Dim
4       Underscore
5       Blink
7       Reverse
8       Hidden
 
       Foreground Colors
30      Black
31      Red
32      Green
33      Yellow
34      Blue
35      Magenta
36      Cyan
37      White
 
       Background Colors
40      Black
41      Red
42      Green
43      Yellow
44      Blue
45      Magenta
46      Cyan
47      White
============================ */
 
// regexp d'exclusion, mettre $exclude=null si aucun
$exclude = array(
                 '/GET \/images/i'
              );
 
// regexp de colorisation, voir codes ANSI
$color = array(
                '/GET \/index/' => '31',
                '/GET \/page.+id=[0-9]/U' => '37;41'
            );
 
$reg = array();
$rep = array();
 
foreach( $color as $k => $v )
{
 $reg[] = $k;
 $rep[] = "\x1B[{$v}m\\0\x1B[0m";
}
 
$in = fopen( 'php://stdin', 'r' );
$ex = false;
while( !feof( $in ) )
{
$l = fgets( $in, 4096 );
if( $exclude )
  foreach( $exclude as $ex_reg )
    if( $ex = preg_match( $ex_reg, $l ) )
       break;
if( !$ex )
  echo preg_replace( $reg, $rep, $l );
$ex = false;
}
 
fclose( $in );
 
?>