#!/usr/bin/perl
# filter and color an Apache 'combined' CustomLog access_log
# usage: tail -f access_log | ./logfilter.pl
#
# Matt Sparks, 20050819
# http://f0rked.com
use strict;
use warnings;

# Array of file extensions to ignore
my @filter_extensions=(); # ("jpg","ico");

sub c {
    my($text,$color)=@_;
    $color="normal" if !$color;
    my %colors=(
        "red"           => "[0;31m", 
        "light_red"     => "[1;31m",
        "green"         => "[0;32m", 
        "light_green"   => "[1;32m", 
        "yellow"        => "[0;33m", 
        "light_yellow"  => "[1;33m",
        "blue"          => "[0;34m", 
        "light_blue"    => "[1;34m", 
        "magenta"       => "[0;35m",
        "light_magenta" => "[1;35m",
        "cyan"          => "[0;36m", 
        "light_cyan"    => "[1;36m", 
        "white"         => "[1;37m", 
        "normal"        => "[0m", 
        "black"         => "[0;30m",
        "gray"          => "[1;30m",
        "brown"         => "[0;33m", 
        "bold"          => "[1m", 
        "underline"     => "[4m", 
        "reverse"       => "[7m", 
    );
    
    my $e=$colors{$color};
    return chr(27)."$e$text".chr(27)."[0m"; 
}

while(<STDIN>) {
    my($host,$logname,$user,$timestamp,$request,$code,$size,$referrer,$useragent);
    if (/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}) (.+?) (.+?) \[(.+?)\] \"(.+?)\" ([0-9\-]+) ([0-9\-]+) \"(.+?)\" \"(.+?)\"$/) {
        ($host,$logname,$user,$timestamp,$request,$code,$size,$referrer,$useragent)
            =($1,$2,$3,$4,$5,$6,$7,$8,$9);
    }
    else {
        print $_;
        next;
    }
    
    my $file=(split / /,$request)[1];
    my $print=1;
    for(@filter_extensions) {
        $print=0 if (substr($file,-length) eq $_)
    }
    printf qq(%s%s %s %s [%s] "%s" %s %s "%s" "%s"\n),
        " "x(15-length($host)),
        c($host),
        c($logname),
        c($user),
        c($timestamp),
        c($request,"white"),
        c($code,"light_yellow"),
        c($size),
        c($referrer,"light_green"),
        c($useragent,"light_cyan") if $print;    
}
