#!/usr/bin/perl -sw

sub help {
    print q{
Name:
   sort-apache-log - merge and sort Apache logfiles

Usage:
   sort-apache-log logfile(s) > sorted_logfile 
   cat logfile(s) | sort-apache-log > sorted_logfile 

Description:

   sort-apache-log will read logfiles generated by Apache and sort
   them according to time. This is especially useful for merging
   several logfiles.

   The format should include a time stamp in the format:

   [dd/Mmm/yyyy:hh:mm:ss +zone] e.g. [31/Dec/2004:23:59:59 +0100]

   The standard logformat has this.

Example:
   Merge the logfiles access_log-server1 and access_log-server2:

     sort-apache-log access_log-server1 access_log-server2 > sorted_logfile

Example:
   Merge logfiles, but remove duplicates:

     sort-apache-log access_log.1 access_log.2 | uniq > sorted_logfile

Author:
   Copyright 2005-02-22 Ole Tange http://ole.tange.dk
   Licensed under GPL
};

}

if($h) { help(); exit; }

%mon = ("Jan" => "01", 
	"Feb" => "02",
	"Mar" => "03",
	"Apr" => "04",
	"Maj" => "05",
	"Jun" => "06",
	"Jul" => "07",
	"Aug" => "08",
	"Sep" => "09",
	"Oct" => "10",
	"Nov" => "11",
	"Dec" => "12");

open(SORT,"| sort | cut -f 2-") || die;


# Copy [datestamp] to start:
while(<>) {
    #           DD   MMM   YYYY   HH MM SS
    m{^[^\[]+\[(..)/(...)/(....):(..:..:..) [^\]]+\]} || do { warn($_); next };
    print SORT "[",$3,$mon{$2},$1,$4,"]\t", $_;
}
close SORT;

$h=$h; # Ignore perl -w
