[perl #40272] subroutine call with & in perlop example
[p5sagit/p5-mst-13.2.git] / ext / Sys / Syslog / Syslog.pm
CommitLineData
a0d0e21e 1package Sys::Syslog;
8168e71f 2use strict;
89c3c464 3use warnings::register;
8168e71f 4use Carp;
6e4ef777 5use POSIX qw(strftime setlocale LC_TIME);
6use Socket ':all';
3b355090 7require 5.006;
a0d0e21e 8require Exporter;
a0d0e21e 9
89c3c464 10{ no strict 'vars';
4b035b3d 11 $VERSION = '0.17';
89c3c464 12 @ISA = qw(Exporter);
942974c1 13
89c3c464 14 %EXPORT_TAGS = (
4b035b3d 15 standard => [qw(openlog syslog closelog setlogmask)],
16 extended => [qw(setlogsock)],
17 macros => [
18 # levels
19 qw(
20 LOG_ALERT LOG_CRIT LOG_DEBUG LOG_EMERG LOG_ERR
21 LOG_INFO LOG_NOTICE LOG_WARNING
22 ),
23
24 # facilities
25 qw(
26 LOG_AUTH LOG_AUTHPRIV LOG_CRON LOG_DAEMON LOG_FTP
27 LOG_INSTALL LOG_KERN LOG_LAUNCHD LOG_LFMT LOG_LOCAL0
28 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4 LOG_LOCAL5
29 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR LOG_MAIL LOG_NETINFO
30 LOG_NEWS LOG_RAS LOG_REMOTEAUTH LOG_SYSLOG LOG_USER LOG_UUCP
31 ),
32
33 # options
34 qw(
35 LOG_CONS LOG_PID LOG_NDELAY LOG_NOWAIT LOG_ODELAY LOG_PERROR
36 ),
37
38 # others macros
39 qw(
40 LOG_FACMASK LOG_NFACILITIES LOG_PRIMASK
41 LOG_MASK LOG_UPTO
42 ),
43 ],
89c3c464 44 );
942974c1 45
89c3c464 46 @EXPORT = (
942974c1 47 @{$EXPORT_TAGS{standard}},
89c3c464 48 );
942974c1 49
89c3c464 50 @EXPORT_OK = (
942974c1 51 @{$EXPORT_TAGS{extended}},
52 @{$EXPORT_TAGS{macros}},
89c3c464 53 );
54
55 eval {
56 require XSLoader;
57 XSLoader::load('Sys::Syslog', $VERSION);
58 1
59 } or do {
60 require DynaLoader;
61 push @ISA, 'DynaLoader';
62 bootstrap Sys::Syslog $VERSION;
63 };
64}
65
66
67#
68# Public variables
69#
70our $host; # host to send syslog messages to
71
72#
73# Global variables
74#
75my $connected = 0; # flag to indicate if we're connected or not
76my $syslog_send; # coderef of the function used to send messages
77my $syslog_path = undef; # syslog path for "stream" and "unix" mechanisms
78my $transmit_ok = 0; # flag to indicate if the last message was transmited
79my $current_proto = undef; # current mechanism used to transmit messages
80my $ident = ''; # identifiant prepended to each message
81my $facility = ''; # current facility
82my $maskpri = LOG_UPTO(&LOG_DEBUG); # current log mask
83
84my %options = (
85 ndelay => 0,
86 nofatal => 0,
87 nowait => 0,
88 pid => 0,
942974c1 89);
a0d0e21e 90
23642f4b 91# it would be nice to try stream/unix first, since that will be
92# most efficient. However streams are dodgy - see _syslog_send_stream
8edeb3ad 93my @connectMethods = qw(native tcp udp unix stream console);
dbfdd438 94if ($^O =~ /^(freebsd|linux)$/) {
95 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
96}
23642f4b 97my @defaultMethods = @connectMethods;
89c3c464 98my @fallbackMethods = ();
8168e71f 99
89c3c464 100# coderef for a nicer handling of errors
101my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
5be1dfc7 102
5be1dfc7 103
89c3c464 104sub AUTOLOAD {
105 # This AUTOLOAD is used to 'autoload' constants from the constant()
106 # XS function.
107 no strict 'vars';
108 my $constname;
109 ($constname = $AUTOLOAD) =~ s/.*:://;
110 croak "Sys::Syslog::constant() not defined" if $constname eq 'constant';
111 my ($error, $val) = constant($constname);
112 croak $error if $error;
113 no strict 'refs';
114 *$AUTOLOAD = sub { $val };
115 goto &$AUTOLOAD;
116}
5be1dfc7 117
5be1dfc7 118
89c3c464 119sub openlog {
120 ($ident, my $logopt, $facility) = @_;
8168e71f 121
89c3c464 122 for my $opt (split /\b/, $logopt) {
123 $options{$opt} = 1 if exists $options{$opt}
124 }
5be1dfc7 125
89c3c464 126 $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
127 return 1 unless $options{ndelay};
128 connect_log();
129}
5be1dfc7 130
89c3c464 131sub closelog {
132 $facility = $ident = '';
133 disconnect_log();
134}
8168e71f 135
89c3c464 136sub setlogmask {
137 my $oldmask = $maskpri;
138 $maskpri = shift unless $_[0] == 0;
139 $oldmask;
140}
8168e71f 141
89c3c464 142sub setlogsock {
143 my $setsock = shift;
144 $syslog_path = shift;
145 disconnect_log() if $connected;
146 $transmit_ok = 0;
147 @fallbackMethods = ();
148 @connectMethods = @defaultMethods;
942974c1 149
89c3c464 150 if (ref $setsock eq 'ARRAY') {
151 @connectMethods = @$setsock;
942974c1 152
89c3c464 153 } elsif (lc $setsock eq 'stream') {
154 unless (defined $syslog_path) {
155 my @try = qw(/dev/log /dev/conslog);
156 if (length &_PATH_LOG) { # Undefined _PATH_LOG is "".
157 unshift @try, &_PATH_LOG;
158 }
159 for my $try (@try) {
160 if (-w $try) {
161 $syslog_path = $try;
162 last;
163 }
164 }
165 warnings::warnif "stream passed to setlogsock, but could not find any device"
166 unless defined $syslog_path
167 }
168 unless (-w $syslog_path) {
169 warnings::warnif "stream passed to setlogsock, but $syslog_path is not writable";
170 return undef;
171 } else {
172 @connectMethods = ( 'stream' );
173 }
942974c1 174
89c3c464 175 } elsif (lc $setsock eq 'unix') {
8edeb3ad 176 if (length _PATH_LOG() || (defined $syslog_path && -w $syslog_path)) {
177 $syslog_path = _PATH_LOG() unless defined $syslog_path;
89c3c464 178 @connectMethods = ( 'unix' );
179 } else {
180 warnings::warnif 'unix passed to setlogsock, but path not available';
181 return undef;
182 }
8168e71f 183
89c3c464 184 } elsif (lc $setsock eq 'native') {
185 @connectMethods = ( 'native' );
8168e71f 186
89c3c464 187 } elsif (lc $setsock eq 'tcp') {
188 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
189 @connectMethods = ( 'tcp' );
190 } else {
191 warnings::warnif "tcp passed to setlogsock, but tcp service unavailable";
192 return undef;
193 }
942974c1 194
89c3c464 195 } elsif (lc $setsock eq 'udp') {
196 if (getservbyname('syslog', 'udp')) {
197 @connectMethods = ( 'udp' );
198 } else {
199 warnings::warnif "udp passed to setlogsock, but udp service unavailable";
200 return undef;
201 }
942974c1 202
89c3c464 203 } elsif (lc $setsock eq 'inet') {
204 @connectMethods = ( 'tcp', 'udp' );
942974c1 205
89c3c464 206 } elsif (lc $setsock eq 'console') {
207 @connectMethods = ( 'console' );
942974c1 208
89c3c464 209 } else {
210 croak "Invalid argument passed to setlogsock; must be 'stream', 'unix', 'native', 'tcp', 'udp' or 'inet'"
211 }
942974c1 212
89c3c464 213 return 1;
214}
942974c1 215
89c3c464 216sub syslog {
217 my $priority = shift;
218 my $mask = shift;
219 my ($message, $buf);
220 my (@words, $num, $numpri, $numfac, $sum);
221 my $failed = undef;
222 my $fail_time = undef;
8edeb3ad 223 my $error = $!;
8168e71f 224
89c3c464 225 my $facility = $facility; # may need to change temporarily.
8168e71f 226
89c3c464 227 croak "syslog: expecting argument \$priority" unless defined $priority;
228 croak "syslog: expecting argument \$format" unless defined $mask;
5be1dfc7 229
8edeb3ad 230 @words = split(/\W+/, $priority, 2); # Allow "level" or "level|facility".
89c3c464 231 undef $numpri;
232 undef $numfac;
5be1dfc7 233
89c3c464 234 foreach (@words) {
8edeb3ad 235 $num = xlate($_); # Translate word to number.
89c3c464 236 if ($num < 0) {
237 croak "syslog: invalid level/facility: $_"
238 }
239 elsif ($num <= &LOG_PRIMASK) {
240 croak "syslog: too many levels given: $_" if defined $numpri;
241 $numpri = $num;
242 return 0 unless LOG_MASK($numpri) & $maskpri;
243 }
244 else {
245 croak "syslog: too many facilities given: $_" if defined $numfac;
246 $facility = $_;
247 $numfac = $num;
248 }
249 }
5be1dfc7 250
89c3c464 251 croak "syslog: level must be given" unless defined $numpri;
942974c1 252
89c3c464 253 if (not defined $numfac) { # Facility not specified in this call.
254 $facility = 'user' unless $facility;
255 $numfac = xlate($facility);
256 }
3d256c0f 257
89c3c464 258 connect_log() unless $connected;
8168e71f 259
89c3c464 260 if ($mask =~ /%m/) {
89c3c464 261 # escape percent signs if sprintf will be called
8edeb3ad 262 $error =~ s/%/%%/g if @_;
89c3c464 263 # replace %m with $err, if preceded by an even number of percent signs
8edeb3ad 264 $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
89c3c464 265 }
5be1dfc7 266
89c3c464 267 $mask .= "\n" unless $mask =~ /\n$/;
268 $message = @_ ? sprintf($mask, @_) : $mask;
942974c1 269
89c3c464 270 if($current_proto eq 'native') {
271 $buf = $message;
942974c1 272
89c3c464 273 } else {
274 my $whoami = $ident;
942974c1 275
89c3c464 276 if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
277 $whoami = $1;
278 $mask = $2;
279 }
942974c1 280
89c3c464 281 unless ($whoami) {
282 $whoami = getlogin() || getpwuid($<) || 'syslog';
283 }
942974c1 284
89c3c464 285 $whoami .= "[$$]" if $options{pid};
942974c1 286
89c3c464 287 $sum = $numpri + $numfac;
288 my $oldlocale = setlocale(LC_TIME);
289 setlocale(LC_TIME, 'C');
290 my $timestamp = strftime "%b %e %T", localtime;
291 setlocale(LC_TIME, $oldlocale);
292 $buf = "<$sum>$timestamp $whoami: $message\0";
293 }
942974c1 294
89c3c464 295 # it's possible that we'll get an error from sending
296 # (e.g. if method is UDP and there is no UDP listener,
297 # then we'll get ECONNREFUSED on the send). So what we
298 # want to do at this point is to fallback onto a different
299 # connection method.
300 while (scalar @fallbackMethods || $syslog_send) {
301 if ($failed && (time - $fail_time) > 60) {
302 # it's been a while... maybe things have been fixed
303 @fallbackMethods = ();
304 disconnect_log();
305 $transmit_ok = 0; # make it look like a fresh attempt
306 connect_log();
307 }
942974c1 308
89c3c464 309 if ($connected && !connection_ok()) {
310 # Something was OK, but has now broken. Remember coz we'll
311 # want to go back to what used to be OK.
312 $failed = $current_proto unless $failed;
313 $fail_time = time;
314 disconnect_log();
315 }
942974c1 316
89c3c464 317 connect_log() unless $connected;
318 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
942974c1 319
89c3c464 320 if ($syslog_send) {
321 if ($syslog_send->($buf, $numpri)) {
322 $transmit_ok++;
323 return 1;
324 }
325 # typically doesn't happen, since errors are rare from write().
326 disconnect_log();
327 }
328 }
329 # could not send, could not fallback onto a working
330 # connection method. Lose.
331 return 0;
332}
942974c1 333
89c3c464 334sub _syslog_send_console {
335 my ($buf) = @_;
336 chop($buf); # delete the NUL from the end
337 # The console print is a method which could block
338 # so we do it in a child process and always return success
339 # to the caller.
340 if (my $pid = fork) {
942974c1 341
89c3c464 342 if ($options{nowait}) {
343 return 1;
344 } else {
345 if (waitpid($pid, 0) >= 0) {
346 return ($? >> 8);
347 } else {
348 # it's possible that the caller has other
349 # plans for SIGCHLD, so let's not interfere
350 return 1;
351 }
352 }
353 } else {
354 if (open(CONS, ">/dev/console")) {
355 my $ret = print CONS $buf . "\r"; # XXX: should this be \x0A ?
356 exit $ret if defined $pid;
357 close CONS;
358 }
359 exit if defined $pid;
360 }
361}
942974c1 362
89c3c464 363sub _syslog_send_stream {
364 my ($buf) = @_;
365 # XXX: this only works if the OS stream implementation makes a write
366 # look like a putmsg() with simple header. For instance it works on
367 # Solaris 8 but not Solaris 7.
368 # To be correct, it should use a STREAMS API, but perl doesn't have one.
369 return syswrite(SYSLOG, $buf, length($buf));
370}
942974c1 371
89c3c464 372sub _syslog_send_socket {
373 my ($buf) = @_;
374 return syswrite(SYSLOG, $buf, length($buf));
375 #return send(SYSLOG, $buf, 0);
376}
942974c1 377
89c3c464 378sub _syslog_send_native {
379 my ($buf, $numpri) = @_;
380 eval { syslog_xs($numpri, $buf) };
381 return $@ ? 0 : 1;
382}
ce43db9b 383
5be1dfc7 384
89c3c464 385# xlate()
386# -----
387# private function to translate names to numeric values
388#
389sub xlate {
390 my($name) = @_;
391 return $name+0 if $name =~ /^\s*\d+\s*$/;
392 $name = uc $name;
393 $name = "LOG_$name" unless $name =~ /^LOG_/;
394 $name = "Sys::Syslog::$name";
395 # Can't have just eval { &$name } || -1 because some LOG_XXX may be zero.
396 my $value = eval { no strict 'refs'; &$name };
397 defined $value ? $value : -1;
398}
5be1dfc7 399
942974c1 400
89c3c464 401# connect_log()
402# -----------
403# This function acts as a kind of front-end: it tries to connect to
404# a syslog service using the selected methods, trying each one in the
405# selected order.
406#
407sub connect_log {
408 @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
409 if ($transmit_ok && $current_proto) {
410 # Retry what we were on, because it has worked in the past.
411 unshift(@fallbackMethods, $current_proto);
412 }
413 $connected = 0;
414 my @errs = ();
415 my $proto = undef;
416 while ($proto = shift @fallbackMethods) {
417 no strict 'refs';
418 my $fn = "connect_$proto";
419 $connected = &$fn(\@errs) if defined &$fn;
420 last if $connected;
421 }
3d256c0f 422
89c3c464 423 $transmit_ok = 0;
424 if ($connected) {
425 $current_proto = $proto;
426 my($old) = select(SYSLOG); $| = 1; select($old);
427 } else {
428 @fallbackMethods = ();
429 $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
430 return undef;
431 }
432}
942974c1 433
89c3c464 434sub connect_tcp {
435 my ($errs) = @_;
4b035b3d 436
89c3c464 437 my $tcp = getprotobyname('tcp');
438 if (!defined $tcp) {
439 push @$errs, "getprotobyname failed for tcp";
440 return 0;
441 }
4b035b3d 442
443 my $syslog = getservbyname('syslog', 'tcp');
444 $syslog = getservbyname('syslogng', 'tcp') unless defined $syslog;
89c3c464 445 if (!defined $syslog) {
446 push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
447 return 0;
448 }
942974c1 449
4b035b3d 450 my $addr;
89c3c464 451 if (defined $host) {
4b035b3d 452 $addr = inet_aton($host);
453 if (!$addr) {
89c3c464 454 push @$errs, "can't lookup $host";
455 return 0;
456 }
457 } else {
4b035b3d 458 $addr = INADDR_LOOPBACK;
89c3c464 459 }
4b035b3d 460 $addr = sockaddr_in($syslog, $addr);
942974c1 461
89c3c464 462 if (!socket(SYSLOG, AF_INET, SOCK_STREAM, $tcp)) {
463 push @$errs, "tcp socket: $!";
464 return 0;
465 }
466 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
467 setsockopt(SYSLOG, &IPPROTO_TCP, &TCP_NODELAY, 1);
4b035b3d 468 if (!connect(SYSLOG, $addr)) {
89c3c464 469 push @$errs, "tcp connect: $!";
470 return 0;
471 }
4b035b3d 472
89c3c464 473 $syslog_send = \&_syslog_send_socket;
4b035b3d 474
89c3c464 475 return 1;
476}
942974c1 477
89c3c464 478sub connect_udp {
479 my ($errs) = @_;
4b035b3d 480
89c3c464 481 my $udp = getprotobyname('udp');
482 if (!defined $udp) {
483 push @$errs, "getprotobyname failed for udp";
484 return 0;
485 }
4b035b3d 486
487 my $syslog = getservbyname('syslog', 'udp');
89c3c464 488 if (!defined $syslog) {
489 push @$errs, "getservbyname failed for syslog/udp";
490 return 0;
491 }
4b035b3d 492
493 my $addr;
89c3c464 494 if (defined $host) {
4b035b3d 495 $addr = inet_aton($host);
496 if (!$addr) {
89c3c464 497 push @$errs, "can't lookup $host";
498 return 0;
499 }
500 } else {
4b035b3d 501 $addr = INADDR_LOOPBACK;
89c3c464 502 }
4b035b3d 503 $addr = sockaddr_in($syslog, $addr);
942974c1 504
89c3c464 505 if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, $udp)) {
506 push @$errs, "udp socket: $!";
507 return 0;
508 }
4b035b3d 509 if (!connect(SYSLOG, $addr)) {
89c3c464 510 push @$errs, "udp connect: $!";
511 return 0;
512 }
4b035b3d 513
89c3c464 514 # We want to check that the UDP connect worked. However the only
515 # way to do that is to send a message and see if an ICMP is returned
516 _syslog_send_socket("");
517 if (!connection_ok()) {
518 push @$errs, "udp connect: nobody listening";
519 return 0;
520 }
4b035b3d 521
89c3c464 522 $syslog_send = \&_syslog_send_socket;
4b035b3d 523
89c3c464 524 return 1;
525}
9903e4c8 526
89c3c464 527sub connect_stream {
528 my ($errs) = @_;
529 # might want syslog_path to be variable based on syslog.h (if only
530 # it were in there!)
8edeb3ad 531 $syslog_path = '/dev/conslog' unless defined $syslog_path;
89c3c464 532 if (!-w $syslog_path) {
533 push @$errs, "stream $syslog_path is not writable";
534 return 0;
535 }
536 if (!open(SYSLOG, ">" . $syslog_path)) {
537 push @$errs, "stream can't open $syslog_path: $!";
538 return 0;
539 }
540 $syslog_send = \&_syslog_send_stream;
541 return 1;
542}
942974c1 543
89c3c464 544sub connect_unix {
545 my ($errs) = @_;
4b035b3d 546
547 $syslog_path ||= _PATH_LOG() if length _PATH_LOG();
548
549 if (not defined $syslog_path) {
550 push @$errs, "_PATH_LOG not available in syslog.h and no user-supplied socket path";
89c3c464 551 return 0;
552 }
4b035b3d 553
89c3c464 554 if (! -S $syslog_path) {
555 push @$errs, "$syslog_path is not a socket";
556 return 0;
557 }
4b035b3d 558
559 my $addr = sockaddr_un($syslog_path);
560 if (!$addr) {
89c3c464 561 push @$errs, "can't locate $syslog_path";
562 return 0;
563 }
4b035b3d 564 if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
89c3c464 565 push @$errs, "unix stream socket: $!";
566 return 0;
567 }
4b035b3d 568 if (!connect(SYSLOG, $addr)) {
569 if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
89c3c464 570 push @$errs, "unix dgram socket: $!";
571 return 0;
572 }
4b035b3d 573 if (!connect(SYSLOG, $addr)) {
89c3c464 574 push @$errs, "unix dgram connect: $!";
575 return 0;
576 }
577 }
4b035b3d 578
89c3c464 579 $syslog_send = \&_syslog_send_socket;
4b035b3d 580
89c3c464 581 return 1;
582}
942974c1 583
89c3c464 584sub connect_native {
585 my ($errs) = @_;
586 my $logopt = 0;
5be1dfc7 587
89c3c464 588 # reconstruct the numeric equivalent of the options
589 for my $opt (keys %options) {
590 $logopt += xlate($opt) if $options{$opt}
591 }
942974c1 592
89c3c464 593 eval { openlog_xs($ident, $logopt, xlate($facility)) };
594 if ($@) {
595 push @$errs, $@;
596 return 0;
597 }
942974c1 598
89c3c464 599 $syslog_send = \&_syslog_send_native;
942974c1 600
89c3c464 601 return 1;
602}
6e4ef777 603
89c3c464 604sub connect_console {
605 my ($errs) = @_;
606 if (!-w '/dev/console') {
607 push @$errs, "console is not writable";
608 return 0;
609 }
610 $syslog_send = \&_syslog_send_console;
611 return 1;
612}
6e4ef777 613
89c3c464 614# to test if the connection is still good, we need to check if any
615# errors are present on the connection. The errors will not be raised
616# by a write. Instead, sockets are made readable and the next read
617# would cause the error to be returned. Unfortunately the syslog
618# 'protocol' never provides anything for us to read. But with
619# judicious use of select(), we can see if it would be readable...
620sub connection_ok {
621 return 1 if defined $current_proto and (
622 $current_proto eq 'native' or $current_proto eq 'console'
623 );
624 my $rin = '';
625 vec($rin, fileno(SYSLOG), 1) = 1;
626 my $ret = select $rin, undef, $rin, 0;
627 return ($ret ? 0 : 1);
628}
942974c1 629
89c3c464 630sub disconnect_log {
631 $connected = 0;
632 $syslog_send = undef;
942974c1 633
89c3c464 634 if($current_proto eq 'native') {
635 eval { close_xs() };
636 return 1;
637 }
6e4ef777 638
89c3c464 639 return close SYSLOG;
640}
6e4ef777 641
89c3c464 6421;
942974c1 643
89c3c464 644__END__
5be1dfc7 645
89c3c464 646=head1 NAME
8168e71f 647
89c3c464 648Sys::Syslog - Perl interface to the UNIX syslog(3) calls
3ffabb8c 649
89c3c464 650=head1 VERSION
3ffabb8c 651
4b035b3d 652Version 0.17
23642f4b 653
89c3c464 654=head1 SYNOPSIS
cb63fe9d 655
89c3c464 656 use Sys::Syslog; # all except setlogsock(), or:
657 use Sys::Syslog qw(:DEFAULT setlogsock); # default set, plus setlogsock()
658 use Sys::Syslog qw(:standard :macros); # standard functions, plus macros
23642f4b 659
89c3c464 660 setlogsock $sock_type;
661 openlog $ident, $logopt, $facility; # don't forget this
662 syslog $priority, $format, @args;
663 $oldmask = setlogmask $mask_priority;
664 closelog;
cb63fe9d 665
942974c1 666
89c3c464 667=head1 DESCRIPTION
5be1dfc7 668
89c3c464 669C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
670Call C<syslog()> with a string priority and a list of C<printf()> args
671just like C<syslog(3)>.
5be1dfc7 672
5be1dfc7 673
89c3c464 674=head1 EXPORTS
5be1dfc7 675
89c3c464 676C<Sys::Syslog> exports the following C<Exporter> tags:
5be1dfc7 677
89c3c464 678=over 4
679
680=item *
681
682C<:standard> exports the standard C<syslog(3)> functions:
683
684 openlog closelog setlogmask syslog
685
686=item *
687
688C<:extended> exports the Perl specific functions for C<syslog(3)>:
689
690 setlogsock
691
692=item *
693
694C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
695macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions.
696See L<"CONSTANTS"> for the supported constants and their meaning.
697
698=back
699
700By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
701
702
703=head1 FUNCTIONS
704
705=over 4
706
707=item B<openlog($ident, $logopt, $facility)>
708
709Opens the syslog.
710C<$ident> is prepended to every message. C<$logopt> contains zero or
711more of the options detailed below. C<$facility> specifies the part
712of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
713see L<"Facilities"> for a list of well-known facilities, and your
714C<syslog(3)> documentation for the facilities available in your system.
715Check L<"SEE ALSO"> for useful links. Facility can be given as a string
716or a numeric macro.
717
718This function will croak if it can't connect to the syslog daemon.
719
720Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
721
722B<You should use C<openlog()> before calling C<syslog()>.>
723
724B<Options>
725
726=over 4
727
728=item *
729
730C<cons> - This option is ignored, since the failover mechanism will drop
731down to the console automatically if all other media fail.
732
733=item *
734
735C<ndelay> - Open the connection immediately (normally, the connection is
736opened when the first message is logged).
737
738=item *
739
740C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only
741emit warnings instead of dying if the connection to the syslog can't
742be established.
743
744=item *
745
746C<nowait> - Don't wait for child processes that may have been created
747while logging the message. (The GNU C library does not create a child
748process, so this option has no effect on Linux.)
749
750=item *
751
752C<pid> - Include PID with each message.
753
754=back
755
756B<Examples>
757
758Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
759
760 openlog($name, "ndelay,pid", "local0");
761
762Same thing, but this time using the macro corresponding to C<LOCAL0>:
763
764 openlog($name, "ndelay,pid", LOG_LOCAL0);
765
766
767=item B<syslog($priority, $message)>
768
769=item B<syslog($priority, $format, @args)>
770
771If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
772with the addition that C<%m> in $message or C<$format> is replaced with
773C<"$!"> (the latest error message).
774
775C<$priority> can specify a level, or a level and a facility. Levels and
776facilities can be given as strings or as macros.
777
778If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
779try to guess the C<$ident> by extracting the shortest prefix of
780C<$format> that ends in a C<":">.
781
782B<Examples>
783
784 syslog("info", $message); # informational level
785 syslog(LOG_INFO, $message); # informational level
786
787 syslog("info|local0", $message); # information level, Local0 facility
788 syslog(LOG_INFO|LOG_LOCAL0, $message); # information level, Local0 facility
789
790=over 4
791
792=item B<Note>
793
794C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
795formatting string to C<sprintf()> even when no formatting arguments
796were provided. If the code calling C<syslog()> might execute with
797older versions of this module, make sure to call the function as
798C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
799$message)>. This protects against hostile formatting sequences that
800might show up if $message contains tainted data.
801
802=back
803
804
805=item B<setlogmask($mask_priority)>
806
807Sets the log mask for the current process to C<$mask_priority> and
808returns the old mask. If the mask argument is 0, the current log mask
809is not modified. See L<"Levels"> for the list of available levels.
810You can use the C<LOG_UPTO()> function to allow all levels up to a
811given priority (but it only accept the numeric macros as arguments).
812
813B<Examples>
814
815Only log errors:
816
817 setlogmask( LOG_MASK(LOG_ERR) );
818
819Log everything except informational messages:
820
821 setlogmask( ~(LOG_MASK(LOG_INFO)) );
822
823Log critical messages, errors and warnings:
824
825 setlogmask( LOG_MASK(LOG_CRIT) | LOG_MASK(LOG_ERR) | LOG_MASK(LOG_WARNING) );
826
827Log all messages up to debug:
828
829 setlogmask( LOG_UPTO(LOG_DEBUG) );
830
831
832=item B<setlogsock($sock_type)>
833
834=item B<setlogsock($sock_type, $stream_location)> (added in 5.004_02)
835
836Sets the socket type to be used for the next call to
837C<openlog()> or C<syslog()> and returns true on success,
4b035b3d 838C<undef> on failure. The available mechanisms are:
839
840=over
841
842=item *
843
844C<"native"> - use the native C functions from your C<syslog(3)> library.
845
846=item *
847
848C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp>
849service.
850
851=item *
852
853C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
854
855=item *
856
857C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that order.
858
859=item *
860
861C<"unix"> - connect to a UNIX domain socket (in some systems a character
862special device). The name of that socket is the second parameter or, if
863you omit the second parameter, the value returned by the C<_PATH_LOG> macro
864(if your system defines it), or F</dev/log> or F</dev/conslog>, whatever is
865writable.
866
867=item *
868
869C<"stream"> - connect to the stream indicated by the pathname provided as
870the optional second parameter, or, if omitted, to F</dev/conslog>.
871For example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">.
872
873=item *
874
875C<"console"> - send messages directly to the console, as for the C<"cons">
876option of C<openlog()>.
877
878=back
89c3c464 879
880A reference to an array can also be passed as the first parameter.
881When this calling method is used, the array should contain a list of
4b035b3d 882mechanisms which are attempted in order.
89c3c464 883
4b035b3d 884The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<stream>, C<console>.
89c3c464 885
886Giving an invalid value for C<$sock_type> will croak.
887
4b035b3d 888B<Examples>
889
890Select the UDP socket mechanism:
891
892 setlogsock("udp");
893
894Select the native, UDP socket then UNIX domain socket mechanisms:
895
896 setlogsock(["native", "udp", "unix"]);
897
89c3c464 898
899=item B<closelog()>
900
4b035b3d 901Closes the log file and returns true on success.
89c3c464 902
903=back
904
905
906=head1 EXAMPLES
907
908 openlog($program, 'cons,pid', 'user');
909 syslog('info', '%s', 'this is another test');
910 syslog('mail|warning', 'this is a better test: %d', time);
911 closelog();
5be1dfc7 912
913 syslog('debug', 'this is the last test');
cb63fe9d 914
915 setlogsock('unix');
5be1dfc7 916 openlog("$program $$", 'ndelay', 'user');
917 syslog('notice', 'fooprogram: this is really done');
918
cb63fe9d 919 setlogsock('inet');
5be1dfc7 920 $! = 55;
6e4ef777 921 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
922
923Log to UDP port on C<$remotehost> instead of logging locally:
5be1dfc7 924
476b65d9 925 setlogsock('udp');
926 $Sys::Syslog::host = $remotehost;
927 openlog($program, 'ndelay', 'user');
928 syslog('info', 'something happened over here');
929
8168e71f 930
931=head1 CONSTANTS
932
933=head2 Facilities
934
935=over 4
936
937=item *
938
939C<LOG_AUTH> - security/authorization messages
940
941=item *
942
943C<LOG_AUTHPRIV> - security/authorization messages (private)
944
945=item *
946
4b035b3d 947C<LOG_CRON> - clock daemons (B<cron> and B<at>)
8168e71f 948
949=item *
950
951C<LOG_DAEMON> - system daemons without separate facility value
952
953=item *
954
4b035b3d 955C<LOG_FTP> - FTP daemon
8168e71f 956
957=item *
958
959C<LOG_KERN> - kernel messages
960
961=item *
962
4b035b3d 963C<LOG_INSTALL> - installer subsystem
964
965=item *
966
967C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X)
968
969=item *
970
8168e71f 971C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
972
973=item *
974
975C<LOG_LPR> - line printer subsystem
976
977=item *
978
979C<LOG_MAIL> - mail subsystem
980
981=item *
982
4b035b3d 983C<LOG_NETINFO> - NetInfo subsystem (Mac OS X)
984
985=item *
986
8168e71f 987C<LOG_NEWS> - USENET news subsystem
988
989=item *
990
4b035b3d 991C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X)
992
993=item *
994
995C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X)
996
997=item *
998
8168e71f 999C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1000
1001=item *
1002
1003C<LOG_USER> (default) - generic user-level messages
1004
1005=item *
1006
1007C<LOG_UUCP> - UUCP subsystem
1008
1009=back
1010
1011
1012=head2 Levels
1013
1014=over 4
1015
1016=item *
1017
1018C<LOG_EMERG> - system is unusable
1019
1020=item *
1021
1022C<LOG_ALERT> - action must be taken immediately
1023
1024=item *
1025
1026C<LOG_CRIT> - critical conditions
1027
1028=item *
1029
942974c1 1030C<LOG_ERR> - error conditions
8168e71f 1031
1032=item *
1033
1034C<LOG_WARNING> - warning conditions
1035
1036=item *
1037
1038C<LOG_NOTICE> - normal, but significant, condition
1039
1040=item *
1041
1042C<LOG_INFO> - informational message
1043
1044=item *
1045
1046C<LOG_DEBUG> - debug-level message
1047
1048=back
1049
1050
1051=head1 DIAGNOSTICS
1052
1053=over 4
1054
1055=item Invalid argument passed to setlogsock
1056
1057B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
1058
1059=item no connection to syslog available
1060
1061B<(F)> C<syslog()> failed to connect to the specified socket.
1062
1063=item stream passed to setlogsock, but %s is not writable
1064
942974c1 1065B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
8168e71f 1066path is not writable.
1067
1068=item stream passed to setlogsock, but could not find any device
1069
942974c1 1070B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
8168e71f 1071provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1072
1073=item tcp passed to setlogsock, but tcp service unavailable
1074
942974c1 1075B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
8168e71f 1076is not available on the system.
1077
1078=item syslog: expecting argument %s
1079
1080B<(F)> You forgot to give C<syslog()> the indicated argument.
1081
1082=item syslog: invalid level/facility: %s
1083
6e4ef777 1084B<(F)> You specified an invalid level or facility.
8168e71f 1085
1086=item syslog: too many levels given: %s
1087
1088B<(F)> You specified too many levels.
1089
1090=item syslog: too many facilities given: %s
1091
1092B<(F)> You specified too many facilities.
1093
1094=item syslog: level must be given
1095
1096B<(F)> You forgot to specify a level.
1097
1098=item udp passed to setlogsock, but udp service unavailable
1099
942974c1 1100B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
8168e71f 1101is not available on the system.
1102
1103=item unix passed to setlogsock, but path not available
1104
942974c1 1105B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
8168e71f 1106was unable to find an appropriate an appropriate device.
1107
1108=back
1109
1110
5be1dfc7 1111=head1 SEE ALSO
1112
1113L<syslog(3)>
1114
6e4ef777 1115SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
1116L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1117
1118GNU C Library documentation on syslog,
1119L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1120
1121Solaris 10 documentation on syslog,
1122L<http://docs.sun.com/app/docs/doc/816-5168/6mbb3hruo?a=view>
1123
1124AIX 5L 5.3 documentation on syslog,
1125L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.doc/libs/basetrf2/syslog.htm>
1126
1127HP-UX 11i documentation on syslog,
1128L<http://docs.hp.com/en/B9106-90010/syslog.3C.html>
1129
1130Tru64 5.1 documentation on syslog,
1131L<http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51_HTML/MAN/MAN3/0193____.HTM>
1132
1133Stratus VOS 15.1,
1134L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1135
1136I<RFC 3164 - The BSD syslog Protocol>, L<http://www.faqs.org/rfcs/rfc3164.html>
1137-- Please note that this is an informational RFC, and therefore does not
1138specify a standard of any kind.
1139
1140I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1141
04f98b29 1142I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1143
8168e71f 1144
6e4ef777 1145=head1 AUTHORS
5be1dfc7 1146
150b260b 1147Tom Christiansen E<lt>F<tchrist@perl.com>E<gt> and Larry Wall
1148E<lt>F<larry@wall.org>E<gt>.
1149
1150UNIX domain sockets added by Sean Robinson
23642f4b 1151E<lt>F<robinson_s@sc.maricopa.edu>E<gt> with support from Tim Bunce
8168e71f 1152E<lt>F<Tim.Bunce@ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
150b260b 1153
1154Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
1155E<lt>F<tom@compton.nu>E<gt>.
5be1dfc7 1156
8168e71f 1157Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick@ccl4.org>E<gt>.
23642f4b 1158
1159Failover to different communication modes by Nick Williams
1160E<lt>F<Nick.Williams@morganstanley.com>E<gt>.
b903fcff 1161
89c3c464 1162XS code for using native C functions borrowed from C<L<Unix::Syslog>>,
1163written by Marcus Harnisch E<lt>F<marcus.harnisch@gmx.net>E<gt>.
1164
8168e71f 1165Extracted from core distribution for publishing on the CPAN by
1166SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien@aperghis.netE<gt>.
1167
1168
1169=head1 BUGS
1170
1171Please report any bugs or feature requests to
1172C<bug-sys-syslog at rt.cpan.org>, or through the web interface at
1173L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sys-Syslog>.
1174I will be notified, and then you'll automatically be notified of progress on
1175your bug as I make changes.
1176
1177
1178=head1 SUPPORT
1179
1180You can find documentation for this module with the perldoc command.
1181
1182 perldoc Sys::Syslog
1183
1184You can also look for information at:
1185
1186=over 4
1187
1188=item * AnnoCPAN: Annotated CPAN documentation
1189
1190L<http://annocpan.org/dist/Sys-Syslog>
1191
1192=item * CPAN Ratings
1193
1194L<http://cpanratings.perl.org/d/Sys-Syslog>
1195
1196=item * RT: CPAN's request tracker
1197
1198L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Sys-Syslog>
1199
1200=item * Search CPAN
1201
6e4ef777 1202L<http://search.cpan.org/dist/Sys-Syslog/>
1203
1204=item * Kobes' CPAN Search
1205
1206L<http://cpan.uwinnipeg.ca/dist/Sys-Syslog>
1207
1208=item * Perl Documentation
1209
1210L<http://perldoc.perl.org/Sys/Syslog.html>
8168e71f 1211
1212=back
1213
1214
1215=head1 LICENSE
1216
1217This program is free software; you can redistribute it and/or modify it
1218under the same terms as Perl itself.
1219
5be1dfc7 1220=cut