#!/usr/bin/perl -w

# Copyright 2001-2006 The Apache Software Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

=head1 NAME

request_log - Creates a request log in combined log format

=head1 SYNOPSIS

  Plugin request_log
  LogFile /path/to/logfile

=head1 DESCRIPTION

This plugin attempts to emulate the standard apache combined log format of:

  "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\""

Which most log parsers can cope with by default.

=head1 CONFIG

=head2 LogFile STRING

Specifies a log file to write to. Doesn't do any log file rotation or anything
fancy like that. Patches welcome obviously ;-)

=cut

sub conf_RequestLog : Validate(TAKE1) {
    my ($self, $value) = @_;

    open(my $fh, '>>', $value) || die "open(>> $value) : $!";
    return $fh;
}

use POSIX ();

sub hook_response_sent {
    my ($self, $code) = @_;
    
    # [07/Aug/2006:21:08:52 +0000]
    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",
        $self->client->peer_ip_string,
        '-',
        '-', # TODO - get username out of headers_in maybe?
        $time,
        $self->client->headers_in->request_line,
        $self->client->headers_out->response_code,
        '-', # TODO - get bytes sent
        $self->client->headers_in->header('Referer') || '-',
        $self->client->headers_in->header('User-Agent') || '-',
        );
    
    my $logfile = $self->config('RequestLog') || die "No LogFile configured";
    syswrite($logfile, $line) || die "Unable to write to logfile: $!";
    
    return DECLINED;
}
