4 # tom christiansen <tchrist@convex.com>
5 # modified to use sockets by Larry Wall <lwall@jpl-devvax.jpl.nasa.gov>
6 # NOTE: openlog now takes three arguments, just like openlog(3)
8 # call syslog() with a string priority and a list of printf() args
11 # usage: require 'syslog.pl';
13 # then (put these all in a script to test function)
16 # do openlog($program,'cons,pid','user');
17 # do syslog('info','this is another test');
18 # do syslog('warn','this is a better test: %d', time);
21 # do syslog('debug','this is the last test');
22 # do openlog("$program $$",'ndelay','user');
23 # do syslog('notice','fooprogram: this is really done');
26 # do syslog('info','problem was %m'); # %m == $! in syslog(3)
30 $host = 'localhost' unless $host; # set $syslog'host to change
35 ($ident, $logopt, $facility) = @_; # package vars
36 $lo_pid = $logopt =~ /\bpid\b/;
37 $lo_ndelay = $logopt =~ /\bndelay\b/;
38 $lo_cons = $logopt =~ /\bncons\b/;
39 $lo_nowait = $logopt =~ /\bnowait\b/;
40 &connect if $lo_ndelay;
44 $facility = $ident = '';
49 local($priority) = shift;
51 local($message, $whoami);
53 &connect unless $connected;
57 die "syslog: expected both priority and mask" unless $mask && $priority;
59 $facility = "user" unless $facility;
61 if (!$ident && $mask =~ /^(\S.*):\s?(.*)/) {
65 $whoami .= " [$$]" if $lo_pid;
68 $mask .= "\n" unless $mask =~ /\n$/;
69 $message = sprintf ($mask, @_);
71 $whoami = sprintf ("%s %d",$ENV{'USER'}||$ENV{'LOGNAME'},$$) unless $whoami;
73 $sum = &xlate($priority) + &xlate($facility);
74 unless (send(SYSLOG,"<$sum>$whoami: $message",0)) {
78 do {$died = wait;} until $died == $pid || $died < 0;
82 open(CONS,">/dev/console");
83 print CONS "$<facility.$priority>$whoami: $message\n";
84 exit if defined $pid; # if fork failed, we're parent
94 $name = "LOG_$name" unless $name =~ /^LOG_/;
95 $name = "syslog'$name";
108 ($name,$aliases,$proto) = getprotobyname('udp');
111 ($name,$aliase,$port,$proto) = getservbyname('syslog','udp');
114 if (chop($myname = `hostname`)) {
115 ($name,$aliases,$addrtype,$length,@addrs) = gethostbyname($myname);
116 die "Can't lookup $myname\n" unless $name;
117 @bytes = unpack("C4",$addrs[0]);
122 $this = pack($pat, $af_inet, 0, @bytes);
124 if ($host =~ /^\d+\./) {
125 @bytes = split(/\./,$host);
128 ($name,$aliases,$addrtype,$length,@addrs) = gethostbyname($host);
129 die "Can't lookup $host\n" unless $name;
130 @bytes = unpack("C4",$addrs[0]);
132 $that = pack($pat,$af_inet,$syslog,@bytes);
134 socket(SYSLOG,$af_inet,$datagram,$udp) || die "socket: $!\n";
135 bind(SYSLOG,$this) || die "bind: $!\n";
136 connect(SYSLOG,$that) || die "connect: $!\n";
138 local($old) = select(SYSLOG); $| = 1; select($old);