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