#
# syslog.pl
#
# tom christiansen <tchrist@convex.com>
#
# call syslog() with a string priority and a list of printf() args
# like syslog(3) but using logger(8).  will only open a new pipe
# to logger if it needs to.
#
#  usage: do 'syslog.pl' || die "syslog.pl: $@";
#
#  then (put these all in a script to test function)
#		
#
#	do openlog($program,'user');
#	do syslog('info','this is another test');
#	do syslog('warn','this is a better test: %d', time);
#	do closelog();
#	
#	do syslog('debug','this is the last test');
#	do openlog("$program $$",'user');
#	do syslog('notice','fooprogram: this is really done');
#
#	$! = 55;
#	do syslog('info','problem was %m'); # %m == $! in syslog(3)

package syslog;

$logpath = '/usr/ucb/logger';

$opriority = $ofacility = $facility = $ident = '';

die "syslog: can't call $logpath: $!" unless -x $logpath;

sub main'openlog {
    &main'closelog if $logopen;
    ($ident, $facility) = @_;  # package vars
} 

sub main'closelog {
    $facility = $ident = '';
    if ($logopen) {
	$logopen = 0;
	close LOG;
    } 
} 
 
sub main'syslog {
    local($priority) = shift;
    local($mask) = shift;
    local($message, $whoami, $oldfh);

    $whoami = $ident;

    die "syslog: expected both priority and mask" unless $mask && $priority;

    $facility = "user" unless $facility;

    if (!$ident && $mask =~ /^(\S.*):\s?(.*)/) {
	$whoami = $1;
	$mask = $2;
    } 

    $mask =~ s/%m/$!/g;
    $mask .= "\n" unless $mask =~ /\n$/;

    $whoami = sprintf ("%s %d", $ENV{'USER'}, $$) unless $whoami;

    if ($opriority ne $priority || $ofacility ne $facility) {
	$opriority = $priority;
	$ofacility = $facility;
	close LOG if $logopen++;
	open(LOG, "| $logpath -t '$whoami' -p '$facility.$priority'");
	$oldfh = select(LOG);
	$| = 1;
	select($oldfh);
    } 
    printf LOG "$mask", @_;
}

1;
