8 our @ISA = qw(Exporter DynaLoader);
9 our @EXPORT = qw(openlog closelog setlogmask syslog);
10 our @EXPORT_OK = qw(setlogsock);
11 our $VERSION = '0.06';
13 # it would be nice to try stream/unix first, since that will be
14 # most efficient. However streams are dodgy - see _syslog_send_stream
15 my @connectMethods = ( 'tcp', 'udp', 'unix', 'stream', 'console' );
16 if ($^O =~ /^(freebsd|linux)$/) {
17 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
19 my @defaultMethods = @connectMethods;
20 my $syslog_path = undef;
22 my $current_proto = undef;
24 my $fail_time = undef;
25 our ($connected, @fallbackMethods, $syslog_send, $host);
32 Sys::Syslog, openlog, closelog, setlogmask, syslog - Perl interface to the UNIX syslog(3) calls
36 use Sys::Syslog; # all except setlogsock, or:
37 use Sys::Syslog qw(:DEFAULT setlogsock); # default set, plus setlogsock
39 setlogsock $sock_type;
40 openlog $ident, $logopt, $facility; # don't forget this
41 syslog $priority, $format, @args;
42 $oldmask = setlogmask $mask_priority;
47 Sys::Syslog is an interface to the UNIX C<syslog(3)> program.
48 Call C<syslog()> with a string priority and a list of C<printf()> args
49 just like C<syslog(3)>.
51 Syslog provides the functions:
55 =item openlog $ident, $logopt, $facility
57 I<$ident> is prepended to every message. I<$logopt> contains zero or
58 more of the words I<pid>, I<ndelay>, I<nowait>. The cons option is
59 ignored, since the failover mechanism will drop down to the console
60 automatically if all other media fail. I<$facility> specifies the
61 part of the system to report about, for example LOG_USER or LOG_LOCAL0:
62 see your C<syslog(3)> documentation for the facilities available in
65 B<You should use openlog() before calling syslog().>
67 =item syslog $priority, $format, @args
69 If I<$priority> permits, logs I<($format, @args)>
70 printed as by C<printf(3V)>, with the addition that I<%m>
71 is replaced with C<"$!"> (the latest error message).
73 If you didn't use openlog() before using syslog(), syslog will try to
74 guess the I<$ident> by extracting the shortest prefix of I<$format>
77 =item setlogmask $mask_priority
79 Sets log mask I<$mask_priority> and returns the old mask.
81 =item setlogsock $sock_type [$stream_location] (added in 5.004_02)
83 Sets the socket type to be used for the next call to
84 C<openlog()> or C<syslog()> and returns TRUE on success,
87 A value of 'unix' will connect to the UNIX domain socket (in some
88 systems a character special device) returned by the C<_PATH_LOG> macro
89 (if your system defines it), or F</dev/log> or F</dev/conslog>,
90 whatever is writable. A value of 'stream' will connect to the stream
91 indicated by the pathname provided as the optional second parameter.
92 (For example Solaris and IRIX require 'stream' instead of 'unix'.)
93 A value of 'inet' will connect to an INET socket (either tcp or udp,
94 tried in that order) returned by getservbyname(). 'tcp' and 'udp' can
95 also be given as values. The value 'console' will send messages
96 directly to the console, as for the 'cons' option in the logopts in
99 A reference to an array can also be passed as the first parameter.
100 When this calling method is used, the array should contain a list of
101 sock_types which are attempted in order.
103 The default is to try tcp, udp, unix, stream, console.
105 Giving an invalid value for sock_type will croak.
113 Note that C<openlog> now takes three arguments, just like C<openlog(3)>.
117 openlog($program, 'cons,pid', 'user');
118 syslog('info', '%s', 'this is another test');
119 syslog('mail|warning', 'this is a better test: %d', time);
122 syslog('debug', 'this is the last test');
125 openlog("$program $$", 'ndelay', 'user');
126 syslog('notice', 'fooprogram: this is really done');
130 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
132 # Log to UDP port on $remotehost instead of logging locally
134 $Sys::Syslog::host = $remotehost;
135 openlog($program, 'ndelay', 'user');
136 syslog('info', 'something happened over here');
144 Tom Christiansen E<lt>F<tchrist@perl.com>E<gt> and Larry Wall
145 E<lt>F<larry@wall.org>E<gt>.
147 UNIX domain sockets added by Sean Robinson
148 E<lt>F<robinson_s@sc.maricopa.edu>E<gt> with support from Tim Bunce
149 E<lt>F<Tim.Bunce@ig.co.uk>E<gt> and the perl5-porters mailing list.
151 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
152 E<lt>F<tom@compton.nu>E<gt>.
154 Code for constant()s regenerated by Nicholas Clark E<lt>F<nick@ccl4.org>E<gt>.
156 Failover to different communication modes by Nick Williams
157 E<lt>F<Nick.Williams@morganstanley.com>E<gt>.
162 # This AUTOLOAD is used to 'autoload' constants from the constant()
167 ($constname = $AUTOLOAD) =~ s/.*:://;
168 croak "&Sys::Syslog::constant not defined" if $constname eq 'constant';
169 my ($error, $val) = constant($constname);
174 *$AUTOLOAD = sub { $val };
178 bootstrap Sys::Syslog $VERSION;
180 our $maskpri = &LOG_UPTO(&LOG_DEBUG);
183 our ($ident, $logopt, $facility) = @_; # package vars
184 our $lo_pid = $logopt =~ /\bpid\b/;
185 our $lo_ndelay = $logopt =~ /\bndelay\b/;
186 our $lo_nowait = $logopt =~ /\bnowait\b/;
187 return 1 unless $lo_ndelay;
192 our $facility = our $ident = '';
197 my $oldmask = $maskpri;
204 $syslog_path = shift;
205 &disconnect if $connected;
207 @fallbackMethods = ();
208 @connectMethods = @defaultMethods;
209 if (ref $setsock eq 'ARRAY') {
210 @connectMethods = @$setsock;
211 } elsif (lc($setsock) eq 'stream') {
212 unless (defined $syslog_path) {
213 my @try = qw(/dev/log /dev/conslog);
214 if (length &_PATH_LOG) { # Undefined _PATH_LOG is "".
215 unshift @try, &_PATH_LOG;
223 carp "stream passed to setlogsock, but could not find any device"
224 unless defined $syslog_path;
226 unless (-w $syslog_path) {
227 carp "stream passed to setlogsock, but $syslog_path is not writable";
230 @connectMethods = ( 'stream' );
232 } elsif (lc($setsock) eq 'unix') {
233 if (length _PATH_LOG() && !defined $syslog_path) {
234 $syslog_path = _PATH_LOG();
235 @connectMethods = ( 'unix' );
237 carp 'unix passed to setlogsock, but path not available';
240 } elsif (lc($setsock) eq 'tcp') {
241 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
242 @connectMethods = ( 'tcp' );
244 carp "tcp passed to setlogsock, but tcp service unavailable";
247 } elsif (lc($setsock) eq 'udp') {
248 if (getservbyname('syslog', 'udp')) {
249 @connectMethods = ( 'udp' );
251 carp "udp passed to setlogsock, but udp service unavailable";
254 } elsif (lc($setsock) eq 'inet') {
255 @connectMethods = ( 'tcp', 'udp' );
256 } elsif (lc($setsock) eq 'console') {
257 @connectMethods = ( 'console' );
259 carp "Invalid argument passed to setlogsock; must be 'stream', 'unix', 'tcp', 'udp' or 'inet'";
265 my $priority = shift;
267 my ($message, $whoami);
268 my (@words, $num, $numpri, $numfac, $sum);
270 local($facility) = $facility; # may need to change temporarily.
272 croak "syslog: expecting argument \$priority" unless $priority;
273 croak "syslog: expecting argument \$format" unless $mask;
275 @words = split(/\W+/, $priority, 2);# Allow "level" or "level|facility".
279 $num = &xlate($_); # Translate word to number.
280 if (/^kern$/ || $num < 0) {
281 croak "syslog: invalid level/facility: $_";
283 elsif ($num <= &LOG_PRIMASK) {
284 croak "syslog: too many levels given: $_" if defined($numpri);
286 return 0 unless &LOG_MASK($numpri) & $maskpri;
289 croak "syslog: too many facilities given: $_" if defined($numfac);
295 croak "syslog: level must be given" unless defined($numpri);
297 if (!defined($numfac)) { # Facility not specified in this call.
298 $facility = 'user' unless $facility;
299 $numfac = &xlate($facility);
302 &connect unless $connected;
304 $whoami = our $ident;
306 if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
312 ($whoami = getlogin) ||
313 ($whoami = getpwuid($<)) ||
314 ($whoami = 'syslog');
317 $whoami .= "[$$]" if our $lo_pid;
319 $mask =~ s/(?<!%)%m/$!/g;
320 $mask .= "\n" unless $mask =~ /\n$/;
321 $message = sprintf ($mask, @_);
323 $sum = $numpri + $numfac;
324 my $buf = "<$sum>$whoami: $message\0";
326 # it's possible that we'll get an error from sending
327 # (e.g. if method is UDP and there is no UDP listener,
328 # then we'll get ECONNREFUSED on the send). So what we
329 # want to do at this point is to fallback onto a different
331 while (scalar @fallbackMethods || $syslog_send) {
332 if ($failed && (time - $fail_time) > 60) {
333 # it's been a while... maybe things have been fixed
334 @fallbackMethods = ();
336 $transmit_ok = 0; # make it look like a fresh attempt
339 if ($connected && !connection_ok()) {
340 # Something was OK, but has now broken. Remember coz we'll
341 # want to go back to what used to be OK.
342 $failed = $current_proto unless $failed;
346 &connect unless $connected;
347 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
349 if (&{$syslog_send}($buf)) {
353 # typically doesn't happen, since errors are rare from write().
357 # could not send, could not fallback onto a working
358 # connection method. Lose.
362 sub _syslog_send_console {
364 chop($buf); # delete the NUL from the end
365 # The console print is a method which could block
366 # so we do it in a child process and always return success
368 if (my $pid = fork) {
373 if (waitpid($pid, 0) >= 0) {
376 # it's possible that the caller has other
377 # plans for SIGCHLD, so let's not interfere
382 if (open(CONS, ">/dev/console")) {
383 my $ret = print CONS $buf . "\r";
384 exit ($ret) if defined $pid;
387 exit if defined $pid;
391 sub _syslog_send_stream {
393 # XXX: this only works if the OS stream implementation makes a write
394 # look like a putmsg() with simple header. For instance it works on
395 # Solaris 8 but not Solaris 7.
396 # To be correct, it should use a STREAMS API, but perl doesn't have one.
397 return syswrite(SYSLOG, $buf, length($buf));
399 sub _syslog_send_socket {
401 return syswrite(SYSLOG, $buf, length($buf));
402 #return send(SYSLOG, $buf, 0);
407 return $name+0 if $name =~ /^\s*\d+\s*$/;
409 $name = "LOG_$name" unless $name =~ /^LOG_/;
410 $name = "Sys::Syslog::$name";
411 # Can't have just eval { &$name } || -1 because some LOG_XXX may be zero.
412 my $value = eval { no strict 'refs'; &$name };
413 defined $value ? $value : -1;
417 @fallbackMethods = @connectMethods unless (scalar @fallbackMethods);
418 if ($transmit_ok && $current_proto) {
419 # Retry what we were on, because it's worked in the past.
420 unshift(@fallbackMethods, $current_proto);
425 while ($proto = shift(@fallbackMethods)) {
427 my $fn = "connect_$proto";
428 $connected = &$fn(\@errs) if defined &$fn;
429 last if ($connected);
434 $current_proto = $proto;
435 my($old) = select(SYSLOG); $| = 1; select($old);
437 @fallbackMethods = ();
438 foreach my $err (@errs) {
441 croak "no connection to syslog available";
448 require Sys::Hostname;
449 my($host_uniq) = Sys::Hostname::hostname();
450 ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
452 my $tcp = getprotobyname('tcp');
454 push(@{$errs}, "getprotobyname failed for tcp");
457 my $syslog = getservbyname('syslog','tcp');
458 $syslog = getservbyname('syslogng','tcp') unless (defined $syslog);
459 if (!defined $syslog) {
460 push(@{$errs}, "getservbyname failed for tcp");
464 my $this = sockaddr_in($syslog, INADDR_ANY);
465 my $that = sockaddr_in($syslog, inet_aton($host));
467 push(@{$errs}, "can't lookup $host");
470 if (!socket(SYSLOG,AF_INET,SOCK_STREAM,$tcp)) {
471 push(@{$errs}, "tcp socket: $!");
474 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
475 setsockopt(SYSLOG, IPPROTO_TCP, TCP_NODELAY, 1);
476 if (!CORE::connect(SYSLOG,$that)) {
477 push(@{$errs}, "tcp connect: $!");
480 $syslog_send = \&_syslog_send_socket;
487 require Sys::Hostname;
488 my($host_uniq) = Sys::Hostname::hostname();
489 ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
491 my $udp = getprotobyname('udp');
493 push(@{$errs}, "getprotobyname failed for udp");
496 my $syslog = getservbyname('syslog','udp');
497 if (!defined $syslog) {
498 push(@{$errs}, "getservbyname failed for udp");
501 my $this = sockaddr_in($syslog, INADDR_ANY);
502 my $that = sockaddr_in($syslog, inet_aton($host));
504 push(@{$errs}, "can't lookup $host");
507 if (!socket(SYSLOG,AF_INET,SOCK_DGRAM,$udp)) {
508 push(@{$errs}, "udp socket: $!");
511 if (!CORE::connect(SYSLOG,$that)) {
512 push(@{$errs}, "udp connect: $!");
515 # We want to check that the UDP connect worked. However the only
516 # way to do that is to send a message and see if an ICMP is returned
517 _syslog_send_socket("");
518 if (!connection_ok()) {
519 push(@{$errs}, "udp connect: nobody listening");
522 $syslog_send = \&_syslog_send_socket;
528 # might want syslog_path to be variable based on syslog.h (if only
530 $syslog_path = '/dev/conslog';
531 if (!-w $syslog_path) {
532 push(@{$errs}, "stream $syslog_path is not writable");
535 if (!open(SYSLOG, ">" . $syslog_path)) {
536 push(@{$errs}, "stream can't open $syslog_path: $!");
539 $syslog_send = \&_syslog_send_stream;
545 if (length _PATH_LOG()) {
546 $syslog_path = _PATH_LOG();
548 push(@{$errs}, "_PATH_LOG not available in syslog.h");
551 my $that = sockaddr_un($syslog_path);
553 push(@{$errs}, "can't locate $syslog_path");
556 if (!socket(SYSLOG,AF_UNIX,SOCK_STREAM,0)) {
557 push(@{$errs}, "unix stream socket: $!");
560 if (!CORE::connect(SYSLOG,$that)) {
561 if (!socket(SYSLOG,AF_UNIX,SOCK_DGRAM,0)) {
562 push(@{$errs}, "unix dgram socket: $!");
565 if (!CORE::connect(SYSLOG,$that)) {
566 push(@{$errs}, "unix dgram connect: $!");
570 $syslog_send = \&_syslog_send_socket;
574 sub connect_console {
576 if (!-w '/dev/console') {
577 push(@{$errs}, "console is not writable");
580 $syslog_send = \&_syslog_send_console;
584 # to test if the connection is still good, we need to check if any
585 # errors are present on the connection. The errors will not be raised
586 # by a write. Instead, sockets are made readable and the next read
587 # would cause the error to be returned. Unfortunately the syslog
588 # 'protocol' never provides anything for us to read. But with
589 # judicious use of select(), we can see if it would be readable...
591 return 1 if (defined $current_proto && $current_proto eq 'console');
593 vec($rin, fileno(SYSLOG), 1) = 1;
594 my $ret = select $rin, undef, $rin, 0;
595 return ($ret ? 0 : 1);
601 $syslog_send = undef;