DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Sort Twiki Access Log By Hits Per Host Each Day

03.29.2011
| 3262 views |
  • submit to reddit
        Produce output like this:

Date: 19/Mar/2011
                           auckland.co.nz : 60343
                           tryphena.co.nz : 54
                              okupu.co.nz : 4
Date: 20/Mar/2011
                           auckland.co.nz : 60354
                           tryphena.co.nz : 49
                             claris.co.nz : 49
                        portfitzroy.co.nz : 32

#!/usr/bin/perl
#
#
#
use warnings;
use strict;

my @mon = qw( Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec );
my $mon;
@{$mon}{@mon} = (0..$#mon);

sub by_month {
    $mon->{$a} <=> $mon->{$b};
}

my $file = '/var/log/httpd/twiki/access.log';

my $users;

open (my $file_fh, $file) || die "Can't read '$file': $!\n";
while (defined (my $line = <$file_fh>)) {

    #
    #
    #
    my @line = split(/\s+/, $line);
    (my $date = $line[3]) =~ s|^\[(.*?):.*$|$1|g;
    my ( $day, $month, $year ) = split('/', $date);

    $users->{$year}->{$month}->{$day}->{$line[1]}++;

}
close $file_fh;

for my $year ( sort keys %{$users} ) {
    for my $month ( sort by_month keys %{$users->{$year}} ) {
        for my $day ( sort keys %{$users->{$year}->{$month}} ) {
            print "Date: $day/$month/$year\n";
            for my $host ( sort {
                $users->{$year}->{$month}->{$day}->{$b} <=> $users->{$year}->{$month}->{$day}->{$a}
            } keys %{$users->{$year}->{$month}->{$day}} ) {
                printf " %40s : $users->{$year}->{$month}->{$day}->{$host}\n", $host;
            }
        }
    }
}