Fw: CPAN Upload: S/SA/SAPER/Sys-Syslog-0.15.tar.gz
[p5sagit/p5-mst-13.2.git] / ext / Sys / Syslog / Syslog.pm
1 package Sys::Syslog;
2 use strict;
3 use warnings::register;
4 use Carp;
5 use POSIX qw(strftime setlocale LC_TIME);
6 use Socket ':all';
7 require 5.006;
8 require Exporter;
9
10 {   no strict 'vars';
11     $VERSION = '0.15';
12     @ISA = qw(Exporter);
13
14     %EXPORT_TAGS = (
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
25         LOG_MASK LOG_UPTO
26     )],
27     );
28
29     @EXPORT = (
30     @{$EXPORT_TAGS{standard}}, 
31     );
32
33     @EXPORT_OK = (
34     @{$EXPORT_TAGS{extended}}, 
35     @{$EXPORT_TAGS{macros}}, 
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
53 our $host;                      # host to send syslog messages to
54
55
56 # Global variables
57
58 my $connected = 0;              # flag to indicate if we're connected or not
59 my $syslog_send;                # coderef of the function used to send messages
60 my $syslog_path = undef;        # syslog path for "stream" and "unix" mechanisms
61 my $transmit_ok = 0;            # flag to indicate if the last message was transmited
62 my $current_proto = undef;      # current mechanism used to transmit messages
63 my $ident = '';                 # identifiant prepended to each message
64 my $facility = '';              # current facility
65 my $maskpri = LOG_UPTO(&LOG_DEBUG);     # current log mask
66
67 my %options = (
68     ndelay  => 0, 
69     nofatal => 0, 
70     nowait  => 0, 
71     pid     => 0, 
72 );
73
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
76 my @connectMethods = ( 'tcp', 'udp', 'unix', 'stream', 'console' );
77 if ($^O =~ /^(freebsd|linux)$/) {
78     @connectMethods = grep { $_ ne 'udp' } @connectMethods;
79 }
80 my @defaultMethods = @connectMethods;
81 my @fallbackMethods = ();
82
83 # coderef for a nicer handling of errors
84 my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
85
86
87 sub 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 }
100
101
102 sub openlog {
103     ($ident, my $logopt, $facility) = @_;
104
105     for my $opt (split /\b/, $logopt) {
106         $options{$opt} = 1 if exists $options{$opt}
107     }
108
109     $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
110     return 1 unless $options{ndelay};
111     connect_log();
112
113
114 sub closelog {
115     $facility = $ident = '';
116     disconnect_log();
117
118
119 sub setlogmask {
120     my $oldmask = $maskpri;
121     $maskpri = shift unless $_[0] == 0;
122     $oldmask;
123 }
124
125 sub setlogsock {
126     my $setsock = shift;
127     $syslog_path = shift;
128     disconnect_log() if $connected;
129     $transmit_ok = 0;
130     @fallbackMethods = ();
131     @connectMethods = @defaultMethods;
132
133     if (ref $setsock eq 'ARRAY') {
134         @connectMethods = @$setsock;
135
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         }
157
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         }
166
167     } elsif (lc $setsock eq 'native') {
168         @connectMethods = ( 'native' );
169
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         }
177
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         }
185
186     } elsif (lc $setsock eq 'inet') {
187         @connectMethods = ( 'tcp', 'udp' );
188
189     } elsif (lc $setsock eq 'console') {
190         @connectMethods = ( 'console' );
191
192     } else {
193         croak "Invalid argument passed to setlogsock; must be 'stream', 'unix', 'native', 'tcp', 'udp' or 'inet'"
194     }
195
196     return 1;
197 }
198
199 sub 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;
206
207     my $facility = $facility;   # may need to change temporarily.
208
209     croak "syslog: expecting argument \$priority" unless defined $priority;
210     croak "syslog: expecting argument \$format"   unless defined $mask;
211
212     @words = split(/\W+/, $priority, 2);# Allow "level" or "level|facility".
213     undef $numpri;
214     undef $numfac;
215
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     }
232
233     croak "syslog: level must be given" unless defined $numpri;
234
235     if (not defined $numfac) {  # Facility not specified in this call.
236         $facility = 'user' unless $facility;
237         $numfac = xlate($facility);
238     }
239
240     connect_log() unless $connected;
241
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     }
249
250     $mask .= "\n" unless $mask =~ /\n$/;
251     $message = @_ ? sprintf($mask, @_) : $mask;
252
253     if($current_proto eq 'native') {
254         $buf = $message;
255
256     } else {
257         my $whoami = $ident;
258
259         if (!$whoami && $mask =~ /^(\S.*?):\s?(.*)/) {
260             $whoami = $1;
261             $mask = $2;
262         }
263
264         unless ($whoami) {
265             $whoami = getlogin() || getpwuid($<) || 'syslog';
266         }
267
268         $whoami .= "[$$]" if $options{pid};
269
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     }
277
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         }
291
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         }
299
300         connect_log() unless $connected;
301         $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
302
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 }
316
317 sub _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) {
324
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 }
345
346 sub _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 }
354
355 sub _syslog_send_socket {
356     my ($buf) = @_;
357     return syswrite(SYSLOG, $buf, length($buf));
358     #return send(SYSLOG, $buf, 0);
359 }
360
361 sub _syslog_send_native {
362     my ($buf, $numpri) = @_;
363     eval { syslog_xs($numpri, $buf) };
364     return $@ ? 0 : 1;
365 }
366
367
368 # xlate()
369 # -----
370 # private function to translate names to numeric values
371
372 sub 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 }
382
383
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
390 sub 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     }
405
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 }
416
417 sub 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     }
430
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);
443
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 }
457
458 sub 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);
482
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 }
501
502 sub 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 }
518
519 sub 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 }
553
554 sub connect_native {
555     my ($errs) = @_;
556     my $logopt = 0;
557
558     # reconstruct the numeric equivalent of the options
559     for my $opt (keys %options) {
560         $logopt += xlate($opt) if $options{$opt}
561     }
562
563     eval { openlog_xs($ident, $logopt, xlate($facility)) };
564     if ($@) {
565         push @$errs, $@;
566         return 0;
567     }
568
569     $syslog_send = \&_syslog_send_native;
570
571     return 1;
572 }
573
574 sub 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 }
583
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...
590 sub 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 }
599
600 sub disconnect_log {
601     $connected = 0;
602     $syslog_send = undef;
603
604     if($current_proto eq 'native') {
605         eval { close_xs() };
606         return 1;
607     }
608
609     return close SYSLOG;
610 }
611
612 1;
613
614 __END__
615
616 =head1 NAME
617
618 Sys::Syslog - Perl interface to the UNIX syslog(3) calls
619
620 =head1 VERSION
621
622 Version 0.15
623
624 =head1 SYNOPSIS
625
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
629
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;
635
636
637 =head1 DESCRIPTION
638
639 C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
640 Call C<syslog()> with a string priority and a list of C<printf()> args
641 just like C<syslog(3)>.
642
643
644 =head1 EXPORTS
645
646 C<Sys::Syslog> exports the following C<Exporter> tags: 
647
648 =over 4
649
650 =item *
651
652 C<:standard> exports the standard C<syslog(3)> functions: 
653
654     openlog closelog setlogmask syslog
655
656 =item *
657
658 C<:extended> exports the Perl specific functions for C<syslog(3)>: 
659
660     setlogsock
661
662 =item *
663
664 C<:macros> exports the symbols corresponding to most of your C<syslog(3)> 
665 macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions. 
666 See L<"CONSTANTS"> for the supported constants and their meaning. 
667
668 =back
669
670 By 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
679 Opens the syslog.
680 C<$ident> is prepended to every message.  C<$logopt> contains zero or
681 more of the options detailed below.  C<$facility> specifies the part 
682 of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
683 see L<"Facilities"> for a list of well-known facilities, and your 
684 C<syslog(3)> documentation for the facilities available in your system. 
685 Check L<"SEE ALSO"> for useful links. Facility can be given as a string 
686 or a numeric macro. 
687
688 This function will croak if it can't connect to the syslog daemon.
689
690 Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
691
692 B<You should use C<openlog()> before calling C<syslog()>.>
693
694 B<Options>
695
696 =over 4
697
698 =item *
699
700 C<cons> - This option is ignored, since the failover mechanism will drop 
701 down to the console automatically if all other media fail.
702
703 =item *
704
705 C<ndelay> - Open the connection immediately (normally, the connection is
706 opened when the first message is logged).
707
708 =item *
709
710 C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only 
711 emit warnings instead of dying if the connection to the syslog can't 
712 be established. 
713
714 =item *
715
716 C<nowait> - Don't wait for child processes that may have been created 
717 while logging the message.  (The GNU C library does not create a child
718 process, so this option has no effect on Linux.)
719
720 =item *
721
722 C<pid> - Include PID with each message.
723
724 =back
725
726 B<Examples>
727
728 Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>: 
729
730     openlog($name, "ndelay,pid", "local0");
731
732 Same 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
741 If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
742 with the addition that C<%m> in $message or C<$format> is replaced with
743 C<"$!"> (the latest error message). 
744
745 C<$priority> can specify a level, or a level and a facility.  Levels and 
746 facilities can be given as strings or as macros.
747
748 If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will 
749 try to guess the C<$ident> by extracting the shortest prefix of 
750 C<$format> that ends in a C<":">.
751
752 B<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
764 C<Sys::Syslog> version v0.07 and older passed the C<$message> as the 
765 formatting string to C<sprintf()> even when no formatting arguments
766 were provided.  If the code calling C<syslog()> might execute with 
767 older versions of this module, make sure to call the function as
768 C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
769 $message)>.  This protects against hostile formatting sequences that
770 might show up if $message contains tainted data.
771
772 =back
773
774
775 =item B<setlogmask($mask_priority)>
776
777 Sets the log mask for the current process to C<$mask_priority> and 
778 returns the old mask.  If the mask argument is 0, the current log mask 
779 is not modified.  See L<"Levels"> for the list of available levels. 
780 You can use the C<LOG_UPTO()> function to allow all levels up to a 
781 given priority (but it only accept the numeric macros as arguments).
782
783 B<Examples>
784
785 Only log errors: 
786
787     setlogmask( LOG_MASK(LOG_ERR) );
788
789 Log everything except informational messages: 
790
791     setlogmask( ~(LOG_MASK(LOG_INFO)) );
792
793 Log critical messages, errors and warnings: 
794
795     setlogmask( LOG_MASK(LOG_CRIT) | LOG_MASK(LOG_ERR) | LOG_MASK(LOG_WARNING) );
796
797 Log 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
806 Sets the socket type to be used for the next call to
807 C<openlog()> or C<syslog()> and returns true on success,
808 C<undef> on failure.
809
810 A value of C<"unix"> will connect to the UNIX domain socket (in some
811 systems 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>,
813 whatever is writable.  A value of 'stream' will connect to the stream
814 indicated by the pathname provided as the optional second parameter.
815 (For example Solaris and IRIX require C<"stream"> instead of C<"unix">.)
816 A value of C<"inet"> will connect to an INET socket (either C<tcp> or C<udp>,
817 tried in that order) returned by C<getservbyname()>. C<"tcp"> and C<"udp"> 
818 can also be given as values. The value C<"console"> will send messages
819 directly to the console, as for the C<"cons"> option in the logopts in
820 C<openlog()>.
821
822 A reference to an array can also be passed as the first parameter.
823 When this calling method is used, the array should contain a list of
824 sock_types which are attempted in order.
825
826 The default is to try C<tcp>, C<udp>, C<unix>, C<stream>, C<console>.
827
828 Giving an invalid value for C<$sock_type> will croak.
829
830
831 =item B<closelog()>
832
833 Closes 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();
844
845     syslog('debug', 'this is the last test');
846
847     setlogsock('unix');
848     openlog("$program $$", 'ndelay', 'user');
849     syslog('notice', 'fooprogram: this is really done');
850
851     setlogsock('inet');
852     $! = 55;
853     syslog('info', 'problem was %m');   # %m == $! in syslog(3)
854
855 Log to UDP port on C<$remotehost> instead of logging locally:
856
857     setlogsock('udp');
858     $Sys::Syslog::host = $remotehost;
859     openlog($program, 'ndelay', 'user');
860     syslog('info', 'something happened over here');
861
862
863 =head1 CONSTANTS
864
865 =head2 Facilities
866
867 =over 4
868
869 =item *
870
871 C<LOG_AUTH> - security/authorization messages
872
873 =item *
874
875 C<LOG_AUTHPRIV> - security/authorization messages (private)
876
877 =item *
878
879 C<LOG_CRON> - clock daemon (B<cron> and B<at>)
880
881 =item *
882
883 C<LOG_DAEMON> - system daemons without separate facility value
884
885 =item *
886
887 C<LOG_FTP> - ftp daemon
888
889 =item *
890
891 C<LOG_KERN> - kernel messages
892
893 =item *
894
895 C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
896
897 =item *
898
899 C<LOG_LPR> - line printer subsystem
900
901 =item *
902
903 C<LOG_MAIL> - mail subsystem
904
905 =item *
906
907 C<LOG_NEWS> - USENET news subsystem
908
909 =item *
910
911 C<LOG_SYSLOG> - messages generated internally by B<syslogd>
912
913 =item *
914
915 C<LOG_USER> (default) - generic user-level messages
916
917 =item *
918
919 C<LOG_UUCP> - UUCP subsystem
920
921 =back
922
923
924 =head2 Levels
925
926 =over 4
927
928 =item *
929
930 C<LOG_EMERG> - system is unusable
931
932 =item *
933
934 C<LOG_ALERT> - action must be taken immediately
935
936 =item *
937
938 C<LOG_CRIT> - critical conditions
939
940 =item *
941
942 C<LOG_ERR> - error conditions
943
944 =item *
945
946 C<LOG_WARNING> - warning conditions
947
948 =item *
949
950 C<LOG_NOTICE> - normal, but significant, condition
951
952 =item *
953
954 C<LOG_INFO> - informational message
955
956 =item *
957
958 C<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
969 B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>. 
970
971 =item no connection to syslog available
972
973 B<(F)> C<syslog()> failed to connect to the specified socket.
974
975 =item stream passed to setlogsock, but %s is not writable
976
977 B<(W)> You asked C<setlogsock()> to use a stream socket, but the given 
978 path is not writable. 
979
980 =item stream passed to setlogsock, but could not find any device
981
982 B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't 
983 provide 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
987 B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service 
988 is not available on the system. 
989
990 =item syslog: expecting argument %s
991
992 B<(F)> You forgot to give C<syslog()> the indicated argument.
993
994 =item syslog: invalid level/facility: %s
995
996 B<(F)> You specified an invalid level or facility.
997
998 =item syslog: too many levels given: %s
999
1000 B<(F)> You specified too many levels. 
1001
1002 =item syslog: too many facilities given: %s
1003
1004 B<(F)> You specified too many facilities. 
1005
1006 =item syslog: level must be given
1007
1008 B<(F)> You forgot to specify a level.
1009
1010 =item udp passed to setlogsock, but udp service unavailable
1011
1012 B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service 
1013 is not available on the system. 
1014
1015 =item unix passed to setlogsock, but path not available
1016
1017 B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog> 
1018 was unable to find an appropriate an appropriate device.
1019
1020 =back
1021
1022
1023 =head1 SEE ALSO
1024
1025 L<syslog(3)>
1026
1027 SUSv3 issue 6, IEEE Std 1003.1, 2004 edition, 
1028 L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1029
1030 GNU C Library documentation on syslog, 
1031 L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1032
1033 Solaris 10 documentation on syslog, 
1034 L<http://docs.sun.com/app/docs/doc/816-5168/6mbb3hruo?a=view>
1035
1036 AIX 5L 5.3 documentation on syslog, 
1037 L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.doc/libs/basetrf2/syslog.htm>
1038
1039 HP-UX 11i documentation on syslog, 
1040 L<http://docs.hp.com/en/B9106-90010/syslog.3C.html>
1041
1042 Tru64 5.1 documentation on syslog, 
1043 L<http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51_HTML/MAN/MAN3/0193____.HTM>
1044
1045 Stratus VOS 15.1, 
1046 L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1047
1048 I<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 
1050 specify a standard of any kind.
1051
1052 I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1053
1054 I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1055
1056
1057 =head1 AUTHORS
1058
1059 Tom Christiansen E<lt>F<tchrist@perl.com>E<gt> and Larry Wall
1060 E<lt>F<larry@wall.org>E<gt>.
1061
1062 UNIX domain sockets added by Sean Robinson
1063 E<lt>F<robinson_s@sc.maricopa.edu>E<gt> with support from Tim Bunce 
1064 E<lt>F<Tim.Bunce@ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
1065
1066 Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
1067 E<lt>F<tom@compton.nu>E<gt>.
1068
1069 Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick@ccl4.org>E<gt>.
1070
1071 Failover to different communication modes by Nick Williams
1072 E<lt>F<Nick.Williams@morganstanley.com>E<gt>.
1073
1074 XS code for using native C functions borrowed from C<L<Unix::Syslog>>, 
1075 written by Marcus Harnisch E<lt>F<marcus.harnisch@gmx.net>E<gt>.
1076
1077 Extracted from core distribution for publishing on the CPAN by 
1078 SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien@aperghis.netE<gt>.
1079
1080
1081 =head1 BUGS
1082
1083 Please report any bugs or feature requests to
1084 C<bug-sys-syslog at rt.cpan.org>, or through the web interface at
1085 L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=Sys-Syslog>.
1086 I will be notified, and then you'll automatically be notified of progress on
1087 your bug as I make changes.
1088
1089
1090 =head1 SUPPORT
1091
1092 You can find documentation for this module with the perldoc command.
1093
1094     perldoc Sys::Syslog
1095
1096 You can also look for information at:
1097
1098 =over 4
1099
1100 =item * AnnoCPAN: Annotated CPAN documentation
1101
1102 L<http://annocpan.org/dist/Sys-Syslog>
1103
1104 =item * CPAN Ratings
1105
1106 L<http://cpanratings.perl.org/d/Sys-Syslog>
1107
1108 =item * RT: CPAN's request tracker
1109
1110 L<http://rt.cpan.org/NoAuth/Bugs.html?Dist=Sys-Syslog>
1111
1112 =item * Search CPAN
1113
1114 L<http://search.cpan.org/dist/Sys-Syslog/>
1115
1116 =item * Kobes' CPAN Search
1117
1118 L<http://cpan.uwinnipeg.ca/dist/Sys-Syslog>
1119
1120 =item * Perl Documentation
1121
1122 L<http://perldoc.perl.org/Sys/Syslog.html>
1123
1124 =back
1125
1126
1127 =head1 LICENSE
1128
1129 This program is free software; you can redistribute it and/or modify it
1130 under the same terms as Perl itself.
1131
1132 =cut