# LogStructured.pm
#
# Log to a file
#
# Author: Alexander Hartmaier (abraxxa@cpan.org)
# Copyright (C) 2014 Alexander Hartmaier

package Radius::LogStructured;
use Radius::LogFILE;
@ISA = qw(Radius::LogFILE);
use strict;
use warnings;

%Radius::LogStructured::ConfigKeywords =
('Filename'  =>
 ['string', 'The name of the file that will be logged to. The file name can include special path name characters as defined in "Special characters in file names and other parameters" in the Radiator Reference manual. The default is %L/logfile, i.e. a file named logfile in LogDir.', 0],

 'LogFormatHook' =>
 ['hook',
  'Specifies a Perl hook that will be run for each log message. The default is a passthrough of the log message.',
  1],
);

#####################################################################
# Do per-instance default initialization
# This is called by Configurable during Configurable::new before
# the config file is parsed. Its a good place initialize instance
# variables
# that might get overridden when the config file is parsed.
# Do per-instance default initialization. This is called after
# construction is complete
sub initialize
{
    my ($self) = @_;

    $self->SUPER::initialize;
    $self->set("LogFormatHook",
        'sub {
            my $self = shift;
            my $priority = shift;
            my $s = shift;
            my $p = shift;

	    my $message = Radius::Util::format_special(
                "%Y-%m-%dT%H:%M:%SZ %0 $s",
		$p, undef,
		$Radius::Log::priorityToString[$priority]
            );
            return $message;
        }');
}

#####################################################################
# Log a message
# $priority is the message priority, $s is the message
# $r is the current request packet, if any
sub log
{
    my ($self, $priority, $s, $p) = @_;

#    print "Logger $self->{Identifier}, $priority, $s, $p\n";
    if ($self->{Filename} ne '' && $self->willLog($priority, $p))
    {
	#print "logging to $self->{Filename}\n";
	my ($message) = $self->runHook('LogFormatHook', $p, $self, $priority, $s, $p );

	my $filename = &Radius::Util::format_special($self->{Filename}, $p, undef, $priority, $s);
	&Radius::Util::append($filename, $message . "\n")
	    || warn "Log could not append '$message' to log file '$filename': $!";
    }
}

1;
