# Log.pm
#
# Object for handling logging
#
# Author: Mike McCauley (mikem@open.com.au)
# Copyright (C) 1997 Open System Consultants
# $Id: Log.pm,v 1.12 2001/03/08 23:12:11 mikem Exp mikem $

# Message priorities to pass to log
# These are the same abbreviations as used by syslog
# These are exported to main for convenience
$main::LOG_ERR = 0;        # Error conditions
$main::LOG_WARNING = 1;    # Warning conditions
$main::LOG_NOTICE = 2;     # Normal but significant
$main::LOG_INFO = 3;       # Informational
$main::LOG_DEBUG = 4;      # For debugging

package Radius::Log;
use Radius::LogFILE;

use Exporter();
@ISA = ('Exporter');
@EXPORT = qw(log);

use strict;

# Maps our LOG_* numbers into priority level names
@Radius::Log::priorityToString  = ('ERR', 'WARNING', 'NOTICE', 'INFO', 'DEBUG');

# Catch recursion in calls to log
my $in_log = 0;

# For backwards compatibility, a default FILE logger
my $default_logger;

# Make sure we get reinitialized on sighup
push(@main::reinitFns, \&reinitialize);

sub adjustTrace
{
    my ($increment) = @_;

    map { $_->adjustTrace($increment) } @Radius::Log::logModules;
    return $main::config->{Trace} + $increment;
}

#####################################################################
# addModule($name, $file)
# Add a new logging module to the stack of log modules
sub addModule
{
    my ($name, $file) = @_;

    my $class = "Radius::Log$name";
    if (eval("require $class"))
    {
	$class->new($file, $name);
    }
    else
    {
	&main::log($main::LOG_ERR, "Could not load Log module $class: $@");
    }
}

#####################################################################
# Log a message to all the loggers defined
# $p is the message priority, $s is the message
sub log
{
    my ($p, $s) = @_;

    # Print to stdout as well, if required
    print scalar localtime(time) . ": $Radius::Log::priorityToString[$p]: $s\n"
	if $main::config->{LogStdout} && $p <= $main::config->{Trace};

    # Catch recursion
    return if $in_log;
    $in_log = 1;

    # Call each log module with $p, $s
    map $_->log($p, $s), @Radius::Log::logModules;

    $in_log = 0;
}

#####################################################################
# Make a default file logger
sub setupDefaultLogger
{
    # For backwards compatibility, create a basic FILE logger
    # if they have defined a log filename in the global config
    # This will disappear one day
    if (!$default_logger && $main::config->{LogFile} ne '')
    {
	$default_logger = Radius::LogFILE->new();
    }
    if ($default_logger)
    {
	$default_logger->{Filename} = $main::config->{LogFile};
	$default_logger->{Trace} = $main::config->{Trace};
    }
}

#####################################################################
# REInitialize the log module
sub reinitialize
{
    $default_logger = undef;
    @Radius::Log::logModules = ();
}

1;
