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