combined log format CGI

Fist Farm needed a CGI that generated Combined Log Format for fistfarm.com, which he was working on at the time. It's surprisingly hard to find one that does just that!

He wanted to call it from inside an SSI, but the ideas should be the same.

Here's what I came up with.

#! /usr/bin/perl

$logfile = "log.blah";

use POSIX;
my $time = POSIX::strftime("[%d/%b/%Y:%H:%M:%S +0000]", gmtime);
my $line = sprintf("%s %s %s %s \"%s\" %s %s \"%s\" \"%s\"\n",
                   $ENV {REMOTE_ADDR} || "-", # %h
                   $ENV {REMOTE_IDENT} || "-", # %l
                   $ENV {REMOTE_USER} || "-", # %u
                   $time,              # %t
                   "$ENV{REQUEST_METHOD} $ENV{REQUEST_URI}", # %r
                   "-", # %>s  (status code)
                   "-", # %b (size)
                   $ENV {HTTP_REFERER} || "-",
                   $ENV {HTTP_USER_AGENT}) || "-");
open LOG, ">>$logfile";
print LOG $line;
close LOG;

print "Content-type: text/html\n\n";
print "";

Note that it's impossible to guess the status code or the size of the request from a CGI; I just left them blank.

To call using an SSI, I did: