Mae向きなブログ

Mae向きな情報発信を続けていきたいと思います。

アクセス解析(Squid)

Squidアクセスログを元に,アクセスランキングを生成するPerlスクリプトを書いてみました。以下のことを考慮。

  • ページ内に,画像ファイルが多数あるサイトがアクセスランキングの上位にならないように,text/htmlだけを集計する。
  • www.yahoo.co.jp,search.yahoo.co.jpやauctions.yahoo.co.jpへのアクセス回数をyahoo.co.jpとしてカウントするようにする。
#!/usr/bin/perl
#
use strict;

## Configuration
# logfileのディレクトリ
my $log_path = "/var/log/squid";
# logfile名
my $log_file = "access.log";
# 圧縮されたlogfile名
my $log_file_gz = "access.log.*.gz";
# 出力先ディレクトリ
my $output_path = ".";
# 出力ファイル名
my $outfile = "accessrank.txt";
# 上位,何位まで表示するか指定。ただし,0のときは全て表示
my $head = 100;
# アクセスをカウントするfiletype
my @mime_type = qw(
   text/html
                );
## End of configuration.

my %access_list;

## Main
&analysis;
&output;
exit(0);
##

sub analysis {
    foreach my $line (`(cat $log_path/$log_file;zcat $log_path/$log_file_gz)`){
        chomp($line);
        next unless ($line =~ m|text/html$|);
        if ($line =~ m|https?://(.*?)/|){
            $line = $1;
            $line =~ s|.*\.([^.]+\.[^.]+\.[^.]+$)|$1|;
        }
        $access_list{$line}++;
    }
}

sub output {
    open OUT, "> $output_path/$outfile" or die $!;

    printf OUT "This file is written by access_rank.pl.(M.Maehara)\n\n";
    my $line_no = 1;
    foreach my $key(sort {$access_list{$b} <=> $access_list{$a}} keys %access_li
st){

        if ($line_no <= $head || !$head){
            printf OUT "%7d\t%s\n",$access_list{$key},$key;
        }
        $line_no++;
    }
    close OUT;
}

sub isskip {
    my $line = shift @_;
    foreach my $ext (@mime_type){
        if ($line =~ m|$ext$|) {
            return 0;
        }
    }
    return 1;
}
1;

職場のアクセスログをもとに解析した結果は,以下のとおりです。Yahooへのアクセス数の多さにびっくりしました。

 342256 yahoo.co.jp
  52862 教育機関プロバイダ
  37241 msn.co.jp
  36611 google.co.jp
  24617 infoseek.co.jp