This is a live mirror of the Perl 5 development currently hosted at https://github.com/perl/perl5
Time::HiRes version bump.
[perl5.git] / cpan / Sys-Syslog / Syslog.pm
CommitLineData
a0d0e21e 1package Sys::Syslog;
8168e71f 2use strict;
f93f88eb 3use warnings;
89c3c464 4use warnings::register;
8168e71f 5use Carp;
848ca32c 6use Exporter qw< import >;
07b7e4bc 7use File::Basename;
06fd9d7a
CBW
8use POSIX qw< strftime setlocale LC_TIME >;
9use Socket qw< :all >;
d329efa2 10require 5.005;
a0d0e21e 11
06fd9d7a 12
89c3c464 13{ no strict 'vars';
848ca32c 14 $VERSION = '0.33';
942974c1 15
89c3c464 16 %EXPORT_TAGS = (
4b035b3d
SP
17 standard => [qw(openlog syslog closelog setlogmask)],
18 extended => [qw(setlogsock)],
19 macros => [
20 # levels
21 qw(
22 LOG_ALERT LOG_CRIT LOG_DEBUG LOG_EMERG LOG_ERR
23 LOG_INFO LOG_NOTICE LOG_WARNING
24 ),
25
a650b841 26 # standard facilities
4b035b3d 27 qw(
a650b841
AT
28 LOG_AUTH LOG_AUTHPRIV LOG_CRON LOG_DAEMON LOG_FTP LOG_KERN
29 LOG_LOCAL0 LOG_LOCAL1 LOG_LOCAL2 LOG_LOCAL3 LOG_LOCAL4
30 LOG_LOCAL5 LOG_LOCAL6 LOG_LOCAL7 LOG_LPR LOG_MAIL LOG_NEWS
31 LOG_SYSLOG LOG_USER LOG_UUCP
32 ),
33 # Mac OS X specific facilities
34 qw( LOG_INSTALL LOG_LAUNCHD LOG_NETINFO LOG_RAS LOG_REMOTEAUTH ),
35 # modern BSD specific facilities
36 qw( LOG_CONSOLE LOG_NTP LOG_SECURITY ),
37 # IRIX specific facilities
38 qw( LOG_AUDIT LOG_LFMT ),
4b035b3d
SP
39
40 # options
41 qw(
42 LOG_CONS LOG_PID LOG_NDELAY LOG_NOWAIT LOG_ODELAY LOG_PERROR
43 ),
44
45 # others macros
46 qw(
47 LOG_FACMASK LOG_NFACILITIES LOG_PRIMASK
48 LOG_MASK LOG_UPTO
49 ),
50 ],
89c3c464 51 );
942974c1 52
89c3c464 53 @EXPORT = (
07b7e4bc 54 @{$EXPORT_TAGS{standard}},
89c3c464 55 );
942974c1 56
89c3c464 57 @EXPORT_OK = (
07b7e4bc
RGS
58 @{$EXPORT_TAGS{extended}},
59 @{$EXPORT_TAGS{macros}},
89c3c464
AT
60 );
61
62 eval {
63 require XSLoader;
64 XSLoader::load('Sys::Syslog', $VERSION);
65 1
66 } or do {
67 require DynaLoader;
68 push @ISA, 'DynaLoader';
69 bootstrap Sys::Syslog $VERSION;
70 };
71}
72
73
74#
75# Public variables
76#
a650b841 77use vars qw($host); # host to send syslog messages to (see notes at end)
89c3c464 78
f93f88eb
AT
79#
80# Prototypes
81#
82sub silent_eval (&);
83
89c3c464
AT
84#
85# Global variables
86#
a650b841 87use vars qw($facility);
06fd9d7a 88my $connected = 0; # flag to indicate if we're connected or not
89c3c464 89my $syslog_send; # coderef of the function used to send messages
06fd9d7a
CBW
90my $syslog_path = undef; # syslog path for "stream" and "unix" mechanisms
91my $syslog_xobj = undef; # if defined, holds the external object used to send messages
aaa7a444 92my $transmit_ok = 0; # flag to indicate if the last message was transmitted
06fd9d7a
CBW
93my $sock_port = undef; # socket port
94my $sock_timeout = 0; # socket timeout, see below
95my $current_proto = undef; # current mechanism used to transmit messages
96my $ident = ''; # identifiant prepended to each message
97$facility = ''; # current facility
98my $maskpri = LOG_UPTO(&LOG_DEBUG); # current log mask
89c3c464
AT
99
100my %options = (
101 ndelay => 0,
06fd9d7a 102 noeol => 0,
89c3c464 103 nofatal => 0,
06fd9d7a 104 nonul => 0,
89c3c464 105 nowait => 0,
35a209d1 106 perror => 0,
89c3c464 107 pid => 0,
942974c1 108);
a0d0e21e 109
a650b841 110# Default is now to first use the native mechanism, so Perl programs
d329efa2
AT
111# behave like other normal Unix programs, then try other mechanisms.
112my @connectMethods = qw(native tcp udp unix pipe stream console);
06fd9d7a 113if ($^O eq "freebsd" or $^O eq "linux") {
dbfdd438
SR
114 @connectMethods = grep { $_ ne 'udp' } @connectMethods;
115}
a650b841 116
f93f88eb
AT
117# And on Win32 systems, we try to use the native mechanism for this
118# platform, the events logger, available through Win32::EventLog.
26f266f7 119EVENTLOG: {
26f266f7 120 my $is_Win32 = $^O =~ /Win32/i;
a650b841 121
06fd9d7a 122 if (can_load("Sys::Syslog::Win32", $is_Win32)) {
26f266f7
AT
123 unshift @connectMethods, 'eventlog';
124 }
26f266f7 125}
35a209d1 126
23642f4b 127my @defaultMethods = @connectMethods;
89c3c464 128my @fallbackMethods = ();
8168e71f 129
f93f88eb
AT
130# The timeout in connection_ok() was pushed up to 0.25 sec in
131# Sys::Syslog v0.19 in order to address a heisenbug on MacOSX:
132# http://london.pm.org/pipermail/london.pm/Week-of-Mon-20061211/005961.html
133#
134# However, this also had the effect of slowing this test for
135# all other operating systems, which apparently impacted some
136# users (cf. CPAN-RT #34753). So, in order to make everybody
137# happy, the timeout is now zero by default on all systems
138# except on OSX where it is set to 250 msec, and can be set
139# with the infamous setlogsock() function.
0374b0a2
SH
140#
141# Update 2011-08: this issue is also been seen on multiprocessor
142# Debian GNU/kFreeBSD systems. See http://bugs.debian.org/627821
143# and https://rt.cpan.org/Ticket/Display.html?id=69997
144# Also, lowering the delay to 1 ms, which should be enough.
145
146$sock_timeout = 0.001 if $^O =~ /darwin|gnukfreebsd/;
f93f88eb 147
aaa7a444
CBW
148
149# Perl 5.6.0's warnings.pm doesn't have warnings::warnif()
150if (not defined &warnings::warnif) {
151 *warnings::warnif = sub {
152 goto &warnings::warn if warnings::enabled(__PACKAGE__)
153 }
154}
155
89c3c464
AT
156# coderef for a nicer handling of errors
157my $err_sub = $options{nofatal} ? \&warnings::warnif : \&croak;
5be1dfc7 158
5be1dfc7 159
89c3c464
AT
160sub AUTOLOAD {
161 # This AUTOLOAD is used to 'autoload' constants from the constant()
162 # XS function.
163 no strict 'vars';
164 my $constname;
165 ($constname = $AUTOLOAD) =~ s/.*:://;
166 croak "Sys::Syslog::constant() not defined" if $constname eq 'constant';
167 my ($error, $val) = constant($constname);
a650b841 168 croak $error if $error;
89c3c464
AT
169 no strict 'refs';
170 *$AUTOLOAD = sub { $val };
171 goto &$AUTOLOAD;
172}
5be1dfc7 173
5be1dfc7 174
89c3c464
AT
175sub openlog {
176 ($ident, my $logopt, $facility) = @_;
8168e71f 177
a650b841
AT
178 # default values
179 $ident ||= basename($0) || getlogin() || getpwuid($<) || 'syslog';
180 $logopt ||= '';
181 $facility ||= LOG_USER();
182
89c3c464
AT
183 for my $opt (split /\b/, $logopt) {
184 $options{$opt} = 1 if exists $options{$opt}
185 }
5be1dfc7 186
f93f88eb 187 $err_sub = delete $options{nofatal} ? \&warnings::warnif : \&croak;
89c3c464
AT
188 return 1 unless $options{ndelay};
189 connect_log();
190}
5be1dfc7 191
89c3c464 192sub closelog {
06fd9d7a
CBW
193 disconnect_log() if $connected;
194 $options{$_} = 0 for keys %options;
195 $facility = $ident = "";
196 $connected = 0;
197 return 1
89c3c464 198}
8168e71f 199
89c3c464
AT
200sub setlogmask {
201 my $oldmask = $maskpri;
202 $maskpri = shift unless $_[0] == 0;
203 $oldmask;
204}
f93f88eb 205
a650b841 206
06fd9d7a
CBW
207my %mechanism = (
208 console => {
209 check => sub { 1 },
210 },
211 eventlog => {
212 check => sub { return can_load("Win32::EventLog") },
213 err_msg => "no Win32 API available",
214 },
215 inet => {
216 check => sub { 1 },
217 },
218 native => {
219 check => sub { 1 },
220 },
221 pipe => {
222 check => sub {
223 ($syslog_path) = grep { defined && length && -p && -w _ }
224 $syslog_path, &_PATH_LOG, "/dev/log";
225 return $syslog_path ? 1 : 0
226 },
227 err_msg => "path not available",
228 },
229 stream => {
230 check => sub {
a650b841 231 if (not defined $syslog_path) {
06fd9d7a
CBW
232 my @try = qw(/dev/log /dev/conslog);
233 unshift @try, &_PATH_LOG if length &_PATH_LOG;
234 ($syslog_path) = grep { -w } @try;
a650b841 235 }
06fd9d7a
CBW
236 return defined $syslog_path && -w $syslog_path
237 },
238 err_msg => "could not find any writable device",
239 },
240 tcp => {
241 check => sub {
33f804f6
SH
242 return 1 if defined $sock_port;
243
06fd9d7a
CBW
244 if (getservbyname('syslog', 'tcp') || getservbyname('syslogng', 'tcp')) {
245 $host = $syslog_path;
246 return 1
247 }
248 else {
249 return
250 }
251 },
252 err_msg => "TCP service unavailable",
253 },
254 udp => {
255 check => sub {
33f804f6
SH
256 return 1 if defined $sock_port;
257
06fd9d7a
CBW
258 if (getservbyname('syslog', 'udp')) {
259 $host = $syslog_path;
260 return 1
261 }
262 else {
263 return
264 }
265 },
266 err_msg => "UDP service unavailable",
267 },
268 unix => {
269 check => sub {
270 my @try = ($syslog_path, &_PATH_LOG);
271 ($syslog_path) = grep { defined && length && -w } @try;
272 return defined $syslog_path && -w $syslog_path
273 },
274 err_msg => "path not available",
275 },
276);
277
278sub setlogsock {
279 my %opt;
280
281 # handle arguments
282 # - old API: setlogsock($sock_type, $sock_path, $sock_timeout)
283 # - new API: setlogsock(\%options)
284 croak "setlogsock(): Invalid number of arguments"
285 unless @_ >= 1 and @_ <= 3;
286
287 if (my $ref = ref $_[0]) {
288 if ($ref eq "HASH") {
289 %opt = %{ $_[0] };
290 croak "setlogsock(): No argument given" unless keys %opt;
89c3c464 291 }
06fd9d7a
CBW
292 elsif ($ref eq "ARRAY") {
293 @opt{qw< type path timeout >} = @_;
d329efa2 294 }
06fd9d7a
CBW
295 else {
296 croak "setlogsock(): Unexpected \L$ref\E reference"
a650b841 297 }
06fd9d7a
CBW
298 }
299 else {
300 @opt{qw< type path timeout >} = @_;
301 }
8168e71f 302
0374b0a2 303 # check socket type, remove invalid ones
06fd9d7a
CBW
304 my $diag_invalid_type = "setlogsock(): Invalid type%s; must be one of "
305 . join ", ", map { "'$_'" } sort keys %mechanism;
306 croak sprintf $diag_invalid_type, "" unless defined $opt{type};
307 my @sock_types = ref $opt{type} eq "ARRAY" ? @{$opt{type}} : ($opt{type});
308 my @tmp;
309
310 for my $sock_type (@sock_types) {
311 carp sprintf $diag_invalid_type, " '$sock_type'" and next
312 unless exists $mechanism{$sock_type};
313 push @tmp, "tcp", "udp" and next if $sock_type eq "inet";
314 push @tmp, $sock_type;
315 }
942974c1 316
06fd9d7a 317 @sock_types = @tmp;
942974c1 318
06fd9d7a
CBW
319 # set global options
320 $syslog_path = $opt{path} if defined $opt{path};
321 $host = $opt{host} if defined $opt{host};
322 $sock_timeout = $opt{timeout} if defined $opt{timeout};
323 $sock_port = $opt{port} if defined $opt{port};
942974c1 324
06fd9d7a
CBW
325 disconnect_log() if $connected;
326 $transmit_ok = 0;
327 @fallbackMethods = ();
0374b0a2
SH
328 @connectMethods = ();
329 my $found = 0;
942974c1 330
0374b0a2 331 # check each given mechanism and test if it can be used on the current system
06fd9d7a
CBW
332 for my $sock_type (@sock_types) {
333 if ( $mechanism{$sock_type}{check}->() ) {
0374b0a2
SH
334 push @connectMethods, $sock_type;
335 $found = 1;
06fd9d7a
CBW
336 }
337 else {
aaa7a444
CBW
338 warnings::warnif("setlogsock(): type='$sock_type': "
339 . $mechanism{$sock_type}{err_msg});
06fd9d7a 340 }
89c3c464 341 }
942974c1 342
0374b0a2
SH
343 # if no mechanism worked from the given ones, use the default ones
344 @connectMethods = @defaultMethods unless @connectMethods;
345
346 return $found;
89c3c464 347}
942974c1 348
89c3c464 349sub syslog {
aaa7a444 350 my ($priority, $mask, @args) = @_;
89c3c464
AT
351 my ($message, $buf);
352 my (@words, $num, $numpri, $numfac, $sum);
353 my $failed = undef;
354 my $fail_time = undef;
8edeb3ad 355 my $error = $!;
8168e71f 356
a650b841
AT
357 # if $ident is undefined, it means openlog() wasn't previously called
358 # so do it now in order to have sensible defaults
359 openlog() unless $ident;
360
361 local $facility = $facility; # may need to change temporarily.
8168e71f 362
89c3c464
AT
363 croak "syslog: expecting argument \$priority" unless defined $priority;
364 croak "syslog: expecting argument \$format" unless defined $mask;
5be1dfc7 365
06fd9d7a
CBW
366 if ($priority =~ /^\d+$/) {
367 $numpri = LOG_PRI($priority);
0374b0a2 368 $numfac = LOG_FAC($priority) << 3;
06fd9d7a
CBW
369 }
370 elsif ($priority =~ /^\w+/) {
371 # Allow "level" or "level|facility".
372 @words = split /\W+/, $priority, 2;
5be1dfc7 373
06fd9d7a
CBW
374 undef $numpri;
375 undef $numfac;
f93f88eb 376
06fd9d7a
CBW
377 for my $word (@words) {
378 next if length $word == 0;
f93f88eb 379
06fd9d7a
CBW
380 # Translate word to number.
381 $num = xlate($word);
382
383 if ($num < 0) {
384 croak "syslog: invalid level/facility: $word"
385 }
0374b0a2 386 elsif ($num <= LOG_PRIMASK() and $word ne "kern") {
06fd9d7a
CBW
387 croak "syslog: too many levels given: $word"
388 if defined $numpri;
389 $numpri = $num;
06fd9d7a
CBW
390 }
391 else {
392 croak "syslog: too many facilities given: $word"
393 if defined $numfac;
394 $facility = $word if $word =~ /^[A-Za-z]/;
0374b0a2 395 $numfac = $num;
06fd9d7a 396 }
f93f88eb 397 }
89c3c464 398 }
06fd9d7a
CBW
399 else {
400 croak "syslog: invalid level/facility: $priority"
401 }
5be1dfc7 402
89c3c464 403 croak "syslog: level must be given" unless defined $numpri;
942974c1 404
0374b0a2
SH
405 # don't log if priority is below mask level
406 return 0 unless LOG_MASK($numpri) & $maskpri;
407
89c3c464
AT
408 if (not defined $numfac) { # Facility not specified in this call.
409 $facility = 'user' unless $facility;
410 $numfac = xlate($facility);
411 }
3d256c0f 412
89c3c464 413 connect_log() unless $connected;
8168e71f 414
89c3c464 415 if ($mask =~ /%m/) {
07b7e4bc 416 # escape percent signs for sprintf()
aaa7a444 417 $error =~ s/%/%%/g if @args;
a650b841 418 # replace %m with $error, if preceded by an even number of percent signs
8edeb3ad 419 $mask =~ s/(?<!%)((?:%%)*)%m/$1$error/g;
89c3c464 420 }
5be1dfc7 421
89c3c464 422 $mask .= "\n" unless $mask =~ /\n$/;
aaa7a444 423 $message = @args ? sprintf($mask, @args) : $mask;
942974c1 424
d329efa2 425 if ($current_proto eq 'native') {
89c3c464 426 $buf = $message;
a650b841
AT
427 }
428 elsif ($current_proto eq 'eventlog') {
429 $buf = $message;
430 }
431 else {
89c3c464 432 my $whoami = $ident;
89c3c464 433 $whoami .= "[$$]" if $options{pid};
942974c1 434
89c3c464
AT
435 $sum = $numpri + $numfac;
436 my $oldlocale = setlocale(LC_TIME);
437 setlocale(LC_TIME, 'C');
33f804f6 438 my $timestamp = strftime "%b %d %H:%M:%S", localtime;
89c3c464 439 setlocale(LC_TIME, $oldlocale);
06fd9d7a
CBW
440
441 # construct the stream that will be transmitted
442 $buf = "<$sum>$timestamp $whoami: $message";
443
444 # add (or not) a newline
445 $buf .= "\n" if !$options{noeol} and rindex($buf, "\n") == -1;
446
447 # add (or not) a NUL character
448 $buf .= "\0" if !$options{nonul};
89c3c464 449 }
942974c1 450
35a209d1
AT
451 # handle PERROR option
452 # "native" mechanism already handles it by itself
453 if ($options{perror} and $current_proto ne 'native') {
35a209d1
AT
454 my $whoami = $ident;
455 $whoami .= "[$$]" if $options{pid};
456 print STDERR "$whoami: $message\n";
457 }
458
89c3c464
AT
459 # it's possible that we'll get an error from sending
460 # (e.g. if method is UDP and there is no UDP listener,
461 # then we'll get ECONNREFUSED on the send). So what we
462 # want to do at this point is to fallback onto a different
463 # connection method.
464 while (scalar @fallbackMethods || $syslog_send) {
465 if ($failed && (time - $fail_time) > 60) {
466 # it's been a while... maybe things have been fixed
467 @fallbackMethods = ();
468 disconnect_log();
469 $transmit_ok = 0; # make it look like a fresh attempt
470 connect_log();
471 }
942974c1 472
89c3c464
AT
473 if ($connected && !connection_ok()) {
474 # Something was OK, but has now broken. Remember coz we'll
475 # want to go back to what used to be OK.
476 $failed = $current_proto unless $failed;
477 $fail_time = time;
478 disconnect_log();
479 }
942974c1 480
89c3c464
AT
481 connect_log() unless $connected;
482 $failed = undef if ($current_proto && $failed && $current_proto eq $failed);
942974c1 483
89c3c464 484 if ($syslog_send) {
a650b841 485 if ($syslog_send->($buf, $numpri, $numfac)) {
89c3c464
AT
486 $transmit_ok++;
487 return 1;
488 }
489 # typically doesn't happen, since errors are rare from write().
490 disconnect_log();
491 }
492 }
493 # could not send, could not fallback onto a working
494 # connection method. Lose.
495 return 0;
496}
942974c1 497
89c3c464
AT
498sub _syslog_send_console {
499 my ($buf) = @_;
06fd9d7a 500
89c3c464
AT
501 # The console print is a method which could block
502 # so we do it in a child process and always return success
503 # to the caller.
504 if (my $pid = fork) {
942974c1 505
89c3c464
AT
506 if ($options{nowait}) {
507 return 1;
508 } else {
509 if (waitpid($pid, 0) >= 0) {
510 return ($? >> 8);
511 } else {
512 # it's possible that the caller has other
513 # plans for SIGCHLD, so let's not interfere
514 return 1;
515 }
516 }
517 } else {
518 if (open(CONS, ">/dev/console")) {
519 my $ret = print CONS $buf . "\r"; # XXX: should this be \x0A ?
848ca32c 520 POSIX::_exit($ret) if defined $pid;
89c3c464
AT
521 close CONS;
522 }
06fd9d7a 523
848ca32c 524 POSIX::_exit(0) if defined $pid;
89c3c464
AT
525 }
526}
942974c1 527
89c3c464
AT
528sub _syslog_send_stream {
529 my ($buf) = @_;
530 # XXX: this only works if the OS stream implementation makes a write
531 # look like a putmsg() with simple header. For instance it works on
532 # Solaris 8 but not Solaris 7.
533 # To be correct, it should use a STREAMS API, but perl doesn't have one.
534 return syswrite(SYSLOG, $buf, length($buf));
535}
942974c1 536
d329efa2
AT
537sub _syslog_send_pipe {
538 my ($buf) = @_;
539 return print SYSLOG $buf;
540}
541
89c3c464
AT
542sub _syslog_send_socket {
543 my ($buf) = @_;
544 return syswrite(SYSLOG, $buf, length($buf));
545 #return send(SYSLOG, $buf, 0);
546}
942974c1 547
89c3c464 548sub _syslog_send_native {
06fd9d7a
CBW
549 my ($buf, $numpri, $numfac) = @_;
550 syslog_xs($numpri|$numfac, $buf);
a650b841 551 return 1;
89c3c464 552}
ce43db9b 553
5be1dfc7 554
89c3c464
AT
555# xlate()
556# -----
557# private function to translate names to numeric values
558#
559sub xlate {
f93f88eb
AT
560 my ($name) = @_;
561
89c3c464
AT
562 return $name+0 if $name =~ /^\s*\d+\s*$/;
563 $name = uc $name;
564 $name = "LOG_$name" unless $name =~ /^LOG_/;
2605937c
AT
565
566 # ExtUtils::Constant 0.20 introduced a new way to implement
567 # constants, called ProxySubs. When it was used to generate
568 # the C code, the constant() function no longer returns the
569 # correct value. Therefore, we first try a direct call to
570 # constant(), and if the value is an error we try to call the
571 # constant by its full name.
f93f88eb 572 my $value = constant($name);
2605937c
AT
573
574 if (index($value, "not a valid") >= 0) {
575 $name = "Sys::Syslog::$name";
576 $value = eval { no strict "refs"; &$name };
577 $value = $@ unless defined $value;
578 }
579
580 $value = -1 if index($value, "not a valid") >= 0;
f93f88eb 581
35a209d1 582 return defined $value ? $value : -1;
89c3c464 583}
5be1dfc7 584
942974c1 585
89c3c464
AT
586# connect_log()
587# -----------
588# This function acts as a kind of front-end: it tries to connect to
589# a syslog service using the selected methods, trying each one in the
590# selected order.
591#
592sub connect_log {
593 @fallbackMethods = @connectMethods unless scalar @fallbackMethods;
07b7e4bc 594
89c3c464
AT
595 if ($transmit_ok && $current_proto) {
596 # Retry what we were on, because it has worked in the past.
597 unshift(@fallbackMethods, $current_proto);
598 }
07b7e4bc 599
89c3c464
AT
600 $connected = 0;
601 my @errs = ();
602 my $proto = undef;
07b7e4bc 603
89c3c464
AT
604 while ($proto = shift @fallbackMethods) {
605 no strict 'refs';
606 my $fn = "connect_$proto";
607 $connected = &$fn(\@errs) if defined &$fn;
608 last if $connected;
609 }
3d256c0f 610
89c3c464
AT
611 $transmit_ok = 0;
612 if ($connected) {
613 $current_proto = $proto;
a650b841 614 my ($old) = select(SYSLOG); $| = 1; select($old);
89c3c464
AT
615 } else {
616 @fallbackMethods = ();
617 $err_sub->(join "\n\t- ", "no connection to syslog available", @errs);
618 return undef;
619 }
620}
942974c1 621
89c3c464
AT
622sub connect_tcp {
623 my ($errs) = @_;
4b035b3d 624
06fd9d7a
CBW
625 my $proto = getprotobyname('tcp');
626 if (!defined $proto) {
89c3c464
AT
627 push @$errs, "getprotobyname failed for tcp";
628 return 0;
629 }
4b035b3d 630
06fd9d7a
CBW
631 my $port = $sock_port || getservbyname('syslog', 'tcp');
632 $port = getservbyname('syslogng', 'tcp') unless defined $port;
633 if (!defined $port) {
89c3c464
AT
634 push @$errs, "getservbyname failed for syslog/tcp and syslogng/tcp";
635 return 0;
636 }
942974c1 637
4b035b3d 638 my $addr;
89c3c464 639 if (defined $host) {
4b035b3d
SP
640 $addr = inet_aton($host);
641 if (!$addr) {
89c3c464
AT
642 push @$errs, "can't lookup $host";
643 return 0;
644 }
645 } else {
4b035b3d 646 $addr = INADDR_LOOPBACK;
89c3c464 647 }
06fd9d7a 648 $addr = sockaddr_in($port, $addr);
942974c1 649
06fd9d7a 650 if (!socket(SYSLOG, AF_INET, SOCK_STREAM, $proto)) {
89c3c464
AT
651 push @$errs, "tcp socket: $!";
652 return 0;
653 }
a650b841 654
89c3c464 655 setsockopt(SYSLOG, SOL_SOCKET, SO_KEEPALIVE, 1);
f93f88eb 656 if (silent_eval { IPPROTO_TCP() }) {
d329efa2
AT
657 # These constants don't exist in 5.005. They were added in 1999
658 setsockopt(SYSLOG, IPPROTO_TCP(), TCP_NODELAY(), 1);
659 }
4b035b3d 660 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
661 push @$errs, "tcp connect: $!";
662 return 0;
663 }
4b035b3d 664
89c3c464 665 $syslog_send = \&_syslog_send_socket;
4b035b3d 666
89c3c464
AT
667 return 1;
668}
942974c1 669
89c3c464
AT
670sub connect_udp {
671 my ($errs) = @_;
4b035b3d 672
06fd9d7a
CBW
673 my $proto = getprotobyname('udp');
674 if (!defined $proto) {
89c3c464
AT
675 push @$errs, "getprotobyname failed for udp";
676 return 0;
677 }
4b035b3d 678
06fd9d7a
CBW
679 my $port = $sock_port || getservbyname('syslog', 'udp');
680 if (!defined $port) {
89c3c464
AT
681 push @$errs, "getservbyname failed for syslog/udp";
682 return 0;
683 }
4b035b3d
SP
684
685 my $addr;
89c3c464 686 if (defined $host) {
4b035b3d
SP
687 $addr = inet_aton($host);
688 if (!$addr) {
89c3c464
AT
689 push @$errs, "can't lookup $host";
690 return 0;
691 }
692 } else {
4b035b3d 693 $addr = INADDR_LOOPBACK;
89c3c464 694 }
06fd9d7a 695 $addr = sockaddr_in($port, $addr);
942974c1 696
06fd9d7a 697 if (!socket(SYSLOG, AF_INET, SOCK_DGRAM, $proto)) {
89c3c464
AT
698 push @$errs, "udp socket: $!";
699 return 0;
700 }
4b035b3d 701 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
702 push @$errs, "udp connect: $!";
703 return 0;
704 }
4b035b3d 705
89c3c464
AT
706 # We want to check that the UDP connect worked. However the only
707 # way to do that is to send a message and see if an ICMP is returned
708 _syslog_send_socket("");
709 if (!connection_ok()) {
710 push @$errs, "udp connect: nobody listening";
711 return 0;
712 }
4b035b3d 713
89c3c464 714 $syslog_send = \&_syslog_send_socket;
4b035b3d 715
89c3c464
AT
716 return 1;
717}
9903e4c8 718
89c3c464
AT
719sub connect_stream {
720 my ($errs) = @_;
721 # might want syslog_path to be variable based on syslog.h (if only
722 # it were in there!)
8edeb3ad 723 $syslog_path = '/dev/conslog' unless defined $syslog_path;
848ca32c 724
89c3c464
AT
725 if (!-w $syslog_path) {
726 push @$errs, "stream $syslog_path is not writable";
727 return 0;
728 }
848ca32c
CBW
729
730 require Fcntl;
731
732 if (!sysopen(SYSLOG, $syslog_path, Fcntl::O_WRONLY(), 0400)) {
89c3c464
AT
733 push @$errs, "stream can't open $syslog_path: $!";
734 return 0;
735 }
848ca32c 736
89c3c464 737 $syslog_send = \&_syslog_send_stream;
848ca32c 738
89c3c464
AT
739 return 1;
740}
942974c1 741
d329efa2
AT
742sub connect_pipe {
743 my ($errs) = @_;
744
745 $syslog_path ||= &_PATH_LOG || "/dev/log";
746
747 if (not -w $syslog_path) {
748 push @$errs, "$syslog_path is not writable";
749 return 0;
750 }
751
752 if (not open(SYSLOG, ">$syslog_path")) {
753 push @$errs, "can't write to $syslog_path: $!";
754 return 0;
755 }
756
757 $syslog_send = \&_syslog_send_pipe;
758
759 return 1;
760}
761
89c3c464
AT
762sub connect_unix {
763 my ($errs) = @_;
4b035b3d
SP
764
765 $syslog_path ||= _PATH_LOG() if length _PATH_LOG();
766
767 if (not defined $syslog_path) {
768 push @$errs, "_PATH_LOG not available in syslog.h and no user-supplied socket path";
89c3c464
AT
769 return 0;
770 }
4b035b3d 771
35a209d1 772 if (not (-S $syslog_path or -c _)) {
89c3c464
AT
773 push @$errs, "$syslog_path is not a socket";
774 return 0;
775 }
4b035b3d
SP
776
777 my $addr = sockaddr_un($syslog_path);
778 if (!$addr) {
89c3c464
AT
779 push @$errs, "can't locate $syslog_path";
780 return 0;
781 }
4b035b3d 782 if (!socket(SYSLOG, AF_UNIX, SOCK_STREAM, 0)) {
89c3c464
AT
783 push @$errs, "unix stream socket: $!";
784 return 0;
785 }
a650b841 786
4b035b3d
SP
787 if (!connect(SYSLOG, $addr)) {
788 if (!socket(SYSLOG, AF_UNIX, SOCK_DGRAM, 0)) {
89c3c464
AT
789 push @$errs, "unix dgram socket: $!";
790 return 0;
791 }
4b035b3d 792 if (!connect(SYSLOG, $addr)) {
89c3c464
AT
793 push @$errs, "unix dgram connect: $!";
794 return 0;
795 }
796 }
4b035b3d 797
89c3c464 798 $syslog_send = \&_syslog_send_socket;
4b035b3d 799
89c3c464
AT
800 return 1;
801}
942974c1 802
89c3c464
AT
803sub connect_native {
804 my ($errs) = @_;
805 my $logopt = 0;
5be1dfc7 806
89c3c464
AT
807 # reconstruct the numeric equivalent of the options
808 for my $opt (keys %options) {
809 $logopt += xlate($opt) if $options{$opt}
810 }
942974c1 811
f93f88eb 812 openlog_xs($ident, $logopt, xlate($facility));
89c3c464 813 $syslog_send = \&_syslog_send_native;
942974c1 814
89c3c464
AT
815 return 1;
816}
6e4ef777 817
a650b841
AT
818sub connect_eventlog {
819 my ($errs) = @_;
820
821 $syslog_xobj = Sys::Syslog::Win32::_install();
822 $syslog_send = \&Sys::Syslog::Win32::_syslog_send;
823
824 return 1;
825}
826
89c3c464
AT
827sub connect_console {
828 my ($errs) = @_;
829 if (!-w '/dev/console') {
830 push @$errs, "console is not writable";
831 return 0;
832 }
833 $syslog_send = \&_syslog_send_console;
834 return 1;
835}
6e4ef777 836
a650b841 837# To test if the connection is still good, we need to check if any
89c3c464
AT
838# errors are present on the connection. The errors will not be raised
839# by a write. Instead, sockets are made readable and the next read
840# would cause the error to be returned. Unfortunately the syslog
841# 'protocol' never provides anything for us to read. But with
842# judicious use of select(), we can see if it would be readable...
843sub connection_ok {
844 return 1 if defined $current_proto and (
845 $current_proto eq 'native' or $current_proto eq 'console'
a650b841 846 or $current_proto eq 'eventlog'
89c3c464 847 );
a650b841 848
89c3c464
AT
849 my $rin = '';
850 vec($rin, fileno(SYSLOG), 1) = 1;
f93f88eb 851 my $ret = select $rin, undef, $rin, $sock_timeout;
89c3c464
AT
852 return ($ret ? 0 : 1);
853}
942974c1 854
89c3c464
AT
855sub disconnect_log {
856 $connected = 0;
857 $syslog_send = undef;
942974c1 858
a650b841
AT
859 if (defined $current_proto and $current_proto eq 'native') {
860 closelog_xs();
06fd9d7a
CBW
861 unshift @fallbackMethods, $current_proto;
862 $current_proto = undef;
a650b841
AT
863 return 1;
864 }
865 elsif (defined $current_proto and $current_proto eq 'eventlog') {
866 $syslog_xobj->Close();
06fd9d7a
CBW
867 unshift @fallbackMethods, $current_proto;
868 $current_proto = undef;
89c3c464
AT
869 return 1;
870 }
6e4ef777 871
89c3c464
AT
872 return close SYSLOG;
873}
6e4ef777 874
f93f88eb
AT
875
876#
877# Wrappers around eval() that makes sure that nobody, and I say NOBODY,
878# ever knows that I wanted to test if something was here or not.
879# It is needed because some applications are trying to be too smart,
880# do it wrong, and it ends up in EPIC FAIL.
881# Yes I'm speaking of YOU, SpamAssassin.
882#
883sub silent_eval (&) {
884 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
2605937c 885 return eval { $_[0]->() }
f93f88eb
AT
886}
887
888sub can_load {
06fd9d7a 889 my ($module, $verbose) = @_;
f93f88eb 890 local($SIG{__DIE__}, $SIG{__WARN__}, $@);
06fd9d7a
CBW
891 my $loaded = eval "use $module; 1";
892 warn $@ if not $loaded and $verbose;
893 return $loaded
f93f88eb
AT
894}
895
896
897"Eighth Rule: read the documentation."
942974c1 898
89c3c464 899__END__
5be1dfc7 900
89c3c464 901=head1 NAME
8168e71f 902
89c3c464 903Sys::Syslog - Perl interface to the UNIX syslog(3) calls
3ffabb8c 904
89c3c464 905=head1 VERSION
3ffabb8c 906
848ca32c 907This is the documentation of version 0.33
23642f4b 908
89c3c464 909=head1 SYNOPSIS
cb63fe9d 910
06fd9d7a
CBW
911 use Sys::Syslog; # all except setlogsock()
912 use Sys::Syslog qw(:standard :macros); # standard functions & macros
23642f4b 913
06fd9d7a
CBW
914 openlog($ident, $logopt, $facility); # don't forget this
915 syslog($priority, $format, @args);
916 $oldmask = setlogmask($mask_priority);
917 closelog();
cb63fe9d 918
942974c1 919
89c3c464 920=head1 DESCRIPTION
5be1dfc7 921
89c3c464
AT
922C<Sys::Syslog> is an interface to the UNIX C<syslog(3)> program.
923Call C<syslog()> with a string priority and a list of C<printf()> args
924just like C<syslog(3)>.
5be1dfc7 925
5be1dfc7 926
89c3c464 927=head1 EXPORTS
5be1dfc7 928
89c3c464 929C<Sys::Syslog> exports the following C<Exporter> tags:
5be1dfc7 930
89c3c464
AT
931=over 4
932
933=item *
934
935C<:standard> exports the standard C<syslog(3)> functions:
936
937 openlog closelog setlogmask syslog
938
939=item *
940
941C<:extended> exports the Perl specific functions for C<syslog(3)>:
942
943 setlogsock
944
945=item *
946
947C<:macros> exports the symbols corresponding to most of your C<syslog(3)>
948macros and the C<LOG_UPTO()> and C<LOG_MASK()> functions.
949See L<"CONSTANTS"> for the supported constants and their meaning.
950
951=back
952
953By default, C<Sys::Syslog> exports the symbols from the C<:standard> tag.
954
955
956=head1 FUNCTIONS
957
958=over 4
959
960=item B<openlog($ident, $logopt, $facility)>
961
962Opens the syslog.
963C<$ident> is prepended to every message. C<$logopt> contains zero or
964more of the options detailed below. C<$facility> specifies the part
965of the system to report about, for example C<LOG_USER> or C<LOG_LOCAL0>:
966see L<"Facilities"> for a list of well-known facilities, and your
967C<syslog(3)> documentation for the facilities available in your system.
968Check L<"SEE ALSO"> for useful links. Facility can be given as a string
969or a numeric macro.
970
971This function will croak if it can't connect to the syslog daemon.
972
973Note that C<openlog()> now takes three arguments, just like C<openlog(3)>.
974
975B<You should use C<openlog()> before calling C<syslog()>.>
976
977B<Options>
978
979=over 4
980
981=item *
982
983C<cons> - This option is ignored, since the failover mechanism will drop
984down to the console automatically if all other media fail.
985
986=item *
987
988C<ndelay> - Open the connection immediately (normally, the connection is
989opened when the first message is logged).
990
991=item *
992
06fd9d7a
CBW
993C<noeol> - When set to true, no end of line character (C<\n>) will be
994appended to the message. This can be useful for some buggy syslog daemons.
995
996=item *
997
89c3c464
AT
998C<nofatal> - When set to true, C<openlog()> and C<syslog()> will only
999emit warnings instead of dying if the connection to the syslog can't
1000be established.
1001
1002=item *
1003
06fd9d7a
CBW
1004C<nonul> - When set to true, no C<NUL> character (C<\0>) will be
1005appended to the message. This can be useful for some buggy syslog daemons.
1006
1007=item *
1008
89c3c464
AT
1009C<nowait> - Don't wait for child processes that may have been created
1010while logging the message. (The GNU C library does not create a child
1011process, so this option has no effect on Linux.)
1012
1013=item *
1014
35a209d1 1015C<perror> - Write the message to standard error output as well to the
848ca32c 1016system log (added in C<Sys::Syslog> 0.22).
35a209d1
AT
1017
1018=item *
1019
89c3c464
AT
1020C<pid> - Include PID with each message.
1021
1022=back
1023
1024B<Examples>
1025
1026Open the syslog with options C<ndelay> and C<pid>, and with facility C<LOCAL0>:
1027
1028 openlog($name, "ndelay,pid", "local0");
1029
1030Same thing, but this time using the macro corresponding to C<LOCAL0>:
1031
1032 openlog($name, "ndelay,pid", LOG_LOCAL0);
1033
1034
1035=item B<syslog($priority, $message)>
1036
1037=item B<syslog($priority, $format, @args)>
1038
1039If C<$priority> permits, logs C<$message> or C<sprintf($format, @args)>
1040with the addition that C<%m> in $message or C<$format> is replaced with
1041C<"$!"> (the latest error message).
1042
1043C<$priority> can specify a level, or a level and a facility. Levels and
a650b841
AT
1044facilities can be given as strings or as macros. When using the C<eventlog>
1045mechanism, priorities C<DEBUG> and C<INFO> are mapped to event type
06fd9d7a 1046C<informational>, C<NOTICE> and C<WARNING> to C<warning> and C<ERR> to
a650b841 1047C<EMERG> to C<error>.
89c3c464
AT
1048
1049If you didn't use C<openlog()> before using C<syslog()>, C<syslog()> will
1050try to guess the C<$ident> by extracting the shortest prefix of
1051C<$format> that ends in a C<":">.
1052
1053B<Examples>
1054
06fd9d7a
CBW
1055 # informational level
1056 syslog("info", $message);
1057 syslog(LOG_INFO, $message);
89c3c464 1058
06fd9d7a
CBW
1059 # information level, Local0 facility
1060 syslog("info|local0", $message);
1061 syslog(LOG_INFO|LOG_LOCAL0, $message);
89c3c464
AT
1062
1063=over 4
1064
1065=item B<Note>
1066
1067C<Sys::Syslog> version v0.07 and older passed the C<$message> as the
1068formatting string to C<sprintf()> even when no formatting arguments
1069were provided. If the code calling C<syslog()> might execute with
1070older versions of this module, make sure to call the function as
1071C<syslog($priority, "%s", $message)> instead of C<syslog($priority,
1072$message)>. This protects against hostile formatting sequences that
1073might show up if $message contains tainted data.
1074
1075=back
1076
1077
1078=item B<setlogmask($mask_priority)>
1079
1080Sets the log mask for the current process to C<$mask_priority> and
1081returns the old mask. If the mask argument is 0, the current log mask
1082is not modified. See L<"Levels"> for the list of available levels.
1083You can use the C<LOG_UPTO()> function to allow all levels up to a
1084given priority (but it only accept the numeric macros as arguments).
1085
1086B<Examples>
1087
1088Only log errors:
1089
1090 setlogmask( LOG_MASK(LOG_ERR) );
1091
1092Log everything except informational messages:
1093
1094 setlogmask( ~(LOG_MASK(LOG_INFO)) );
1095
1096Log critical messages, errors and warnings:
1097
06fd9d7a
CBW
1098 setlogmask( LOG_MASK(LOG_CRIT)
1099 | LOG_MASK(LOG_ERR)
1100 | LOG_MASK(LOG_WARNING) );
89c3c464
AT
1101
1102Log all messages up to debug:
1103
1104 setlogmask( LOG_UPTO(LOG_DEBUG) );
1105
1106
06fd9d7a
CBW
1107=item B<setlogsock()>
1108
1109Sets the socket type and options to be used for the next call to C<openlog()>
1110or C<syslog()>. Returns true on success, C<undef> on failure.
89c3c464 1111
06fd9d7a
CBW
1112Being Perl-specific, this function has evolved along time. It can currently
1113be called as follow:
89c3c464 1114
06fd9d7a
CBW
1115=over
1116
1117=item *
1118
1119C<setlogsock($sock_type)>
1120
1121=item *
1122
1123C<setlogsock($sock_type, $stream_location)> (added in Perl 5.004_02)
1124
1125=item *
1126
1127C<setlogsock($sock_type, $stream_location, $sock_timeout)> (added in
1128C<Sys::Syslog> 0.25)
1129
1130=item *
1131
1132C<setlogsock(\%options)> (added in C<Sys::Syslog> 0.28)
1133
1134=back
f93f88eb 1135
06fd9d7a
CBW
1136The available options are:
1137
1138=over
1139
1140=item *
1141
1142C<type> - equivalent to C<$sock_type>, selects the socket type (or
1143"mechanism"). An array reference can be passed to specify several
1144mechanisms to try, in the given order.
1145
1146=item *
1147
1148C<path> - equivalent to C<$stream_location>, sets the stream location.
1149Defaults to standard Unix location, or C<_PATH_LOG>.
1150
1151=item *
1152
1153C<timeout> - equivalent to C<$sock_timeout>, sets the socket timeout
1154in seconds. Defaults to 0 on all systems except S<Mac OS X> where it
1155is set to 0.25 sec.
1156
1157=item *
1158
1159C<host> - sets the hostname to send the messages to. Defaults to
1160the local host.
1161
1162=item *
1163
1164C<port> - sets the TCP or UDP port to connect to. Defaults to the
1165first standard syslog port available on the system.
1166
1167=back
1168
1169
1170The available mechanisms are:
4b035b3d
SP
1171
1172=over
1173
1174=item *
1175
07b7e4bc
RGS
1176C<"native"> - use the native C functions from your C<syslog(3)> library
1177(added in C<Sys::Syslog> 0.15).
4b035b3d
SP
1178
1179=item *
1180
d329efa2
AT
1181C<"eventlog"> - send messages to the Win32 events logger (Win32 only;
1182added in C<Sys::Syslog> 0.19).
1183
1184=item *
1185
4b035b3d 1186C<"tcp"> - connect to a TCP socket, on the C<syslog/tcp> or C<syslogng/tcp>
06fd9d7a 1187service. See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1188
1189=item *
1190
1191C<"udp"> - connect to a UDP socket, on the C<syslog/udp> service.
06fd9d7a 1192See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1193
1194=item *
1195
f93f88eb 1196C<"inet"> - connect to an INET socket, either TCP or UDP, tried in that
06fd9d7a 1197order. See also the C<host>, C<port> and C<timeout> options.
4b035b3d
SP
1198
1199=item *
1200
1201C<"unix"> - connect to a UNIX domain socket (in some systems a character
06fd9d7a
CBW
1202special device). The name of that socket is given by the C<path> option
1203or, if omitted, the value returned by the C<_PATH_LOG> macro (if your
1204system defines it), F</dev/log> or F</dev/conslog>, whichever is writable.
4b035b3d
SP
1205
1206=item *
1207
06fd9d7a
CBW
1208C<"stream"> - connect to the stream indicated by the C<path> option, or,
1209if omitted, the value returned by the C<_PATH_LOG> macro (if your system
1210defines it), F</dev/log> or F</dev/conslog>, whichever is writable. For
1211example Solaris and IRIX system may prefer C<"stream"> instead of C<"unix">.
4b035b3d
SP
1212
1213=item *
1214
06fd9d7a
CBW
1215C<"pipe"> - connect to the named pipe indicated by the C<path> option,
1216or, if omitted, to the value returned by the C<_PATH_LOG> macro (if your
1217system defines it), or F</dev/log> (added in C<Sys::Syslog> 0.21).
1218HP-UX is a system which uses such a named pipe.
4b035b3d 1219
a650b841
AT
1220=item *
1221
d329efa2
AT
1222C<"console"> - send messages directly to the console, as for the C<"cons">
1223option of C<openlog()>.
a650b841 1224
4b035b3d 1225=back
89c3c464 1226
f93f88eb
AT
1227The default is to try C<native>, C<tcp>, C<udp>, C<unix>, C<pipe>, C<stream>,
1228C<console>.
35a209d1
AT
1229Under systems with the Win32 API, C<eventlog> will be added as the first
1230mechanism to try if C<Win32::EventLog> is available.
89c3c464 1231
07b7e4bc 1232Giving an invalid value for C<$sock_type> will C<croak>.
89c3c464 1233
4b035b3d
SP
1234B<Examples>
1235
06fd9d7a 1236Select the UDP socket mechanism:
4b035b3d
SP
1237
1238 setlogsock("udp");
1239
06fd9d7a
CBW
1240Send messages using the TCP socket mechanism on a custom port:
1241
1242 setlogsock({ type => "tcp", port => 2486 });
1243
1244Send messages to a remote host using the TCP socket mechanism:
1245
1246 setlogsock({ type => "tcp", host => $loghost });
1247
1248Try the native, UDP socket then UNIX domain socket mechanisms:
4b035b3d
SP
1249
1250 setlogsock(["native", "udp", "unix"]);
1251
07b7e4bc
RGS
1252=over
1253
1254=item B<Note>
1255
1256Now that the "native" mechanism is supported by C<Sys::Syslog> and selected
1257by default, the use of the C<setlogsock()> function is discouraged because
1258other mechanisms are less portable across operating systems. Authors of
1259modules and programs that use this function, especially its cargo-cult form
848ca32c 1260C<setlogsock("unix")>, are advised to remove any occurrence of it unless they
07b7e4bc
RGS
1261specifically want to use a given mechanism (like TCP or UDP to connect to
1262a remote host).
1263
1264=back
89c3c464
AT
1265
1266=item B<closelog()>
1267
4b035b3d 1268Closes the log file and returns true on success.
89c3c464
AT
1269
1270=back
1271
1272
a650b841
AT
1273=head1 THE RULES OF SYS::SYSLOG
1274
1275I<The First Rule of Sys::Syslog is:>
1276You do not call C<setlogsock>.
1277
1278I<The Second Rule of Sys::Syslog is:>
1279You B<do not> call C<setlogsock>.
1280
1281I<The Third Rule of Sys::Syslog is:>
1282The program crashes, C<die>s, calls C<closelog>, the log is over.
1283
1284I<The Fourth Rule of Sys::Syslog is:>
1285One facility, one priority.
1286
1287I<The Fifth Rule of Sys::Syslog is:>
1288One log at a time.
1289
1290I<The Sixth Rule of Sys::Syslog is:>
1291No C<syslog> before C<openlog>.
1292
1293I<The Seventh Rule of Sys::Syslog is:>
1294Logs will go on as long as they have to.
1295
1296I<The Eighth, and Final Rule of Sys::Syslog is:>
1297If this is your first use of Sys::Syslog, you must read the doc.
1298
1299
89c3c464
AT
1300=head1 EXAMPLES
1301
a650b841
AT
1302An example:
1303
89c3c464
AT
1304 openlog($program, 'cons,pid', 'user');
1305 syslog('info', '%s', 'this is another test');
1306 syslog('mail|warning', 'this is a better test: %d', time);
1307 closelog();
5be1dfc7
HF
1308
1309 syslog('debug', 'this is the last test');
cb63fe9d 1310
a650b841
AT
1311Another example:
1312
5be1dfc7
HF
1313 openlog("$program $$", 'ndelay', 'user');
1314 syslog('notice', 'fooprogram: this is really done');
1315
a650b841
AT
1316Example of use of C<%m>:
1317
5be1dfc7 1318 $! = 55;
6e4ef777
SP
1319 syslog('info', 'problem was %m'); # %m == $! in syslog(3)
1320
1321Log to UDP port on C<$remotehost> instead of logging locally:
5be1dfc7 1322
f93f88eb 1323 setlogsock("udp", $remotehost);
476b65d9
JH
1324 openlog($program, 'ndelay', 'user');
1325 syslog('info', 'something happened over here');
1326
8168e71f
SP
1327
1328=head1 CONSTANTS
1329
1330=head2 Facilities
1331
1332=over 4
1333
1334=item *
1335
a650b841
AT
1336C<LOG_AUDIT> - audit daemon (IRIX); falls back to C<LOG_AUTH>
1337
1338=item *
1339
8168e71f
SP
1340C<LOG_AUTH> - security/authorization messages
1341
1342=item *
1343
1344C<LOG_AUTHPRIV> - security/authorization messages (private)
1345
1346=item *
1347
a650b841
AT
1348C<LOG_CONSOLE> - C</dev/console> output (FreeBSD); falls back to C<LOG_USER>
1349
1350=item *
1351
4b035b3d 1352C<LOG_CRON> - clock daemons (B<cron> and B<at>)
8168e71f
SP
1353
1354=item *
1355
1356C<LOG_DAEMON> - system daemons without separate facility value
1357
1358=item *
1359
4b035b3d 1360C<LOG_FTP> - FTP daemon
8168e71f
SP
1361
1362=item *
1363
1364C<LOG_KERN> - kernel messages
1365
1366=item *
1367
a650b841 1368C<LOG_INSTALL> - installer subsystem (Mac OS X); falls back to C<LOG_USER>
4b035b3d
SP
1369
1370=item *
1371
a650b841
AT
1372C<LOG_LAUNCHD> - launchd - general bootstrap daemon (Mac OS X);
1373falls back to C<LOG_DAEMON>
1374
1375=item *
1376
1377C<LOG_LFMT> - logalert facility; falls back to C<LOG_USER>
4b035b3d
SP
1378
1379=item *
1380
8168e71f
SP
1381C<LOG_LOCAL0> through C<LOG_LOCAL7> - reserved for local use
1382
1383=item *
1384
1385C<LOG_LPR> - line printer subsystem
1386
1387=item *
1388
1389C<LOG_MAIL> - mail subsystem
1390
1391=item *
1392
a650b841 1393C<LOG_NETINFO> - NetInfo subsystem (Mac OS X); falls back to C<LOG_DAEMON>
4b035b3d
SP
1394
1395=item *
1396
8168e71f
SP
1397C<LOG_NEWS> - USENET news subsystem
1398
1399=item *
1400
a650b841
AT
1401C<LOG_NTP> - NTP subsystem (FreeBSD, NetBSD); falls back to C<LOG_DAEMON>
1402
1403=item *
1404
1405C<LOG_RAS> - Remote Access Service (VPN / PPP) (Mac OS X);
1406falls back to C<LOG_AUTH>
4b035b3d
SP
1407
1408=item *
1409
a650b841
AT
1410C<LOG_REMOTEAUTH> - remote authentication/authorization (Mac OS X);
1411falls back to C<LOG_AUTH>
1412
1413=item *
1414
1415C<LOG_SECURITY> - security subsystems (firewalling, etc.) (FreeBSD);
1416falls back to C<LOG_AUTH>
4b035b3d
SP
1417
1418=item *
1419
8168e71f
SP
1420C<LOG_SYSLOG> - messages generated internally by B<syslogd>
1421
1422=item *
1423
1424C<LOG_USER> (default) - generic user-level messages
1425
1426=item *
1427
1428C<LOG_UUCP> - UUCP subsystem
1429
1430=back
1431
1432
1433=head2 Levels
1434
1435=over 4
1436
1437=item *
1438
1439C<LOG_EMERG> - system is unusable
1440
1441=item *
1442
1443C<LOG_ALERT> - action must be taken immediately
1444
1445=item *
1446
1447C<LOG_CRIT> - critical conditions
1448
1449=item *
1450
942974c1 1451C<LOG_ERR> - error conditions
8168e71f
SP
1452
1453=item *
1454
1455C<LOG_WARNING> - warning conditions
1456
1457=item *
1458
1459C<LOG_NOTICE> - normal, but significant, condition
1460
1461=item *
1462
1463C<LOG_INFO> - informational message
1464
1465=item *
1466
1467C<LOG_DEBUG> - debug-level message
1468
1469=back
1470
1471
1472=head1 DIAGNOSTICS
1473
a650b841 1474=over
8168e71f 1475
a650b841 1476=item C<Invalid argument passed to setlogsock>
8168e71f
SP
1477
1478B<(F)> You gave C<setlogsock()> an invalid value for C<$sock_type>.
1479
35a209d1 1480=item C<eventlog passed to setlogsock, but no Win32 API available>
a650b841
AT
1481
1482B<(W)> You asked C<setlogsock()> to use the Win32 event logger but the
1483operating system running the program isn't Win32 or does not provides Win32
35a209d1 1484compatible facilities.
a650b841
AT
1485
1486=item C<no connection to syslog available>
8168e71f
SP
1487
1488B<(F)> C<syslog()> failed to connect to the specified socket.
1489
a650b841 1490=item C<stream passed to setlogsock, but %s is not writable>
8168e71f 1491
942974c1 1492B<(W)> You asked C<setlogsock()> to use a stream socket, but the given
8168e71f
SP
1493path is not writable.
1494
a650b841 1495=item C<stream passed to setlogsock, but could not find any device>
8168e71f 1496
942974c1 1497B<(W)> You asked C<setlogsock()> to use a stream socket, but didn't
8168e71f
SP
1498provide a path, and C<Sys::Syslog> was unable to find an appropriate one.
1499
a650b841 1500=item C<tcp passed to setlogsock, but tcp service unavailable>
8168e71f 1501
942974c1 1502B<(W)> You asked C<setlogsock()> to use a TCP socket, but the service
8168e71f
SP
1503is not available on the system.
1504
a650b841 1505=item C<syslog: expecting argument %s>
8168e71f
SP
1506
1507B<(F)> You forgot to give C<syslog()> the indicated argument.
1508
a650b841 1509=item C<syslog: invalid level/facility: %s>
8168e71f 1510
6e4ef777 1511B<(F)> You specified an invalid level or facility.
8168e71f 1512
a650b841 1513=item C<syslog: too many levels given: %s>
8168e71f
SP
1514
1515B<(F)> You specified too many levels.
1516
a650b841 1517=item C<syslog: too many facilities given: %s>
8168e71f
SP
1518
1519B<(F)> You specified too many facilities.
1520
a650b841 1521=item C<syslog: level must be given>
8168e71f
SP
1522
1523B<(F)> You forgot to specify a level.
1524
a650b841 1525=item C<udp passed to setlogsock, but udp service unavailable>
8168e71f 1526
942974c1 1527B<(W)> You asked C<setlogsock()> to use a UDP socket, but the service
8168e71f
SP
1528is not available on the system.
1529
a650b841 1530=item C<unix passed to setlogsock, but path not available>
8168e71f 1531
942974c1 1532B<(W)> You asked C<setlogsock()> to use a UNIX socket, but C<Sys::Syslog>
8168e71f
SP
1533was unable to find an appropriate an appropriate device.
1534
1535=back
1536
1537
06fd9d7a
CBW
1538=head1 HISTORY
1539
1540C<Sys::Syslog> is a core module, part of the standard Perl distribution
1541since 1990. At this time, modules as we know them didn't exist, the
1542Perl library was a collection of F<.pl> files, and the one for sending
1543syslog messages with was simply F<lib/syslog.pl>, included with Perl 3.0.
1544It was converted as a module with Perl 5.0, but had a version number
1545only starting with Perl 5.6. Here is a small table with the matching
1546Perl and C<Sys::Syslog> versions.
1547
1548 Sys::Syslog Perl
1549 ----------- ----
33f804f6
SH
1550 undef 5.0.0 ~ 5.5.4
1551 0.01 5.6.*
06fd9d7a
CBW
1552 0.03 5.8.0
1553 0.04 5.8.1, 5.8.2, 5.8.3
1554 0.05 5.8.4, 5.8.5, 5.8.6
1555 0.06 5.8.7
1556 0.13 5.8.8
1557 0.22 5.10.0
33f804f6
SH
1558 0.27 5.8.9, 5.10.1 ~ 5.14.2
1559 0.29 5.16.0, 5.16.1
06fd9d7a
CBW
1560
1561
5be1dfc7
HF
1562=head1 SEE ALSO
1563
848ca32c
CBW
1564=head2 Other modules
1565
1566L<Log::Log4perl> - Perl implementation of the Log4j API
1567
1568L<Log::Dispatch> - Dispatches messages to one or more outputs
1569
1570L<Log::Report> - Report a problem, with exceptions and language support
1571
a650b841
AT
1572=head2 Manual Pages
1573
5be1dfc7
HF
1574L<syslog(3)>
1575
6e4ef777
SP
1576SUSv3 issue 6, IEEE Std 1003.1, 2004 edition,
1577L<http://www.opengroup.org/onlinepubs/000095399/basedefs/syslog.h.html>
1578
1579GNU C Library documentation on syslog,
1580L<http://www.gnu.org/software/libc/manual/html_node/Syslog.html>
1581
1582Solaris 10 documentation on syslog,
f93f88eb
AT
1583L<http://docs.sun.com/app/docs/doc/816-5168/syslog-3c?a=view>
1584
1585Mac OS X documentation on syslog,
1586L<http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/syslog.3.html>
6e4ef777 1587
f93f88eb
AT
1588IRIX 6.5 documentation on syslog,
1589L<http://techpubs.sgi.com/library/tpl/cgi-bin/getdoc.cgi?coll=0650&db=man&fname=3c+syslog>
a650b841 1590
6e4ef777 1591AIX 5L 5.3 documentation on syslog,
d329efa2 1592L<http://publib.boulder.ibm.com/infocenter/pseries/v5r3/index.jsp?topic=/com.ibm.aix.basetechref/doc/basetrf2/syslog.htm>
6e4ef777
SP
1593
1594HP-UX 11i documentation on syslog,
f93f88eb 1595L<http://docs.hp.com/en/B2355-60130/syslog.3C.html>
6e4ef777
SP
1596
1597Tru64 5.1 documentation on syslog,
1598L<http://h30097.www3.hp.com/docs/base_doc/DOCUMENTATION/V51_HTML/MAN/MAN3/0193____.HTM>
1599
1600Stratus VOS 15.1,
1601L<http://stratadoc.stratus.com/vos/15.1.1/r502-01/wwhelp/wwhimpl/js/html/wwhelp.htm?context=r502-01&file=ch5r502-01bi.html>
1602
a650b841
AT
1603=head2 RFCs
1604
6e4ef777
SP
1605I<RFC 3164 - The BSD syslog Protocol>, L<http://www.faqs.org/rfcs/rfc3164.html>
1606-- Please note that this is an informational RFC, and therefore does not
1607specify a standard of any kind.
1608
1609I<RFC 3195 - Reliable Delivery for syslog>, L<http://www.faqs.org/rfcs/rfc3195.html>
1610
a650b841
AT
1611=head2 Articles
1612
04f98b29
RGS
1613I<Syslogging with Perl>, L<http://lexington.pm.org/meetings/022001.html>
1614
a650b841 1615=head2 Event Log
8168e71f 1616
a650b841
AT
1617Windows Event Log,
1618L<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wes/wes/windows_event_log.asp>
5be1dfc7 1619
a650b841
AT
1620
1621=head1 AUTHORS & ACKNOWLEDGEMENTS
1622
1623Tom Christiansen E<lt>F<tchrist (at) perl.com>E<gt> and Larry Wall
1624E<lt>F<larry (at) wall.org>E<gt>.
150b260b
GS
1625
1626UNIX domain sockets added by Sean Robinson
a650b841
AT
1627E<lt>F<robinson_s (at) sc.maricopa.edu>E<gt> with support from Tim Bunce
1628E<lt>F<Tim.Bunce (at) ig.co.uk>E<gt> and the C<perl5-porters> mailing list.
150b260b
GS
1629
1630Dependency on F<syslog.ph> replaced with XS code by Tom Hughes
a650b841 1631E<lt>F<tom (at) compton.nu>E<gt>.
5be1dfc7 1632
a650b841 1633Code for C<constant()>s regenerated by Nicholas Clark E<lt>F<nick (at) ccl4.org>E<gt>.
23642f4b
NW
1634
1635Failover to different communication modes by Nick Williams
a650b841
AT
1636E<lt>F<Nick.Williams (at) morganstanley.com>E<gt>.
1637
1638Extracted from core distribution for publishing on the CPAN by
1639SE<eacute>bastien Aperghis-Tramoni E<lt>sebastien (at) aperghis.netE<gt>.
b903fcff 1640
89c3c464 1641XS code for using native C functions borrowed from C<L<Unix::Syslog>>,
a650b841 1642written by Marcus Harnisch E<lt>F<marcus.harnisch (at) gmx.net>E<gt>.
89c3c464 1643
a650b841
AT
1644Yves Orton suggested and helped for making C<Sys::Syslog> use the native
1645event logger under Win32 systems.
1646
1647Jerry D. Hedden and Reini Urban provided greatly appreciated help to
1648debug and polish C<Sys::Syslog> under Cygwin.
8168e71f
SP
1649
1650
1651=head1 BUGS
1652
1653Please report any bugs or feature requests to
a650b841 1654C<bug-sys-syslog (at) rt.cpan.org>, or through the web interface at
35a209d1 1655L<http://rt.cpan.org/Public/Dist/Display.html?Name=Sys-Syslog>.
8168e71f
SP
1656I will be notified, and then you'll automatically be notified of progress on
1657your bug as I make changes.
1658
1659
1660=head1 SUPPORT
1661
1662You can find documentation for this module with the perldoc command.
1663
1664 perldoc Sys::Syslog
1665
1666You can also look for information at:
1667
1668=over 4
1669
1670=item * AnnoCPAN: Annotated CPAN documentation
1671
1672L<http://annocpan.org/dist/Sys-Syslog>
1673
1674=item * CPAN Ratings
1675
1676L<http://cpanratings.perl.org/d/Sys-Syslog>
1677
1678=item * RT: CPAN's request tracker
1679
06fd9d7a 1680L<http://rt.cpan.org/Dist/Display.html?Queue=Sys-Syslog>
8168e71f
SP
1681
1682=item * Search CPAN
1683
6e4ef777
SP
1684L<http://search.cpan.org/dist/Sys-Syslog/>
1685
33f804f6 1686=item * MetaCPAN
6e4ef777 1687
33f804f6 1688L<https://metacpan.org/module/Sys::Syslog>
6e4ef777
SP
1689
1690=item * Perl Documentation
1691
1692L<http://perldoc.perl.org/Sys/Syslog.html>
8168e71f
SP
1693
1694=back
1695
1696
35a209d1
AT
1697=head1 COPYRIGHT
1698
33f804f6 1699Copyright (C) 1990-2012 by Larry Wall and others.
35a209d1
AT
1700
1701
8168e71f
SP
1702=head1 LICENSE
1703
1704This program is free software; you can redistribute it and/or modify it
1705under the same terms as Perl itself.
1706
5be1dfc7 1707=cut
a650b841
AT
1708
1709=begin comment
1710
1711Notes for the future maintainer (even if it's still me..)
1712- - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1713
1714Using Google Code Search, I search who on Earth was relying on $host being
1715public. It found 5 hits:
1716
1717* First was inside Indigo Star Perl2exe documentation. Just an old version
1718of Sys::Syslog.
1719
1720
1721* One real hit was inside DalWeathDB, a weather related program. It simply
1722does a
1723
1724 $Sys::Syslog::host = '127.0.0.1';
1725
1726- L<http://www.gallistel.net/nparker/weather/code/>
1727
1728
1729* Two hits were in TPC, a fax server thingy. It does a
1730
1731 $Sys::Syslog::host = $TPC::LOGHOST;
1732
1733but also has this strange piece of code:
1734
1735 # work around perl5.003 bug
1736 sub Sys::Syslog::hostname {}
1737
1738I don't know what bug the author referred to.
1739
1740- L<http://www.tpc.int/>
a650b841
AT
1741- L<ftp://ftp-usa.tpc.int/pub/tpc/server/UNIX/>
1742
1743
1744* Last hit was in Filefix, which seems to be a FIDOnet mail program (!).
1745This one does not use $host, but has the following piece of code:
1746
1747 sub Sys::Syslog::hostname
1748 {
1749 use Sys::Hostname;
1750 return hostname;
1751 }
1752
1753I guess this was a more elaborate form of the previous bit, maybe because
1754of a bug in Sys::Syslog back then?
1755
1756- L<ftp://ftp.kiae.su/pub/unix/fido/>
1757
d329efa2
AT
1758
1759Links
1760-----
f93f88eb
AT
1761Linux Fast-STREAMS
1762- L<http://www.openss7.org/streams.html>
1763
d329efa2
AT
1764II12021: SYSLOGD HOWTO TCPIPINFO (z/OS, OS/390, MVS)
1765- L<http://www-1.ibm.com/support/docview.wss?uid=isg1II12021>
1766
1767Getting the most out of the Event Viewer
1768- L<http://www.codeproject.com/dotnet/evtvwr.asp?print=true>
1769
1770Log events to the Windows NT Event Log with JNI
1771- L<http://www.javaworld.com/javaworld/jw-09-2001/jw-0928-ntmessages.html>
1772
a650b841 1773=end comment
d329efa2 1774