7 @ISA = qw(Exporter DynaLoader);
8 @EXPORT = qw(openlog closelog setlogmask syslog);
9 @EXPORT_OK = qw(setlogsock);
12 # it would be nice to try stream/unix first, since that will be
13 # most efficient. However streams are dodgy - see _syslog_send_stream
14 #my @connectMethods = ( 'stream', 'unix', 'tcp', 'udp' );
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;
31 Sys::Syslog, openlog, closelog, setlogmask, syslog - Perl interface to the UNIX syslog(3) calls
35 use Sys::Syslog; # all except setlogsock, or:
36 use Sys::Syslog qw(:DEFAULT setlogsock); # default set, plus setlogsock
38 setlogsock $sock_type;
39 openlog $ident, $logopt, $facility;
40 syslog $priority, $format, @args;
41 $oldmask = setlogmask $mask_priority;
46 Sys::Syslog is an interface to the UNIX C<syslog(3)> program.
47 Call C<syslog()> with a string priority and a list of C<printf()> args
48 just like C<syslog(3)>.
50 Syslog provides the functions:
54 =item openlog $ident, $logopt, $facility
56 I<$ident> is prepended to every message. I<$logopt> contains zero or
57 more of the words I<pid>, I<ndelay>, I<nowait>. The cons option is
58 ignored, since the failover mechanism will drop down to the console
59 automatically if all other media fail. I<$facility> specifies the
62 =item syslog $priority, $format, @args
64 If I<$priority> permits, logs I<($format, @args)>
65 printed as by C<printf(3V)>, with the addition that I<%m>
66 is replaced with C<"$!"> (the latest error message).
68 =item setlogmask $mask_priority
70 Sets log mask I<$mask_priority> and returns the old mask.
72 =item setlogsock $sock_type [$stream_location] (added in 5.004_02)
74 Sets the socket type to be used for the next call to
75 C<openlog()> or C<syslog()> and returns TRUE on success,
78 A value of 'unix' will connect to the UNIX domain socket (in some
79 systems a character special device) returned by the C<_PATH_LOG> macro
80 (if your system defines it), or F</dev/log> or F</dev/conslog>,
81 whatever is writable. A value of 'stream' will connect to the stream
82 indicated by the pathname provided as the optional second parameter.
83 A value of 'inet' will connect to an INET socket (either tcp or udp,
84 tried in that order) returned by getservbyname(). 'tcp' and 'udp' can
85 also be given as values. The value 'console' will send messages
86 directly to the console, as for the 'cons' option in the logopts in
89 A reference to an array can also be passed as the first parameter.
90 When this calling method is used, the array should contain a list of
91 sock_types which are attempted in order.
93 The default is to try tcp, udp, unix, stream, console.
95 Giving an invalid value for sock_type will croak.
103 Note that C<openlog> now takes three arguments, just like C<openlog(3)>.
107 openlog($program, 'cons,pid', 'user');
108 syslog('info', 'this is another test');
109 syslog('mail|warning', 'this is a better test: %d', time);
112 syslog('debug', 'this is the last test');
115 openlog("$program $$", 'ndelay', 'user');
116 syslog('notice', 'fooprogram: this is really done');
120 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
128 Tom Christiansen E<lt>F<tchrist@perl.com>E<gt> and Larry Wall
129 E<lt>F<larry@wall.org>E<gt>.
131 UNIX domain sockets added by Sean Robinson
132 E<lt>F<robinson_s@sc.maricopa.edu>E<gt> with support from Tim Bunce
133 E<lt>F<Tim.Bunce@ig.co.uk>E<gt> and the perl5-porters mailing list.
135 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
136 E<lt>F<tom@compton.nu>E<gt>.
138 Code for constant()s regenerated by Nicholas Clark E<lt>F<nick@ccl4.org>E<gt>.
140 Failover to different communication modes by Nick Williams
141 E<lt>F<Nick.Williams@morganstanley.com>E<gt>.
146 # This AUTOLOAD is used to 'autoload' constants from the constant()
151 ($constname = $AUTOLOAD) =~ s/.*:://;
152 croak "&Sys::Syslog::constant not defined" if $constname eq 'constant';
153 my ($error, $val) = constant($constname);
157 *$AUTOLOAD = sub { $val };
161 bootstrap Sys::Syslog $VERSION;
163 $maskpri = &LOG_UPTO(&LOG_DEBUG);
166 ($ident, $logopt, $facility) = @_; # package vars
167 $lo_pid = $logopt =~ /\bpid\b/;
168 $lo_ndelay = $logopt =~ /\bndelay\b/;
169 $lo_nowait = $logopt =~ /\bnowait\b/;
170 return 1 unless $lo_ndelay;
175 $facility = $ident = '';
180 local($oldmask) = $maskpri;
186 local($setsock) = shift;
187 $syslog_path = shift;
188 &disconnect if $connected;
190 @fallbackMethods = ();
191 @connectMethods = @defaultMethods;
192 if (ref $setsock eq 'ARRAY') {
193 @connectMethods = @$setsock;
194 } elsif (lc($setsock) eq 'stream') {
195 unless (defined $syslog_path) {
196 my @try = qw(/dev/log /dev/conslog);
197 if (length &_PATH_LOG) { # Undefined _PATH_LOG is "".
198 unshift @try, &_PATH_LOG;
206 carp "stream passed to setlogsock, but could not find any device"
207 unless defined $syslog_path;
209 unless (-w $syslog_path) {
210 carp "stream passed to setlogsock, but $syslog_path is not writable";
213 @connectMethods = ( 'stream' );
215 } elsif (lc($setsock) eq 'unix') {
216 if (length _PATH_LOG() && !defined $syslog_path) {
217 $syslog_path = _PATH_LOG();
218 @connectMethods = ( 'unix' );
220 carp 'unix passed to setlogsock, but path not available';
223 } elsif (lc($setsock) eq 'tcp') {
224 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
225 @connectMethods = ( 'tcp' );
227 carp "tcp passed to setlogsock, but tcp service unavailable";
230 } elsif (lc($setsock) eq 'udp') {
231 if (getservbyname('syslog', 'udp')) {
232 @connectMethods = ( 'udp' );
234 carp "udp passed to setlogsock, but udp service unavailable";
237 } elsif (lc($setsock) eq 'inet') {
238 @connectMethods = ( 'tcp', 'udp' );
239 } elsif (lc($setsock) eq 'console') {
240 @connectMethods = ( 'console' );
242 carp "Invalid argument passed to setlogsock; must be 'stream', 'unix', 'tcp', 'udp' or 'inet'";
248 local($priority) = shift;
249 local($mask) = shift;
250 local($message, $whoami);
251 local(@words, $num, $numpri, $numfac, $sum);
252 local($facility) = $facility; # may need to change temporarily.
254 croak "syslog: expecting argument \$priority" unless $priority;
255 croak "syslog: expecting argument \$format" unless $mask;
257 @words = split(/\W+/, $priority, 2);# Allow "level" or "level|facility".
261 $num = &xlate($_); # Translate word to number.
262 if (/^kern$/ || $num < 0) {
263 croak "syslog: invalid level/facility: $_";
265 elsif ($num <= &LOG_PRIMASK) {
266 croak "syslog: too many levels given: $_" if defined($numpri);
268 return 0 unless &LOG_MASK($numpri) & $maskpri;
271 croak "syslog: too many facilities given: $_" if defined($numfac);
277 croak "syslog: level must be given" unless defined($numpri);
279 if (!defined($numfac)) { # Facility not specified in this call.
280 $facility = 'user' unless $facility;
281 $numfac = &xlate($facility);
284 &connect unless $connected;
288 if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
294 ($whoami = getlogin) ||
295 ($whoami = getpwuid($<)) ||
296 ($whoami = 'syslog');
299 $whoami .= "[$$]" if $lo_pid;
302 $mask .= "\n" unless $mask =~ /\n$/;
303 $message = sprintf ($mask, @_);
305 $sum = $numpri + $numfac;
306 my $buf = "<$sum>$whoami: $message\0";
308 # it's possible that we'll get an error from sending
309 # (e.g. if method is UDP and there is no UDP listener,
310 # then we'll get ECONNREFUSED on the send). So what we
311 # want to do at this point is to fallback onto a different
313 while (scalar @fallbackMethods || $syslog_send) {
314 if ($failed && (time - $fail_time) > 60) {
315 # it's been a while... maybe things have been fixed
316 @fallbackMethods = ();
318 $transmit_ok = 0; # make it look like a fresh attempt
321 if ($connected && !connection_ok()) {
322 # Something was OK, but has now broken. Remember coz we'll
323 # want to go back to what used to be OK.
324 $failed = $current_proto unless $failed;
328 &connect unless $connected;
329 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
331 if (&{$syslog_send}($buf)) {
335 # typically doesn't happen, since errors are rare from write().
339 # could not send, could not fallback onto a working
340 # connection method. Lose.
344 sub _syslog_send_console {
346 chop($buf); # delete the NUL from the end
347 # The console print is a method which could block
348 # so we do it in a child process and always return success
350 if (my $pid = fork) {
354 if (waitpid($pid, 0) >= 0) {
357 # it's possible that the caller has other
358 # plans for SIGCHLD, so let's not interfere
363 if (open(CONS, ">/dev/console")) {
364 my $ret = print CONS $buf . "\r";
365 exit ($ret) if defined $pid;
368 exit if defined $pid;
372 sub _syslog_send_stream {
374 # XXX: this only works if the OS stream implementation makes a write
375 # look like a putmsg() with simple header. For instance it works on
376 # Solaris 8 but not Solaris 7.
377 # To be correct, it should use a STREAMS API, but perl doesn't have one.
378 return syswrite(SYSLOG, $buf, length($buf));
380 sub _syslog_send_socket {
382 return syswrite(SYSLOG, $buf, length($buf));
383 #return send(SYSLOG, $buf, 0);
389 $name = "LOG_$name" unless $name =~ /^LOG_/;
390 $name = "Sys::Syslog::$name";
391 # Can't have just eval { &$name } || -1 because some LOG_XXX may be zero.
392 my $value = eval { &$name };
393 defined $value ? $value : -1;
397 @fallbackMethods = @connectMethods unless (scalar @fallbackMethods);
398 if ($transmit_ok && $current_proto) {
399 # Retry what we were on, because it's worked in the past.
400 unshift(@fallbackMethods, $current_proto);
405 while ($proto = shift(@fallbackMethods)) {
406 my $fn = "connect_$proto";
407 $connected = &$fn(\@errs) unless (!defined &$fn);
408 last if ($connected);
413 $current_proto = $proto;
414 local($old) = select(SYSLOG); $| = 1; select($old);
416 @fallbackMethods = ();
417 foreach my $err (@errs) {
420 croak "no connection to syslog available";
427 require Sys::Hostname;
428 my($host_uniq) = Sys::Hostname::hostname();
429 ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
431 my $tcp = getprotobyname('tcp');
433 push(@{$errs}, "getprotobyname failed for tcp");
436 my $syslog = getservbyname('syslog','tcp');
437 $syslog = getservbyname('syslogng','tcp') unless (defined $syslog);
438 if (!defined $syslog) {
439 push(@{$errs}, "getservbyname failed for tcp");
443 my $this = sockaddr_in($syslog, INADDR_ANY);
444 my $that = sockaddr_in($syslog, inet_aton($host));
446 push(@{$errs}, "can't lookup $host");
449 if (!socket(SYSLOG,AF_INET,SOCK_STREAM,$tcp)) {
450 push(@{$errs}, "tcp socket: $!");
453 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
454 setsockopt(SYSLOG, IPPROTO_TCP, TCP_NODELAY, 1);
455 if (!CORE::connect(SYSLOG,$that)) {
456 push(@{$errs}, "tcp connect: $!");
459 $syslog_send = \&_syslog_send_socket;
466 require Sys::Hostname;
467 my($host_uniq) = Sys::Hostname::hostname();
468 ($host) = $host_uniq =~ /([A-Za-z0-9_.-]+)/; # allow FQDN (inc _)
470 my $udp = getprotobyname('udp');
472 push(@{$errs}, "getprotobyname failed for udp");
475 my $syslog = getservbyname('syslog','udp');
476 if (!defined $syslog) {
477 push(@{$errs}, "getservbyname failed for udp");
480 my $this = sockaddr_in($syslog, INADDR_ANY);
481 my $that = sockaddr_in($syslog, inet_aton($host));
483 push(@{$errs}, "can't lookup $host");
486 if (!socket(SYSLOG,AF_INET,SOCK_DGRAM,$udp)) {
487 push(@{$errs}, "udp socket: $!");
490 if (!CORE::connect(SYSLOG,$that)) {
491 push(@{$errs}, "udp connect: $!");
494 # We want to check that the UDP connect worked. However the only
495 # way to do that is to send a message and see if an ICMP is returned
496 _syslog_send_socket("");
497 if (!connection_ok()) {
498 push(@{$errs}, "udp connect: nobody listening");
501 $syslog_send = \&_syslog_send_socket;
507 # might want syslog_path to be variable based on syslog.h (if only
509 $syslog_path = '/dev/conslog';
510 if (!-w $syslog_path) {
511 push(@{$errs}, "stream $syslog_path is not writable");
514 if (!open(SYSLOG, ">" . $syslog_path)) {
515 push(@{$errs}, "stream can't open $syslog_path: $!");
518 $syslog_send = \&_syslog_send_stream;
524 if (length _PATH_LOG()) {
525 $syslog_path = _PATH_LOG();
527 push(@{$errs}, "_PATH_LOG not available in syslog.h");
530 my $that = sockaddr_un($syslog_path);
532 push(@{$errs}, "can't locate $syslog_path");
535 if (!socket(SYSLOG,AF_UNIX,SOCK_STREAM,0)) {
536 push(@{$errs}, "unix stream socket: $!");
539 if (!CORE::connect(SYSLOG,$that)) {
540 if (!socket(SYSLOG,AF_UNIX,SOCK_DGRAM,0)) {
541 push(@{$errs}, "unix dgram socket: $!");
544 if (!CORE::connect(SYSLOG,$that)) {
545 push(@{$errs}, "unix dgram connect: $!");
549 $syslog_send = \&_syslog_send_socket;
553 sub connect_console {
555 if (!-w '/dev/console') {
556 push(@{$errs}, "console is not writable");
559 $syslog_send = \&_syslog_send_console;
563 # to test if the connection is still good, we need to check if any
564 # errors are present on the connection. The errors will not be raised
565 # by a write. Instead, sockets are made readable and the next read
566 # would cause the error to be returned. Unfortunately the syslog
567 # 'protocol' never provides anything for us to read. But with
568 # judicious use of select(), we can see if it would be readable...
570 return 1 if (defined $current_proto && $current_proto eq 'console');
572 vec($rin, fileno(SYSLOG), 1) = 1;
573 my $ret = select $rin, undef, $rin, 0;
574 return ($ret ? 0 : 1);
580 $syslog_send = undef;